Exemplo n.º 1
0
pcap_t *
pcap_open_live_extended(const char *source, int snaplen, int promisc, int to_ms, int rfmon, char *errbuf)
{
    pcap_t *p;
    int status;
    
    p = pcap_create(source, errbuf);
    if (p == NULL)
        return (NULL);
    status = pcap_set_snaplen(p, snaplen);
    if (status < 0)
        goto fail;
    status = pcap_set_promisc(p, promisc);
    if (status < 0)
        goto fail;
    status = pcap_set_timeout(p, to_ms);
    if (status < 0)
        goto fail;
    if(pcap_can_set_rfmon(p) == 1) {
        status = pcap_set_rfmon(p, rfmon);
        if (status < 0)
            goto fail;
    }
    status = pcap_activate(p);
    if (status < 0)
        goto fail;
    return (p);
    
fail:
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source, pcap_geterr(p));
    pcap_close(p);
    return (NULL);
}
Exemplo n.º 2
0
pcap_t *
pcap_create(const char *device, char *ebuf)
{
	pcap_t *p;

	p = calloc(1, sizeof(*p));
	if (p == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
		    pcap_strerror(errno));
		return (NULL);
	}
	p->fd = -1;	/* not opened yet */

	p->opt.source = strdup(device);
	if (p->opt.source == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
		    pcap_strerror(errno));
		free(p);
		return (NULL);
	}

	/* put in some defaults*/
	pcap_set_timeout(p, 0);
	pcap_set_snaplen(p, 65535);	/* max packet size */
	p->opt.promisc = 0;
	p->opt.buffer_size = 0;
	return (p);
}
Exemplo n.º 3
0
static pcap_t* open_pcap_dev(const char* ifname, int frameSize, char* errbuf)
{
	pcap_t* handle = pcap_create(ifname, errbuf);
	if (handle) {
		int err;
		err = pcap_set_snaplen(handle, frameSize);
		if (err) AVB_LOGF_WARNING("Cannot set snap len %d", err);

		err = pcap_set_promisc(handle, 1);
		if (err) AVB_LOGF_WARNING("Cannot set promisc %d", err);

		err = pcap_set_immediate_mode(handle, 1);
		if (err) AVB_LOGF_WARNING("Cannot set immediate mode %d", err);

		// we need timeout (here 100ms) otherwise we could block for ever
		err = pcap_set_timeout(handle, 100);
		if (err) AVB_LOGF_WARNING("Cannot set timeout %d", err);

		err = pcap_set_tstamp_precision(handle, PCAP_TSTAMP_PRECISION_NANO);
		if (err) AVB_LOGF_WARNING("Cannot set tstamp nano precision %d", err);

		err = pcap_set_tstamp_type(handle, PCAP_TSTAMP_ADAPTER_UNSYNCED);
		if (err) AVB_LOGF_WARNING("Cannot set tstamp adapter unsynced %d", err);

		err = pcap_activate(handle);
		if (err) AVB_LOGF_WARNING("Cannot activate pcap %d", err);
	}
	return handle;
}
Exemplo n.º 4
0
void capture(char *dev) {
  pcap_t *pcap;
  char errbuf[PCAP_ERRBUF_SIZE];
  struct pcap_pkthdr header;	/* The header that pcap gives us */
  const u_char *packet;		/* The actual packet */

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

  pcap = pcap_create(dev, errbuf);
  pcap_set_rfmon(pcap, 1);
  pcap_set_promisc(pcap, 1);
  pcap_set_buffer_size(pcap, 1 * 1024 * 1024);
  pcap_set_timeout(pcap, 1);
  pcap_set_snaplen(pcap, 16384);
  pcap_activate(pcap);    
  if(DLT_IEEE802_11_RADIO == pcap_datalink(pcap)) {
    pcap_loop(pcap, 0, got_packet, 0);
  } else {
    fprintf(stderr, "Could not initialize a IEEE802_11_RADIO packet capture for interface %s\n", dev);
  }
}
Exemplo n.º 5
0
/*
 * Class:     disy_jnipcap_Pcap
 * Method:    setSnaplen
 * Signature: (JI)I
 */
JNIEXPORT jint JNICALL
Java_disy_jnipcap_Pcap_setSnaplen (JNIEnv *env, jclass jcls, jlong jptr, jint jsnaplen)
{
	pcap_t *p = (pcap_t *) jptr;
	if (p == NULL) return -1;
	return (jint) pcap_set_snaplen (p, (int) jsnaplen);
}
Exemplo n.º 6
0
/* Initializes pcap capture settings and returns a pcap handle on success, NULL on error */
pcap_t *capture_init(char *capture_source) {
    pcap_t *handle = NULL;
    char errbuf[PCAP_ERRBUF_SIZE] = {0};

#ifdef __APPLE__
    // must disassociate from any current AP.  This is the only way.
    pid_t pid = fork();
    if (!pid) {
        char* argv[] = {"/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport", "-z", NULL};
        execve("/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport", argv, NULL);
    }
    int status;
    waitpid(pid, &status, 0);


    handle = pcap_create(capture_source, errbuf);
    if (handle) {
        pcap_set_snaplen(handle, BUFSIZ);
        pcap_set_timeout(handle, 50);
        pcap_set_rfmon(handle, 1);
        pcap_set_promisc(handle, 1);
        int status = pcap_activate(handle);
        if (status)
            cprintf(CRITICAL, "pcap_activate status %d\n", status);
    }
#else
    handle = pcap_open_live(capture_source, BUFSIZ, 1, 0, errbuf);
#endif
    if (!handle) {
        handle = pcap_open_offline(capture_source, errbuf);
    }

    return handle;
}
Exemplo n.º 7
0
static int
tc_pcap_open(pcap_t **pd, char *device, int snap_len, int buf_size)
{
    int    status;
    char   ebuf[PCAP_ERRBUF_SIZE]; 

    *ebuf = '\0';

    *pd = pcap_create(device, ebuf);
    if (*pd == NULL) {
        tc_log_info(LOG_ERR, 0, "pcap create error:%s", ebuf);
        return TC_ERROR;
    }

    status = pcap_set_snaplen(*pd, snap_len);
    if (status != 0) {
        tc_log_info(LOG_ERR, 0, "pcap_set_snaplen error:%s",
                pcap_statustostr(status));
        return TC_ERROR;
    }

    status = pcap_set_promisc(*pd, 0);
    if (status != 0) {
        tc_log_info(LOG_ERR, 0, "pcap_set_promisc error:%s",
                pcap_statustostr(status));
        return TC_ERROR;
    }

    status = pcap_set_timeout(*pd, 1000);
    if (status != 0) {
        tc_log_info(LOG_ERR, 0, "pcap_set_timeout error:%s",
                pcap_statustostr(status));
        return TC_ERROR;
    }

    status = pcap_set_buffer_size(*pd, buf_size);
    if (status != 0) {
        tc_log_info(LOG_ERR, 0, "pcap_set_buffer_size error:%s",
                pcap_statustostr(status));
        return TC_ERROR;
    }

    tc_log_info(LOG_NOTICE, 0, "pcap_set_buffer_size:%d", buf_size);

    status = pcap_activate(*pd);
    if (status < 0) {
        tc_log_info(LOG_ERR, 0, "pcap_activate error:%s",
                pcap_statustostr(status));
        return TC_ERROR;

    } else if (status > 0) {
        tc_log_info(LOG_WARN, 0, "pcap activate warn:%s", 
                pcap_statustostr(status));
    }

    return TC_OK;
}
Exemplo n.º 8
0
int myPcapCatchAndAnaly() {
    int status=0;
    int header_type;
    char errbuf[PCAP_ERRBUF_SIZE];
    /* openwrt && linux */
    char *dev=(char *)"wlan0";
    /* mac os */
    //test
    // char* dev=(char *)"en0";
    handle=pcap_create(dev,errbuf); //为抓取器打开一个句柄

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

    // 由于在该路由器测试时,发现在该openwrt系统上不支持libpcap设置monitor模式,在激活的时候会产生错误
    // 将采用手动设置并检测网卡是否为monitor模式

    // if(pcap_can_set_rfmon(handle)) {
    //      //查看是否能设置为监控模式
    //     printf("Device %s can be opened in monitor mode\n",dev);
    // }
    // else {
    //     printf("Device %s can't be opened in monitor mode!!!\n",dev);
    // }

    // 若是mac os系统,则可以支持
    // test
    if(pcap_set_rfmon(handle,1)!=0) {
        fprintf(stderr, "Device %s couldn't be opened in monitor mode\n", dev);
        return 0;
    } else {
        printf("Device %s has been opened in monitor mode\n", dev);
    }

    pcap_set_promisc(handle,0);   //不设置混杂模式
    pcap_set_snaplen(handle,65535);   //设置最大捕获包的长度
    status=pcap_activate(handle);   //激活

    if(status!=0) {
        pcap_perror(handle,(char*)"pcap error: ");
        return 0;
    }

    header_type=pcap_datalink(handle);  //返回链路层的类型
    if(header_type!=DLT_IEEE802_11_RADIO) {
        printf("Error: incorrect header type - %d\n",header_type);
        return 0;
    }

    int id = 0;
    pcap_loop(handle, -1, getPacket, (u_char*)&id);

    return 1;
}
Exemplo n.º 9
0
NAPCapHandle *
na_pcap_open (const char *iface,
              GError     **error)
{
  char errbuf[PCAP_ERRBUF_SIZE];

  pcap_t *pcap_handle = pcap_create (iface, errbuf);

  if (pcap_handle == NULL)
    {
      g_set_error (error,
                   NA_PCAP_ERROR,
                   NA_PCAP_ERROR_OPEN,
                   "pcap failed to create handle for iface: %s", errbuf);
      return NULL;
    }

  pcap_set_snaplen (pcap_handle, PCAP_SNAPLEN);
  pcap_set_timeout (pcap_handle, 100);

  if (pcap_activate (pcap_handle) != 0)
    {
      g_set_error (error,
                   NA_PCAP_ERROR,
                   NA_PCAP_ERROR_OPEN,
                   "pcap failed to activate handle for iface");
      return NULL;
    }

  NAPCapHandle *handle = g_new0 (NAPCapHandle, 1);

  handle->pcap_handle = pcap_handle;
  handle->iface = iface;
  handle->linktype = pcap_datalink (pcap_handle);

  switch (handle->linktype)
    {
    case (DLT_EN10MB):
      g_debug ("Ethernet link detected");
      break;
    case (DLT_PPP):
      g_debug ("PPP link detected");
      break;
    case (DLT_LINUX_SLL):
      g_debug ("Linux Cooked Socket link detected");
      break;
    default:
      g_debug ("No PPP or Ethernet link: %d", handle->linktype);
      break;
    }

  return handle;
}
Exemplo n.º 10
0
pcap_t *
pcap_open_live(const char *source, int snaplen, int promisc, int to_ms,
    char *errbuf)
{
	pcap_t *p;
	int status;

	p = pcap_create(source, errbuf);
	if (p == NULL)
		return (NULL);
	status = pcap_set_snaplen(p, snaplen);
	if (status < 0)
		goto fail;
	status = pcap_set_promisc(p, promisc);
	if (status < 0)
		goto fail;
	status = pcap_set_timeout(p, to_ms);
	if (status < 0)
		goto fail;
	/*
	 * Mark this as opened with pcap_open_live(), so that, for
	 * example, we show the full list of DLT_ values, rather
	 * than just the ones that are compatible with capturing
	 * when not in monitor mode.  That allows existing applications
	 * to work the way they used to work, but allows new applications
	 * that know about the new open API to, for example, find out the
	 * DLT_ values that they can select without changing whether
	 * the adapter is in monitor mode or not.
	 */
	p->oldstyle = 1;
	status = pcap_activate(p);
	if (status < 0)
		goto fail;
	return (p);
fail:
	if (status == PCAP_ERROR)
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
		    p->errbuf);
	else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
	    status == PCAP_ERROR_PERM_DENIED ||
	    status == PCAP_ERROR_PROMISC_PERM_DENIED)
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
		    pcap_statustostr(status), p->errbuf);
	else
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
		    pcap_statustostr(status));
	pcap_close(p);
	return (NULL);
}
Exemplo n.º 11
0
static void prep_pcap_handle(pcap_t *handle) {
    int err;

    err = pcap_set_rfmon(handle, options.rfmon);
    if(err)
        die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);

    err = pcap_set_promisc(handle, options.promisc);
    if(err)
        die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);

    err = pcap_set_snaplen(handle, options.snaplen);
    if(err)
        die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);

    err = pcap_set_timeout(handle, options.read_timeout);
    if(err)
        die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);

    if(options.buffer_size > 0) {
        err = pcap_set_buffer_size(handle, options.buffer_size);
        if(err)
            die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);
    }

    if(options.tstamp_type != PCAP_ERROR) {
        err = pcap_set_tstamp_type(handle, options.tstamp_type);
        if(err == PCAP_ERROR_ACTIVATED)
            die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);
        else if(err == PCAP_ERROR_CANTSET_TSTAMP_TYPE)
            die(0, "pcap_set_tstamp_type(): Device does not support setting the timestamp");
        else if(err == PCAP_WARNING_TSTAMP_TYPE_NOTSUP)
            plog(0, "pcap_set_tstamp_type(): Device does not support specified tstamp type");
    }

    if(options.tstamp_nano) {
        err = pcap_set_tstamp_precision(handle, PCAP_TSTAMP_PRECISION_NANO);
        if(err == PCAP_ERROR_ACTIVATED)
            die(0, "DEBUG: pcap handle should not be activated at %s:%d", __FILE__, __LINE__);
        else if(err == PCAP_ERROR_TSTAMP_PRECISION_NOTSUP)
            die(0, "pcap_set_tstamp_precision(): Device does not support nanosecond precision");
    }

    if(options.linktype != PCAP_ERROR) {
        err = pcap_set_datalink(handle, options.linktype);
        if(err)
            die(0, "pcap_set_datalink(): %s", pcap_geterr(handle));
    }
}
Exemplo n.º 12
0
CAMLprim value
stub_pcap_set_snaplen (value p_p, value p_size)
{
	int size;
	pcap_t *p;

	p = (pcap_t *) p_p;
	size = Int_val (p_size);

	if (pcap_set_snaplen (p, size)) {
		raise_error ("Cannot set snapshot length. Already activated");
	}

	return Val_unit;
}
Exemplo n.º 13
0
Arquivo: init.c Projeto: fchiba/tcpeek
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)
		);
	}
}
Exemplo n.º 14
0
static pcap_t* _kqtime_newPCap(const char* source, const char* filter_expression,
        pcap_direction_t pcapdir, int snaplen) {
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program filter;

	const char* pcap_source = source ? source : NULL;
	pcap_t* handle = pcap_create(pcap_source, errbuf);
	if(!handle) {
		log("kqtime: error obtaining pcap handle: %s\n", errbuf);
		return NULL;
	}

	if(pcap_set_snaplen(handle, 65536) != 0) {
		log("kqtime: error setting pcap snaplen %d\n", snaplen);
		pcap_close(handle);
		return NULL;
	}

	if(pcap_activate(handle) != 0) {
		log("kqtime: error activating capture device: %s\n", pcap_geterr(handle));
		pcap_close(handle);
		return NULL;
	}

	if(pcap_setdirection(handle, pcapdir) != 0) {
		log("kqtime: error setting capture direction: %s\n", pcap_geterr(handle));
		pcap_close(handle);
		return NULL;
	}

	const char* pcap_filter_expression = filter_expression ? filter_expression : "tcp and not port ssh";
	if(pcap_compile(handle, &filter, pcap_filter_expression,
			0, PCAP_NETMASK_UNKNOWN) != 0) {
		log("kqtime: error compiling filter: %s\n", pcap_geterr(handle));
		pcap_close(handle);
		return NULL;
	}

	if(pcap_setfilter(handle, &filter) < 0) {
		log("kqtime: error setting filter: %s\n", pcap_geterr(handle));
		pcap_freecode(&filter);
		pcap_close(handle);
		return NULL;
	}

	return handle;
}
Exemplo n.º 15
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;
}
Exemplo n.º 16
0
pcap_t *
reader_libpcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf)
{
    pcap_t *p;
    int status;

    p = pcap_create(source, errbuf);
    if (p == NULL)
        return (NULL);
    status = pcap_set_snaplen(p, snaplen);
    if (status < 0)
        goto fail;
    status = pcap_set_promisc(p, promisc);
    if (status < 0)
        goto fail;
    status = pcap_set_timeout(p, to_ms);
    if (status < 0)
        goto fail;
    status = pcap_set_buffer_size(p, config.pcapBufferSize);
    if (status < 0)
        goto fail;
    status = pcap_activate(p);
    if (status < 0)
        goto fail;
    status = pcap_setnonblock(p, TRUE, errbuf);
    if (status < 0) {
        pcap_close(p);
        return (NULL);
    }

    return (p);
fail:
    if (status == PCAP_ERROR)
        snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
            pcap_geterr(p));
    else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
        status == PCAP_ERROR_PERM_DENIED)
        snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
            pcap_statustostr(status), pcap_geterr(p));
    else
        snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
            pcap_statustostr(status));
    pcap_close(p);
    return (NULL);
}
//------------------------------------------------------------------------------
static pcap_t* startPcap(void)
{
    pcap_t* pPcapInst = NULL;
    char    errorMessage[PCAP_ERRBUF_SIZE];

    // Create a pcap live capture handle
    pPcapInst = pcap_create(edrvInstance_l.initParam.pDevName, errorMessage);
    if (pPcapInst == NULL)
    {
        DEBUG_LVL_ERROR_TRACE("%s() Error!! Can't open pcap: %s\n", __func__, errorMessage);
    }

    // Set snapshot length for a not-yet-activated capture handle
    if (pcap_set_snaplen(pPcapInst, 65535) < 0)
    {
        DEBUG_LVL_ERROR_TRACE("%s() couldn't set PCAP snap length\n", __func__);
    }

    // Set promiscuous mode for a not-yet-activated capture handle
    if (pcap_set_promisc(pPcapInst, 1) < 0)
    {
        DEBUG_LVL_ERROR_TRACE("%s() couldn't set PCAP promiscuous mode\n", __func__);
    }

// Pcap immediate mode only supported by libpcap >=1.5.0
#ifdef PCAP_ERROR_TSTAMP_PRECISION_NOTSUP
    // Set immediate mode for a not-yet-activated capture handle
    if (pcap_set_immediate_mode(pPcapInst, 1) < 0)
    {
        DEBUG_LVL_ERROR_TRACE("%s() couldn't set PCAP immediate mode\n", __func__);
    }
#endif

    // Activate the pcap capture handle with the previous parameters
    if (pcap_activate(pPcapInst) < 0)
    {
        DEBUG_LVL_ERROR_TRACE("%s() couldn't activate PCAP\n", __func__);
    }
    return pPcapInst;
}
Exemplo n.º 18
0
void
setup_pcap(void) {
	char errbuf[PCAP_ERRBUF_SIZE];
	int rc;

	pcap = pcap_create(iface, errbuf);
	if (pcap == NULL) {
		fprintf(stderr, "%s: unable to add pcap interface output %s: %s\n",
			argv_program, iface, errbuf);
		exit(EXIT_FAILURE);
	}

	rc = pcap_set_snaplen(pcap, 60);
	if (rc != 0) {
		fprintf(stderr, "%s: pcap_set_snaplen() failed\n", argv_program);
		exit(EXIT_FAILURE);
	}

	rc = pcap_activate(pcap);
	if (rc != 0) {
		fprintf(stderr, "%s: pcap_activate() failed\n", argv_program);
		exit(EXIT_FAILURE);
	}
}
Exemplo n.º 19
0
static PyObject *ppcap_set_snaplen(ppcap *self,
                                   PyObject *args)
{
    int snaplen;
    int retval;

    if (!PyArg_ParseTuple(args, "i", &snaplen))
        return NULL;
    if (!ppcap_isset_handle(self->handle)) {
        PyErr_SetString(PyExc_Ppcap, "pcap handle is not created");
        return NULL;
    }
    if (snaplen < MIN_SNAPLEN) {
        PyErr_Format(PyExc_Ppcap, "snaplen must be >= %d",
                     MIN_SNAPLEN);
        return NULL;
    }
    retval = pcap_set_snaplen(self->handle, snaplen);
    if (retval == PCAP_ERROR_ACTIVATED) {
        PyErr_Format(PyExc_Ppcap, "%s", pcap_geterr(self->handle));
        return NULL;
    }
    Py_RETURN_NONE;
}
Exemplo n.º 20
0
bool PcapActivity::openLive()
{
    Poco::Buffer<char> errBuff(PCAP_ERRBUF_SIZE);
    _pcap = pcap_create(_device.c_str(), errBuff.begin());
    if (_pcap == nullptr) {
        _logger.warning("Couldn't open device %s: %s", _device, std::string(errBuff.begin()));
        return false;
    }
    int status = pcap_set_snaplen(_pcap, 1500);
    if (status < 0) {
        _logger.warning("Can't set pcap snaplen: %s", std::string(pcap_strerror(status)));
    }
    status = pcap_set_promisc(_pcap, 1);
    if (status < 0) {
        _logger.warning("Can't set pcap promiscuous mode: %s", std::string(pcap_strerror(status)));
    }
    status = pcap_set_timeout(_pcap, 2500);
    if (status < 0) {
        _logger.warning("Can't set pcap timeout: %s", std::string(pcap_strerror(status)));
    }
#ifdef POCO_OS_FAMILY_UNIX
    status = pcap_set_buffer_size(_pcap, 2097152); //2MB
#else
    status = pcap_setbuff(_pcap, 2097152); //2MB
#endif
    if (status < 0) {
        _logger.warning("Can't set pcap buffer size: %s", std::string(pcap_strerror(status)));
    }
    status = pcap_activate(_pcap);
    if (status < 0) {

        _logger.warning("Couldn't activate device %s: %s", _device, std::string(pcap_strerror(status)));
        return false;
    }
    return true;
}
Exemplo n.º 21
0
void pcaplistener::initInterface()
{
    char errbuf[PCAP_ERRBUF_SIZE];

    if(pcap_lookupnet(listenInterface.c_str(), &net, &mask, errbuf))
    {
        fprintf(stderr, "Failed to look up netmask: %s", errbuf);
        exit(0);
    }
    if(!(pcap = pcap_create(listenInterface.c_str(), errbuf)))
    {
        fprintf(stderr, "Failed to create interface source: %s", errbuf);
        exit(0);
    }
    if(pcap_set_snaplen(pcap, SNAPLEN))
    {
        fprintf(stderr, "Failed to set pcap snapshot length: %s", errbuf);
        exit(0);
    }
    if(pcap_set_promisc(pcap, 1))
    {
        fprintf(stderr, "Failed to set interface to promiscuous mode: %s", errbuf);
        exit(0);
    }
    if(pcap_set_timeout(pcap, READ_TIMEOUT_MS))
    {
        fprintf(stderr, "Failed to set pcap timeout: %s", errbuf);
        exit(0);
    }
    if(pcap_activate(pcap))
    {
        fprintf(stderr, "Failed to activate pcap: %s", errbuf);
        exit(0);
    }
    fexpr = "(host 0.0.0.1)";
}
Exemplo n.º 22
0
int main(int argc, char** argv)
{
    int          ret = 0;
    int          hadBadPacket = 0;
	int		     inum;
	int		     port;
    int          saveFile = 0;
	int		     i = 0;
    int          frame = ETHER_IF_FRAME_LEN; 
    char         err[PCAP_ERRBUF_SIZE];
	char         filter[32];
	const char  *server = NULL;
	struct       bpf_program fp;
	pcap_if_t   *d;
	pcap_addr_t *a;

    signal(SIGINT, sig_handler);

#ifndef _WIN32
    ssl_InitSniffer();   /* dll load on Windows */
#endif
    ssl_Trace("./tracefile.txt", err);

    if (argc == 1) {
        /* normal case, user chooses device and port */

	    if (pcap_findalldevs(&alldevs, err) == -1)
		    err_sys("Error in pcap_findalldevs");

	    for (d = alldevs; d; d=d->next) {
		    printf("%d. %s", ++i, d->name);
		    if (d->description)
			    printf(" (%s)\n", d->description);
		    else
			    printf(" (No description available)\n");
	    }

	    if (i == 0)
		    err_sys("No interfaces found! Make sure pcap or WinPcap is"
                    " installed correctly and you have sufficient permissions");

	    printf("Enter the interface number (1-%d): ", i);
	    ret = scanf("%d", &inum);
        if (ret != 1)
            printf("scanf port failed\n");

	    if (inum < 1 || inum > i)
		    err_sys("Interface number out of range");

	    /* Jump to the selected adapter */
	    for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);

	    pcap = pcap_create(d->name, err);

        if (pcap == NULL) printf("pcap_create failed %s\n", err);

	    /* get an IPv4 address */
	    for (a = d->addresses; a; a = a->next) {
		    switch(a->addr->sa_family)
		    {
			    case AF_INET:
				    server = 
                        iptos(((struct sockaddr_in *)a->addr)->sin_addr.s_addr);
				    printf("server = %s\n", server);
				    break;

                default:
                    break;
		    }
	    }
	    if (server == NULL)
		    err_sys("Unable to get device IPv4 address");

        ret = pcap_set_snaplen(pcap, 65536);
        if (ret != 0) printf("pcap_set_snaplen failed %s\n", pcap_geterr(pcap));

        ret = pcap_set_timeout(pcap, 1000); 
        if (ret != 0) printf("pcap_set_timeout failed %s\n", pcap_geterr(pcap));

        ret = pcap_set_buffer_size(pcap, 1000000); 
        if (ret != 0)
		    printf("pcap_set_buffer_size failed %s\n", pcap_geterr(pcap));

        ret = pcap_set_promisc(pcap, 1); 
        if (ret != 0) printf("pcap_set_promisc failed %s\n", pcap_geterr(pcap));


        ret = pcap_activate(pcap);
        if (ret != 0) printf("pcap_activate failed %s\n", pcap_geterr(pcap));

	    printf("Enter the port to scan: ");
	    ret = scanf("%d", &port);
        if (ret != 1)
            printf("scanf port failed\n");

	    SNPRINTF(filter, sizeof(filter), "tcp and port %d", port);

	    ret = pcap_compile(pcap, &fp, filter, 0, 0);
        if (ret != 0) printf("pcap_compile failed %s\n", pcap_geterr(pcap));

        ret = pcap_setfilter(pcap, &fp);
        if (ret != 0) printf("pcap_setfilter failed %s\n", pcap_geterr(pcap));

        ret = ssl_SetPrivateKey(server, port, "../../certs/server-key.pem",
                               FILETYPE_PEM, NULL, err);
        if (ret != 0) {
            printf("Please run directly from sslSniffer/sslSnifferTest dir\n");
        }

#ifdef HAVE_SNI
        {
            char altName[128];

            printf("Enter alternate SNI: ");
            ret = scanf("%s", altName);

            if (strnlen(altName, 128) > 0) {
                ret = ssl_SetNamedPrivateKey(altName,
                                   server, port, "../../certs/server-key.pem",
                                   FILETYPE_PEM, NULL, err);
                if (ret != 0) {
                    printf("Please run directly from "
                           "sslSniffer/sslSnifferTest dir\n");
                }
            }
        }
#endif
    }
    else if (argc >= 3) {
        saveFile = 1;
        pcap = pcap_open_offline(argv[1], err);
        if (pcap == NULL) {
            printf("pcap_open_offline failed %s\n", err);
            ret = -1;
        }
        else {
            const char* passwd = NULL;
            /* defaults for server and port */
            port = 443;
            server = "127.0.0.1";

            if (argc >= 4)
                server = argv[3];

            if (argc >= 5)
                port = atoi(argv[4]);

            if (argc >= 6)
                passwd = argv[5];

            ret = ssl_SetPrivateKey(server, port, argv[2],
                                    FILETYPE_PEM, passwd, err);
        }
    }
    else {
        /* usage error */
        printf( "usage: ./snifftest or ./snifftest dump pemKey"
                " [server] [port] [password]\n");
        exit(EXIT_FAILURE);
    }

    if (ret != 0)
        err_sys(err);

    if (pcap_datalink(pcap) == DLT_NULL) 
        frame = NULL_IF_FRAME_LEN;

    while (1) {
        static int packetNumber = 0;
        struct pcap_pkthdr header;
        const unsigned char* packet = pcap_next(pcap, &header);
        packetNumber++;
        if (packet) {

            byte data[65535+16384];  /* may have a partial 16k record cached */

            if (header.caplen > 40)  { /* min ip(20) + min tcp(20) */
				packet        += frame;
				header.caplen -= frame;					
            }
            else
                continue;

            ret = ssl_DecodePacket(packet, header.caplen, data, err);
            if (ret < 0) {
                printf("ssl_Decode ret = %d, %s\n", ret, err);
                hadBadPacket = 1;
            }
            if (ret > 0) {
                data[ret] = 0;
				printf("SSL App Data(%d:%d):%s\n", packetNumber, ret, data);
            }
        }
        else if (saveFile)
            break;      /* we're done reading file */
    }
    FreeAll();

    return hadBadPacket ? EXIT_FAILURE : EXIT_SUCCESS;
}
Exemplo n.º 23
0
/**
 * \brief Init function for ReceivePcap.
 *
 * This is a setup function for recieving packets
 * via libpcap. There are two versions of this function
 * depending on the major version of libpcap used.
 * For versions prior to 1.x we use open_pcap_live,
 * for versions 1.x and greater we use pcap_create + pcap_activate.
 *
 * \param tv pointer to ThreadVars
 * \param initdata pointer to the interface passed from the user
 * \param data pointer gets populated with PcapThreadVars
 *
 * \todo Create a general pcap setup function.
 */
TmEcode ReceivePcapThreadInit(ThreadVars *tv, const void *initdata, void **data)
{
    SCEnter();
    PcapIfaceConfig *pcapconfig = (PcapIfaceConfig *)initdata;

    if (initdata == NULL) {
        SCLogError(SC_ERR_INVALID_ARGUMENT, "initdata == NULL");
        SCReturnInt(TM_ECODE_FAILED);
    }

    PcapThreadVars *ptv = SCMalloc(sizeof(PcapThreadVars));
    if (unlikely(ptv == NULL)) {
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }
    memset(ptv, 0, sizeof(PcapThreadVars));

    ptv->tv = tv;

    ptv->livedev = LiveGetDevice(pcapconfig->iface);
    if (ptv->livedev == NULL) {
        SCLogError(SC_ERR_INVALID_VALUE, "Unable to find Live device");
        SCFree(ptv);
        SCReturnInt(TM_ECODE_FAILED);
    }

    SCLogInfo("using interface %s", (char *)pcapconfig->iface);

    if (LiveGetOffload() == 0) {
        (void)GetIfaceOffloading((char *)pcapconfig->iface, 1, 1);
    } else {
        DisableIfaceOffloading(ptv->livedev, 1, 1);
    }

    ptv->checksum_mode = pcapconfig->checksum_mode;
    if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
        SCLogInfo("Running in 'auto' checksum mode. Detection of interface state will require "
                  xstr(CHECKSUM_SAMPLE_COUNT) " packets.");
    }

    /* XXX create a general pcap setup function */
    char errbuf[PCAP_ERRBUF_SIZE];
    ptv->pcap_handle = pcap_create((char *)pcapconfig->iface, errbuf);
    if (ptv->pcap_handle == NULL) {
        if (strlen(errbuf)) {
            SCLogError(SC_ERR_PCAP_CREATE, "Couldn't create a new pcap handler for %s, error %s",
                    (char *)pcapconfig->iface, errbuf);
        } else {
            SCLogError(SC_ERR_PCAP_CREATE, "Couldn't create a new pcap handler for %s",
                    (char *)pcapconfig->iface);
        }
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }

    if (pcapconfig->snaplen == 0) {
        /* We set snaplen if we can get the MTU */
        ptv->pcap_snaplen = GetIfaceMaxPacketSize(pcapconfig->iface);
    } else {
        ptv->pcap_snaplen = pcapconfig->snaplen;
    }
    if (ptv->pcap_snaplen > 0) {
        /* set Snaplen. Must be called before pcap_activate */
        int pcap_set_snaplen_r = pcap_set_snaplen(ptv->pcap_handle, ptv->pcap_snaplen);
        if (pcap_set_snaplen_r != 0) {
            SCLogError(SC_ERR_PCAP_SET_SNAPLEN, "Couldn't set snaplen, error: %s", pcap_geterr(ptv->pcap_handle));
            SCFree(ptv);
            pcapconfig->DerefFunc(pcapconfig);
            SCReturnInt(TM_ECODE_FAILED);
        }
        SCLogInfo("Set snaplen to %d for '%s'", ptv->pcap_snaplen,
                  pcapconfig->iface);
    }

    /* set Promisc, and Timeout. Must be called before pcap_activate */
    int pcap_set_promisc_r = pcap_set_promisc(ptv->pcap_handle, pcapconfig->promisc);
    //printf("ReceivePcapThreadInit: pcap_set_promisc(%p) returned %" PRId32 "\n", ptv->pcap_handle, pcap_set_promisc_r);
    if (pcap_set_promisc_r != 0) {
        SCLogError(SC_ERR_PCAP_SET_PROMISC, "Couldn't set promisc mode, error %s", pcap_geterr(ptv->pcap_handle));
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }

    int pcap_set_timeout_r = pcap_set_timeout(ptv->pcap_handle,LIBPCAP_COPYWAIT);
    //printf("ReceivePcapThreadInit: pcap_set_timeout(%p) returned %" PRId32 "\n", ptv->pcap_handle, pcap_set_timeout_r);
    if (pcap_set_timeout_r != 0) {
        SCLogError(SC_ERR_PCAP_SET_TIMEOUT, "Problems setting timeout, error %s", pcap_geterr(ptv->pcap_handle));
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    }
#ifdef HAVE_PCAP_SET_BUFF
    ptv->pcap_buffer_size = pcapconfig->buffer_size;
    if (ptv->pcap_buffer_size >= 0 && ptv->pcap_buffer_size <= INT_MAX) {
        if (ptv->pcap_buffer_size > 0)
            SCLogInfo("Going to use pcap buffer size of %" PRId32 "", ptv->pcap_buffer_size);

        int pcap_set_buffer_size_r = pcap_set_buffer_size(ptv->pcap_handle,ptv->pcap_buffer_size);
        //printf("ReceivePcapThreadInit: pcap_set_timeout(%p) returned %" PRId32 "\n", ptv->pcap_handle, pcap_set_buffer_size_r);
        if (pcap_set_buffer_size_r != 0) {
            SCLogError(SC_ERR_PCAP_SET_BUFF_SIZE, "Problems setting pcap buffer size, error %s", pcap_geterr(ptv->pcap_handle));
            SCFree(ptv);
            pcapconfig->DerefFunc(pcapconfig);
            SCReturnInt(TM_ECODE_FAILED);
        }
    }
#endif /* HAVE_PCAP_SET_BUFF */

    /* activate the handle */
    int pcap_activate_r = pcap_activate(ptv->pcap_handle);
    //printf("ReceivePcapThreadInit: pcap_activate(%p) returned %" PRId32 "\n", ptv->pcap_handle, pcap_activate_r);
    if (pcap_activate_r != 0) {
        SCLogError(SC_ERR_PCAP_ACTIVATE_HANDLE, "Couldn't activate the pcap handler, error %s", pcap_geterr(ptv->pcap_handle));
        SCFree(ptv);
        pcapconfig->DerefFunc(pcapconfig);
        SCReturnInt(TM_ECODE_FAILED);
    } else {
        ptv->pcap_state = PCAP_STATE_UP;
    }

    /* set bpf filter if we have one */
    if (pcapconfig->bpf_filter) {
        SCMutexLock(&pcap_bpf_compile_lock);

        ptv->bpf_filter = pcapconfig->bpf_filter;

        if (pcap_compile(ptv->pcap_handle,&ptv->filter,(char *)ptv->bpf_filter,1,0) < 0) {
            SCLogError(SC_ERR_BPF, "bpf compilation error %s", pcap_geterr(ptv->pcap_handle));

            SCMutexUnlock(&pcap_bpf_compile_lock);
            SCFree(ptv);
            pcapconfig->DerefFunc(pcapconfig);
            return TM_ECODE_FAILED;
        }

        if (pcap_setfilter(ptv->pcap_handle,&ptv->filter) < 0) {
            SCLogError(SC_ERR_BPF, "could not set bpf filter %s", pcap_geterr(ptv->pcap_handle));

            SCMutexUnlock(&pcap_bpf_compile_lock);
            SCFree(ptv);
            pcapconfig->DerefFunc(pcapconfig);
            return TM_ECODE_FAILED;
        }

        SCMutexUnlock(&pcap_bpf_compile_lock);
    }

    /* no offloading supported at all */
    (void)GetIfaceOffloading(pcapconfig->iface, 1, 1);

    ptv->datalink = pcap_datalink(ptv->pcap_handle);

    pcapconfig->DerefFunc(pcapconfig);

    ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets",
            ptv->tv);
    ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops",
            ptv->tv);
    ptv->capture_kernel_ifdrops = StatsRegisterCounter("capture.kernel_ifdrops",
            ptv->tv);

    *data = (void *)ptv;
    SCReturnInt(TM_ECODE_OK);
}
Exemplo n.º 24
0
int
main(int argc, char **argv)
{
	register int op;
	register char *cp, *cmdbuf, *device;
	long longarg;
	char *p;
	int timeout = 1000;
	int immediate = 0;
	int nonblock = 0;
	bpf_u_int32 localnet, netmask;
	struct bpf_program fcode;
	char ebuf[PCAP_ERRBUF_SIZE];
	int status;
	int packet_count;

	device = NULL;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	opterr = 0;
	while ((op = getopt(argc, argv, "i:mnt:")) != -1) {
		switch (op) {

		case 'i':
			device = optarg;
			break;

		case 'm':
			immediate = 1;
			break;

		case 'n':
			nonblock = 1;
			break;

		case 't':
			longarg = strtol(optarg, &p, 10);
			if (p == optarg || *p != '\0') {
				error("Timeout value \"%s\" is not a number",
				    optarg);
				/* NOTREACHED */
			}
			if (longarg < 0) {
				error("Timeout value %ld is negative", longarg);
				/* NOTREACHED */
			}
			if (longarg > INT_MAX) {
				error("Timeout value %ld is too large (> %d)",
				    longarg, INT_MAX);
				/* NOTREACHED */
			}
			timeout = (int)longarg;
			break;

		default:
			usage();
			/* NOTREACHED */
		}
	}

	if (device == NULL) {
		device = pcap_lookupdev(ebuf);
		if (device == NULL)
			error("%s", ebuf);
	}
	*ebuf = '\0';
	pd = pcap_create(device, ebuf);
	if (pd == NULL)
		error("%s", ebuf);
	status = pcap_set_snaplen(pd, 65535);
	if (status != 0)
		error("%s: pcap_set_snaplen failed: %s",
			    device, pcap_statustostr(status));
	if (immediate) {
		status = pcap_set_immediate_mode(pd, 1);
		if (status != 0)
			error("%s: pcap_set_immediate_mode failed: %s",
			    device, pcap_statustostr(status));
	}
	status = pcap_set_timeout(pd, timeout);
	if (status != 0)
		error("%s: pcap_set_timeout failed: %s",
		    device, pcap_statustostr(status));
	status = pcap_activate(pd);
	if (status < 0) {
		/*
		 * pcap_activate() failed.
		 */
		error("%s: %s\n(%s)", device,
		    pcap_statustostr(status), pcap_geterr(pd));
	} else if (status > 0) {
		/*
		 * pcap_activate() succeeded, but it's warning us
		 * of a problem it had.
		 */
		warning("%s: %s\n(%s)", device,
		    pcap_statustostr(status), pcap_geterr(pd));
	}
	if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
		localnet = 0;
		netmask = 0;
		warning("%s", ebuf);
	}
	cmdbuf = copy_argv(&argv[optind]);

	if (pcap_compile(pd, &fcode, cmdbuf, 1, netmask) < 0)
		error("%s", pcap_geterr(pd));

	if (pcap_setfilter(pd, &fcode) < 0)
		error("%s", pcap_geterr(pd));
	if (pcap_setnonblock(pd, nonblock, ebuf) == -1)
		error("pcap_setnonblock failed: %s", ebuf);
	printf("Listening on %s\n", device);
	for (;;) {
		packet_count = 0;
		status = pcap_dispatch(pd, -1, countme,
		    (u_char *)&packet_count);
		if (status < 0)
			break;
		if (status != 0) {
			printf("%d packets seen, %d packets counted after pcap_dispatch returns\n",
			    status, packet_count);
		}
	}
	if (status == -2) {
		/*
		 * We got interrupted, so perhaps we didn't
		 * manage to finish a line we were printing.
		 * Print an extra newline, just in case.
		 */
		putchar('\n');
	}
	(void)fflush(stdout);
	if (status == -1) {
		/*
		 * Error.  Report it.
		 */
		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
		    program_name, pcap_geterr(pd));
	}
	pcap_close(pd);
	exit(status == -1 ? 1 : 0);
}
Exemplo n.º 25
0
void Sniffer::set_snap_len(unsigned snap_len) {
    if (pcap_set_snaplen(get_pcap_handle(), snap_len)) {
        throw pcap_error(pcap_geterr(get_pcap_handle()));
    }
}
Exemplo n.º 26
0
struct if_pcap_host_context *
if_pcap_create_handle(const char *ifname, unsigned int isfile, if_pcap_handler handler, void *handlerarg)
{
	struct if_pcap_host_context *ctx;
	int dlt;

	ctx = calloc(1, sizeof(*ctx));
	if (NULL == ctx)
		goto fail;

	ctx->isfile = isfile;
	ctx->pkthandler = handler;
	ctx->pkthandlerarg = handlerarg;

	if (ctx->isfile) {
		ctx->p = pcap_open_offline(ifname, ctx->errbuf);
		if (NULL == ctx->p)
			goto fail;
	} else {
		ctx->p = pcap_create(ifname, ctx->errbuf);
		if (NULL == ctx->p)
			goto fail;

		if (-1 == pcap_setdirection(ctx->p, PCAP_D_IN)) {
			printf("Could not restrict pcap capture to input on %s\n", ifname);
			goto fail;
		}

		pcap_set_timeout(ctx->p, 1);
		pcap_set_snaplen(ctx->p, 65535);
		pcap_set_promisc(ctx->p, 1);

		switch (pcap_activate(ctx->p)) {
		case 0:
			break;
		case PCAP_WARNING_PROMISC_NOTSUP:
			printf("Promiscuous mode not supported on %s: %s\n", ifname, pcap_geterr(ctx->p));
			break;
		case PCAP_WARNING:
			printf("Warning while activating pcap capture on %s: %s\n", ifname, pcap_geterr(ctx->p));
			break;
		case PCAP_ERROR_NO_SUCH_DEVICE:
		case PCAP_ERROR_PERM_DENIED:
			printf("Error activating pcap capture on %s: %s\n", ifname, pcap_geterr(ctx->p));
			/* FALLTHOUGH */
		default:
			goto fail;
			break;
		}

		dlt = pcap_datalink(ctx->p);
		if (DLT_EN10MB != dlt) {
			printf("Data link type on %s is %d, only %d supported\n", ifname, dlt, DLT_EN10MB);
			goto fail;
		}
	}

	return (ctx);

fail:
	if (ctx)
		free(ctx);

	return (NULL);
}
Exemplo n.º 27
0
/**
 *  Set up pcap listener for the given interfaces and protocols.
 *  @return a properly configured pcap_t* object for listening for the given protocols - NULL on error
 *  @see pcap_protocols
 */
pcap_t*
create_pcap_listener(const char * dev		///<[in] Device name to listen on
                     ,		     gboolean blocking		///<[in] TRUE if this is a blocking connection
                     ,		     unsigned listenmask	///<[in] Bit mask of protocols to listen for
                     ///< (see @ref pcap_protocols "list of valid bits")
                     ,		     struct bpf_program*prog)	///<[out] Compiled PCAP program
{
    pcap_t*			pcdescr = NULL;
    bpf_u_int32		maskp = 0;
    bpf_u_int32		netp = 0;
    char			errbuf[PCAP_ERRBUF_SIZE];
    char *			expr = NULL;
    int			filterlen = 1;
    unsigned		j;
    int			cnt=0;
    int			rc;
    const char ORWORD [] = " or ";
    gboolean		need_promisc = FALSE;

    BINDDEBUG(pcap_t);
//	setbuf(stdout, NULL);
    setvbuf(stdout, NULL, _IONBF, 0);
    errbuf[0] = '\0';

    // Search the list of valid bits so we can construct the libpcap filter
    // for the given set of protocols on the fly...
    // On this pass we just compute the amount of memory we'll need...
    for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            ++cnt;
            if (cnt > 1) {
                filterlen += sizeof(ORWORD);
            }
            filterlen += strlen(filterinfo[j].filter);
        }
    }

    if (filterlen < 2) {
        g_warning("Constructed filter is too short - invalid mask argument.");
        return NULL;
    }
    if (NULL == (expr = malloc(filterlen))) {
        g_error("Out of memory!");
        return NULL;
    }
    // Same song, different verse...
    // This time around, we construct the filter
    expr[0] = '\0';
    for (j = 0, cnt = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            ++cnt;
            if (cnt > 1) {
                g_strlcat(expr, ORWORD, filterlen);
            }
            g_strlcat(expr, filterinfo[j].filter, filterlen);
        }
    }
    if (pcap_lookupnet(dev, &netp, &maskp, errbuf) != 0) {
        // This is not a problem for non-IPv4 protocols...
        // It just looks up the ipv4 address - which we mostly don't care about.
        g_info("%s.%d: pcap_lookupnet(\"%s\") failed: [%s]"
               ,	__FUNCTION__, __LINE__, dev, errbuf);
    }

    if (NULL == (pcdescr = pcap_create(dev, errbuf))) {
        g_warning("pcap_create failed: [%s]", errbuf);
        goto oopsie;
    }
    //pcap_set_promisc(pcdescr, FALSE);
    for (j = 0; j < DIMOF(filterinfo); ++j) {
        if (listenmask & filterinfo[j].filterbit) {
            const char * addrstring = filterinfo[j].mcastaddr;
            if (addrstring && !_enable_mcast_address(addrstring, dev, TRUE)) {
                need_promisc = TRUE;
            }
        }
    }
    pcap_set_promisc(pcdescr, need_promisc);
#ifdef HAVE_PCAP_SET_RFMON
    pcap_set_rfmon(pcdescr, FALSE);
#endif
    pcap_setdirection(pcdescr, PCAP_D_IN);
    // Weird bug - returns -3 and doesn't show an error message...
    // And pcap_getnonblock also returns -3... Neither should happen AFAIK...
    errbuf[0] = '\0';
    if ((rc = pcap_setnonblock(pcdescr, !blocking, errbuf)) < 0 && errbuf[0] != '\0') {
        g_warning("pcap_setnonblock(%d) failed: [%s] [rc=%d]", !blocking, errbuf, rc);
        g_warning("Have no idea why this happens - current blocking state is: %d."
                  ,	pcap_getnonblock(pcdescr, errbuf));
    }
    pcap_set_snaplen(pcdescr, 1500);
    /// @todo deal with pcap_set_timeout() call here.
    if (blocking) {
        pcap_set_timeout(pcdescr, 240*1000);
    } else {
        pcap_set_timeout(pcdescr, 1);
    }
    //pcap_set_buffer_size(pcdescr, 1500);

    if (pcap_activate(pcdescr) != 0) {
        g_warning("pcap_activate failed: [%s]", pcap_geterr(pcdescr));
        goto oopsie;
    }
    if (pcap_compile(pcdescr, prog, expr, FALSE, maskp) < 0) {
        g_warning("pcap_compile of [%s] failed: [%s]", expr, pcap_geterr(pcdescr));
        goto oopsie;
    }
    if (pcap_setfilter(pcdescr, prog) < 0) {
        g_warning("pcap_setfilter on [%s] failed: [%s]", expr, pcap_geterr(pcdescr));
        goto oopsie;
    }
    DEBUGMSG1("Compile of [%s] worked!", expr);
    free(expr);
    expr = NULL;
    return(pcdescr);

oopsie:	// Some kind of failure - free things up and return NULL

    g_warning("%s.%d: Could not set up PCAP on %s"
              ,	__FUNCTION__, __LINE__, dev);
    if (expr) {
        free(expr);
        expr = NULL;
    }
    if (pcdescr) {
        close_pcap_listener(pcdescr, dev, listenmask);
        pcdescr = NULL;
    }
    return NULL;
}
Exemplo n.º 28
0
int
main(int argc, char **argv)
{
	register int op;
	register char *cp, *device;
	int dorfmon, dopromisc, snaplen, useactivate, bufsize;
	char ebuf[PCAP_ERRBUF_SIZE];
	pcap_t *pd;
	int status = 0;

	device = NULL;
	dorfmon = 0;
	dopromisc = 0;
	snaplen = MAXIMUM_SNAPLEN;
	bufsize = 0;
	useactivate = 0;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	opterr = 0;
	while ((op = getopt(argc, argv, "i:Ips:aB:")) != -1) {
		switch (op) {

		case 'i':
			device = optarg;
			break;

		case 'I':
			dorfmon = 1;
			useactivate = 1;	/* required for rfmon */
			break;

		case 'p':
			dopromisc = 1;
			break;

		case 's': {
			char *end;

			snaplen = strtol(optarg, &end, 0);
			if (optarg == end || *end != '\0'
			    || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
				error("invalid snaplen %s", optarg);
			else if (snaplen == 0)
				snaplen = MAXIMUM_SNAPLEN;
			break;
		}

		case 'B':
			bufsize = atoi(optarg)*1024;
			if (bufsize <= 0)
				error("invalid packet buffer size %s", optarg);
			useactivate = 1;	/* required for bufsize */
			break;

		case 'a':
			useactivate = 1;
			break;

		default:
			usage();
			/* NOTREACHED */
		}
	}

	if (useactivate) {
		pd = pcap_create(device, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		status = pcap_set_snaplen(pd, snaplen);
		if (status != 0)
			error("%s: pcap_set_snaplen failed: %s",
			    device, pcap_statustostr(status));
		if (dopromisc) {
			status = pcap_set_promisc(pd, 1);
			if (status != 0)
				error("%s: pcap_set_promisc failed: %s",
				    device, pcap_statustostr(status));
		}
		if (dorfmon) {
			status = pcap_set_rfmon(pd, 1);
			if (status != 0)
				error("%s: pcap_set_rfmon failed: %s",
				    device, pcap_statustostr(status));
		}
		status = pcap_set_timeout(pd, 1000);
		if (status != 0)
			error("%s: pcap_set_timeout failed: %s",
			    device, pcap_statustostr(status));
		if (bufsize != 0) {
			status = pcap_set_buffer_size(pd, bufsize);
			if (status != 0)
				error("%s: pcap_set_buffer_size failed: %s",
				    device, pcap_statustostr(status));
		}
		status = pcap_activate(pd);
		if (status < 0) {
			/*
			 * pcap_activate() failed.
			 */
			error("%s: %s\n(%s)", device,
			    pcap_statustostr(status), pcap_geterr(pd));
		} else if (status > 0) {
			/*
			 * pcap_activate() succeeded, but it's warning us
			 * of a problem it had.
			 */
			warning("%s: %s\n(%s)", device,
			    pcap_statustostr(status), pcap_geterr(pd));
		}
	} else {
		*ebuf = '\0';
		pd = pcap_open_live(device, 65535, 0, 1000, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		else if (*ebuf)
			warning("%s", ebuf);
	}
	pcap_close(pd);
	exit(status < 0 ? 1 : 0);
}
Exemplo n.º 29
0
/*
 * Look for a given device in the specified list of devices.
 *
 * If we find it, return 0 and set *curdev_ret to point to it.
 *
 * If we don't find it, check whether we can open it:
 *
 *     If that fails with PCAP_ERROR_NO_SUCH_DEVICE or
 *     PCAP_ERROR_IFACE_NOT_UP, don't attempt to add an entry for
 *     it, as that probably means it exists but doesn't support
 *     packet capture.
 *
 *     Otherwise, attempt to add an entry for it, with the specified
 *     ifnet flags and description, and, if that succeeds, return 0
 *     and set *curdev_ret to point to the new entry, otherwise
 *     return PCAP_ERROR and set errbuf to an error message.
 */
int
add_or_find_if(pcap_if_t **curdev_ret, pcap_if_t **alldevs, const char *name,
    u_int flags, const char *description, char *errbuf)
{
	pcap_t *p;
	pcap_if_t *curdev, *prevdev, *nextdev;
	u_int this_figure_of_merit, nextdev_figure_of_merit;
	char open_errbuf[PCAP_ERRBUF_SIZE];
	int ret;

	/*
	 * Is there already an entry in the list for this interface?
	 */
	for (curdev = *alldevs; curdev != NULL; curdev = curdev->next) {
		if (strcmp(name, curdev->name) == 0)
			break;	/* yes, we found it */
	}

	if (curdev == NULL) {
		/*
		 * No, we didn't find it.
		 *
		 * Can we open this interface for live capture?
		 *
		 * We do this check so that interfaces that are
		 * supplied by the interface enumeration mechanism
		 * we're using but that don't support packet capture
		 * aren't included in the list.  Loopback interfaces
		 * on Solaris are an example of this; we don't just
		 * omit loopback interfaces on all platforms because
		 * you *can* capture on loopback interfaces on some
		 * OSes.
		 *
		 * On OS X, we don't do this check if the device
		 * name begins with "wlt"; at least some versions
		 * of OS X offer monitor mode capturing by having
		 * a separate "monitor mode" device for each wireless
		 * adapter, rather than by implementing the ioctls
		 * that {Free,Net,Open,DragonFly}BSD provide.
		 * Opening that device puts the adapter into monitor
		 * mode, which, at least for some adapters, causes
		 * them to deassociate from the network with which
		 * they're associated.
		 *
		 * Instead, we try to open the corresponding "en"
		 * device (so that we don't end up with, for users
		 * without sufficient privilege to open capture
		 * devices, a list of adapters that only includes
		 * the wlt devices).
		 */
#ifdef __APPLE__
		if (strncmp(name, "wlt", 3) == 0) {
			char *en_name;
			size_t en_name_len;

			/*
			 * Try to allocate a buffer for the "en"
			 * device's name.
			 */
			en_name_len = strlen(name) - 1;
			en_name = malloc(en_name_len + 1);
			if (en_name == NULL) {
				(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
				    "malloc: %s", pcap_strerror(errno));
				return (-1);
			}
			strcpy(en_name, "en");
			strcat(en_name, name + 3);
			p = pcap_create(en_name, open_errbuf);
			free(en_name);
		} else
#endif /* __APPLE */
		p = pcap_create(name, open_errbuf);
		if (p == NULL) {
			/*
			 * The attempt to create the pcap_t failed;
			 * that's probably an indication that we're
			 * out of memory.
			 *
			 * Don't bother including this interface,
			 * but don't treat it as an error.
			 */
			*curdev_ret = NULL;
			return (0);
		}
		/* Small snaplen, so we don't try to allocate much memory. */
		pcap_set_snaplen(p, 68);
		ret = pcap_activate(p);
		pcap_close(p);
		switch (ret) {

		case PCAP_ERROR_NO_SUCH_DEVICE:
		case PCAP_ERROR_IFACE_NOT_UP:
			/*
			 * We expect these two errors - they're the
			 * reason we try to open the device.
			 *
			 * PCAP_ERROR_NO_SUCH_DEVICE typically means
			 * "there's no such device *known to the
			 * OS's capture mechanism*", so, even though
			 * it might be a valid network interface, you
			 * can't capture on it (e.g., the loopback
			 * device in Solaris up to Solaris 10, or
			 * the vmnet devices in OS X with VMware
			 * Fusion).  We don't include those devices
			 * in our list of devices, as there's no
			 * point in doing so - they're not available
			 * for capture.
			 *
			 * PCAP_ERROR_IFACE_NOT_UP means that the
			 * OS's capture mechanism doesn't work on
			 * interfaces not marked as up; some capture
			 * mechanisms *do* support that, so we no
			 * longer reject those interfaces out of hand,
			 * but we *do* want to reject them if they
			 * can't be opened for capture.
			 */
			*curdev_ret = NULL;
			return (0);
		}

		/*
		 * Yes, we can open it, or we can't, for some other
		 * reason.
		 *
		 * If we can open it, we want to offer it for
		 * capture, as you can capture on it.  If we can't,
		 * we want to offer it for capture, so that, if
		 * the user tries to capture on it, they'll get
		 * an error and they'll know why they can't
		 * capture on it (e.g., insufficient permissions)
		 * or they'll report it as a problem (and then
		 * have the error message to provide as information).
		 *
		 * Allocate a new entry.
		 */
		curdev = malloc(sizeof(pcap_if_t));
		if (curdev == NULL) {
			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "malloc: %s", pcap_strerror(errno));
			return (-1);
		}

		/*
		 * Fill in the entry.
		 */
		curdev->next = NULL;
		curdev->name = strdup(name);
		if (curdev->name == NULL) {
			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
			    "malloc: %s", pcap_strerror(errno));
			free(curdev);
			return (-1);
		}
		if (description != NULL) {
			/*
			 * We have a description for this interface.
			 */
			curdev->description = strdup(description);
			if (curdev->description == NULL) {
				(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
				    "malloc: %s", pcap_strerror(errno));
				free(curdev->name);
				free(curdev);
				return (-1);
			}
		} else {
			/*
			 * We don't.
			 */
			curdev->description = NULL;
		}
		curdev->addresses = NULL;	/* list starts out as empty */
		curdev->flags = 0;
		if (ISLOOPBACK(name, flags))
			curdev->flags |= PCAP_IF_LOOPBACK;
		if (ISUP(flags))
			curdev->flags |= PCAP_IF_UP;
		if (ISRUNNING(flags))
			curdev->flags |= PCAP_IF_RUNNING;

		/*
		 * Add it to the list, in the appropriate location.
		 * First, get the "figure of merit" for this
		 * interface.
		 */
		this_figure_of_merit = get_figure_of_merit(curdev);

		/*
		 * Now look for the last interface with an figure of merit
		 * less than or equal to the new interface's figure of
		 * merit.
		 *
		 * We start with "prevdev" being NULL, meaning we're before
		 * the first element in the list.
		 */
		prevdev = NULL;
		for (;;) {
			/*
			 * Get the interface after this one.
			 */
			if (prevdev == NULL) {
				/*
				 * The next element is the first element.
				 */
				nextdev = *alldevs;
			} else
				nextdev = prevdev->next;

			/*
			 * Are we at the end of the list?
			 */
			if (nextdev == NULL) {
				/*
				 * Yes - we have to put the new entry
				 * after "prevdev".
				 */
				break;
			}

			/*
			 * Is the new interface's figure of merit less
			 * than the next interface's figure of merit,
			 * meaning that the new interface is better
			 * than the next interface?
			 */
			nextdev_figure_of_merit = get_figure_of_merit(nextdev);
			if (this_figure_of_merit < nextdev_figure_of_merit) {
				/*
				 * Yes - we should put the new entry
				 * before "nextdev", i.e. after "prevdev".
				 */
				break;
			}

			prevdev = nextdev;
		}

		/*
		 * Insert before "nextdev".
		 */
		curdev->next = nextdev;

		/*
		 * Insert after "prevdev" - unless "prevdev" is null,
		 * in which case this is the first interface.
		 */
		if (prevdev == NULL) {
			/*
			 * This is the first interface.  Pass back a
			 * pointer to it, and put "curdev" before
			 * "nextdev".
			 */
			*alldevs = curdev;
		} else
			prevdev->next = curdev;
	}

	*curdev_ret = curdev;
	return (0);
}
Exemplo n.º 30
0
/**
 * main(int argc, char * const argv[])
 *
 * program entry point
 */
int main(int argc, char * const argv[]) {
   struct config_s config;
   char errbuf[PCAP_ERRBUF_SIZE];
   struct ifreq ifr;
   struct sockaddr_ll sa;
   int n, valid_mac;
   int fd = 0;
   int runcond=1;
   pcap_t *p;

   memset(&config, 0, sizeof(config));
   
   config.vlan = 1;
   config.debuglevel = 0;
   config.cisco_port_low = config.cisco_port_high = 50505;
   config.do_check_addr = 1;
   fprintf(stderr,"IP SLA responder v2.0 (c) Aki Tuomi 2013-\r\n");
   fprintf(stderr,"See LICENSE for more information\r\n");

   if (argc == 2) {
    if (argv[1][0] != '-') {
      if (configure(argv[1], &config)) return -1;
    } else {
      fprintf(stderr,"Usage: %s [config file]\r\n\tDefaults to %s\r\n", argv[0], CONFIGFILE);
      return -1;
    }
   } else {
      if (configure(CONFIGFILE, &config)) return -1;
   }

   if (config.do_ip4) {
      if (config.do_check_addr) {
         char addr[200];
         inet_ntop(AF_INET, &config.ip_addr, addr, 200);
         fprintf(stderr, "Listening on %s %s:%u-%u\n", config.ifname, addr, config.cisco_port_low, config.cisco_port_high);
      } else {
          fprintf(stderr, "Listening on %s 0.0.0.0:%u-%u\n", config.ifname, config.cisco_port_low, config.cisco_port_high);
      }
   }
   if (config.do_ip6) {
      char addr[200];
      inet_ntop(AF_INET6, &config.ip6_addr, addr, 200);
      fprintf(stderr, "Listening on %s [%s]:%u-%u\n", config.ifname, addr, config.cisco_port_low, config.cisco_port_high);
   }
 
   // select first non-loopback if here
   if (strlen(config.ifname) == 0) {
     pcap_if_t *alldevsp, *devptr;
     if (pcap_findalldevs(&alldevsp, errbuf)) {
       fprintf(stderr, "pcap_findalldevs: %s\n", errbuf);
       return EXIT_FAILURE;
     }
     for(devptr = alldevsp; devptr != NULL; devptr = devptr->next) {
        if ((devptr->flags & PCAP_IF_LOOPBACK) == PCAP_IF_LOOPBACK) continue;
        // OK, this is our interface.
        break;
     }
     if (devptr == NULL) {
        fprintf(stderr, "cannot find suitable interface for operations\r\n");
        return EXIT_FAILURE;
     }
     strncpy(config.ifname, devptr->name, sizeof(config.ifname));
     pcap_freealldevs(alldevsp);
   }

   // create raw socket
   fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

   // check for valid mac
   for(n = 0; n < ETH_ALEN; n++) {
     valid_mac = config.mac[n];
     if (valid_mac > 0) break;
   }

   if (valid_mac == 0) {
     // need mac from our interface
     memset(&ifr,0,sizeof ifr);
     strncpy(ifr.ifr_name, config.ifname, IFNAMSIZ);
     ioctl(fd, SIOCGIFHWADDR, &ifr);
     memcpy(config.mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
   }

   // get interface index for binding
   memset(&ifr,0,sizeof ifr);
   strncpy(ifr.ifr_name, config.ifname, IFNAMSIZ);
   ioctl(fd, SIOCGIFINDEX, &ifr);
   memset(&sa,0,sizeof sa);

   // bind our packet if to interface
   sa.sll_family = AF_PACKET;
   sa.sll_ifindex = ifr.ifr_ifindex;
   sa.sll_protocol = htons(ETH_P_ALL);
   bind(fd, (struct sockaddr*)&sa, sizeof sa);

   if (config.do_ip6)
      generate_ip6_values(&config);

   // initialize pcap
   p = pcap_create(ifr.ifr_name, errbuf);
   if (pcap_set_snaplen(p, 65535)) {
     pcap_perror(p, "pcap_set_snaplen");
     exit(1);
   }
   if (pcap_set_promisc(p, 1)) {
     pcap_perror(p, "pcap_set_promisc");
     exit(1);
   }
   // need to activate before setting datalink and filter
   pcap_activate(p);
   if (pcap_set_datalink(p, 1) != 0) {
     pcap_perror(p, "pcap_set_datalink");
     exit(1);
   }

   // start doing hard work
   while(runcond) {
      struct pak_handler_s tmp;
      tmp.config = &config;
      tmp.fd = fd;

      switch(pcap_dispatch(p, 0, pak_handler, (u_char*)&tmp)) {
      case -1:
         // ERROR!
         pcap_perror(p, "pcap_dispatch");
      case -2:
         // abort
         runcond = 0;
      } 
   }

   pcap_close(p);
   return 0;
}