int main()
{
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i = 0;
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	u_int netmask;
	char packet_filter[] = "arp";
	struct bpf_program fcode;

	/* Retrieve the device list */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	/* Print the list */
	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)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return -1;
	}

	printf("Enter the interface number (1-%d):", i);
	scanf_s("%d", &inum);

	if (inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

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

	/* Open the adapter */
	if ((adhandle = pcap_open(d->name,  // name of the device
		65536,     // portion of the packet to capture. 
				   // 65536 grants that the whole packet will be captured on all the MACs.
		PCAP_OPENFLAG_PROMISCUOUS,         // promiscuous mode
		1000,      // read timeout
		NULL,      // remote authentication
		errbuf     // error buffer
		)) == NULL)
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* Check the link layer. We support only Ethernet for simplicity. */
	if (pcap_datalink(adhandle) != DLT_EN10MB)
	{
		fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	if (d->addresses != NULL)
		/* Retrieve the mask of the first address of the interface */
		netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	else
		/* If the interface is without addresses we suppose to be in a C class network */
		netmask = 0xffffff;


	//compile the filter
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0)
	{
		fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	//set the filter
	if (pcap_setfilter(adhandle, &fcode)<0)
	{
		fprintf(stderr, "\nError setting the filter.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	printf("\nlistening on %s...\n", d->description);

	/* At this point, we don't need any more the device list. Free it */
	pcap_freealldevs(alldevs);

	/* start the capture */
	pcap_loop(adhandle, 0, packet_handler, NULL);

	return 0;
}
Example #2
0
int main(int argc, char *argv[])
{
    char errbuf[PCAP_ERRBUF_SIZE];
    int opt = -1;

    while ((opt = getopt(argc, argv, "Ce")) != -1) {
        switch (opt) {
        case 'C':
            g_option_display_header = false;
            break;
        case 'e':
            g_option_color = true;
            break;
        default:
            print_usage(argv[0]);
            exit(1);
        }
    }

    if (optind >= argc) {
        print_usage(argv[0]);
        exit(1);
    }

    // open pcap file
    const char *pcap_file_name = argv[optind];
    pcap_t *pd = pcap_open_offline(pcap_file_name, errbuf);
    if (NULL == pd) {
        die("%s", errbuf);
    }

    // get datalink heaer length
    int dlt = pcap_datalink(pd);
    if (DLT_NULL == dlt) {
        g_datalink_header_length = 4;
    } else if (DLT_RAW == dlt) {
        g_datalink_header_length = 0;
    } else if (DLT_EN10MB == dlt || DLT_IEEE802 == dlt) {
        g_datalink_header_length = 14;
    } else if (DLT_PPP == dlt) {
        g_datalink_header_length = 4;
    } else if (DLT_LINUX_SLL == dlt) {
        g_datalink_header_length = 16;
    } else {
        fprintf(stderr, "unknown datalink type\n");
        return -1;
    }

    // compile and install the filter
    struct bpf_program filter;
    if (pcap_compile(pd, &filter, "tcp", 1, 0) != 0) {
        die("%s", pcap_geterr(pd));
    }
    if (pcap_setfilter(pd, &filter) != 0) {
        die("%s", pcap_geterr(pd));
    }
    
    // start loop
    if (pcap_loop(pd, -1, packet_handler, NULL) != 0) {
        die("%s", pcap_geterr(pd));
    }

    return 0;
}
Example #3
0
int main(int argc, char *argv[])
{
	int c = 0;
	FILE *fp = NULL;
	int long_opt_index = 0, i = 0, channel = 0, passive = 0, mode = 0;
	int source = INTERFACE, ret_val = EXIT_FAILURE;
	struct bpf_program bpf = { 0 };
	char *out_file = NULL, *last_optarg = NULL, *target = NULL, *bssid = NULL;
	const char *short_options = "i:c:n:o:b:5sfuCDhv";
        struct option long_options[] = {
		{ "bssid", required_argument, NULL, 'b' },
                { "interface", required_argument, NULL, 'i' },
                { "channel", required_argument, NULL, 'c' },
		{ "out-file", required_argument, NULL, 'o' },
		{ "probes", required_argument, NULL, 'n' },
		{ "daemonize", no_argument, NULL, 'D' },
		{ "file", no_argument, NULL, 'f' },
		{ "ignore-fcs", no_argument, NULL, 'C' },
		{ "5ghz", no_argument, NULL, '5' },
		{ "scan", no_argument, NULL, 's' },
		{ "survey", no_argument, NULL, 'u' },
                { "help", no_argument, NULL, 'h' },
		{ "verbose", no_argument, NULL, 'v'},
                { 0, 0, 0, 0 }
        };

	fprintf(stderr, "\nWash v%s WiFi Protected Setup Scan Tool\n", PACKAGE_VERSION);
        fprintf(stderr, "Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <*****@*****.**>\n\n");

	globule_init();
	sql_init();
	create_ap_table();
	set_auto_channel_select(0);
	set_wifi_band(BG_BAND);
	set_debug(INFO);
	set_validate_fcs(1);
	set_log_file(stdout);
	set_max_num_probes(DEFAULT_MAX_NUM_PROBES);

	while((c = getopt_long(argc, argv, short_options, long_options, &long_opt_index)) != -1)
        {
                switch(c)
                {
			case 'f':
				source = PCAP_FILE;
				break;
			case 'i':
				set_iface(optarg);
				break;
			case 'b':
				bssid = strdup(optarg);
				break;
			case 'c':
				channel = atoi(optarg);
				set_fixed_channel(1);
				break;
			case '5':
				set_wifi_band(AN_BAND);
				break;
			case 'n':
				set_max_num_probes(atoi(optarg));
				break;
			case 'o':
				out_file = strdup(optarg);
				break;
			case 's':
				mode = SCAN;
				break;
			case 'u':
				mode = SURVEY;
				break;
			case 'C':
				set_validate_fcs(0);
				break;
			case 'D':
				daemonize();
				break;
                        case 'v':
                                set_debug(get_debug() + 1);
                                break;
			default:
				usage(argv[0]);
				goto end;
		}

		/* Track the last optarg. This is used later when looping back through any specified pcap files. */
		if(optarg)
		{
			if(last_optarg)
			{
				free(last_optarg);
			}

			last_optarg = strdup(optarg);
		}
	}

	/* The interface value won't be set if capture files were specified; else, there should have been an interface specified */
	if(!get_iface() && source != PCAP_FILE)
	{
		usage(argv[0]);
		goto end;
	}
	else if(get_iface())
	{
		/* Get the MAC address of the specified interface */
		read_iface_mac();
	}

	if(get_iface() && source == PCAP_FILE)
	{
		cprintf(CRITICAL, "[X] ERROR: -i and -f options cannot be used together.\n");
		usage(argv[0]);
		goto end;
	}

	/* If we're reading from a file, be sure we don't try to transmit probe requests */
	if(source == PCAP_FILE)
	{
		passive = 1;
	}

	/* Open the output file, if any. If none, write to stdout. */
	if(out_file)
	{
		fp = fopen(out_file, "wb");
		if(!fp)
		{
			cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for writing\n", out_file);
			goto end;
		}

		set_log_file(fp);
	}

	/* 
	 * Loop through all of the specified capture sources. If an interface was specified, this will only loop once and the
	 * call to monitor() will block indefinitely. If capture files were specified, this will loop through each file specified
	 * on the command line and monitor() will return after each file has been processed.
	 */
	for(i=argc-1; i>0; i--)
	{
		/* If the source is a pcap file, get the file name from the command line */
		if(source == PCAP_FILE)
		{
			cprintf(VERBOSE, "[V]: using PCAP file\n");
			/* If we've gotten to the arguments, we're done */
			if((argv[i][0] == '-') ||
			   (last_optarg && (memcmp(argv[i], last_optarg, strlen(last_optarg)) == 0))
			)
			{
				break;
			}
			else
			{
				target = argv[i];
			}
		}
		/* Else, use the specified interface name */
		else
		{
			cprintf(VERBOSE, "[V]: using physical iface\n");
			target = get_iface();
		}

		set_handle(capture_init(target));
		if(!get_handle())
		{
			cprintf(CRITICAL, "[X] ERROR: Failed to open '%s' for capturing\n", get_iface());
			goto end;
		}

		if(pcap_compile(get_handle(), &bpf, PACKET_FILTER, 0, 0) != 0)
		{
			cprintf(CRITICAL, "[X] ERROR: Failed to compile packet filter\n");
			goto end;
		}

		if(pcap_setfilter(get_handle(), &bpf) != 0)
		{
			cprintf(CRITICAL, "[X] ERROR: Failed to set packet filter\n");
			goto end;
		}

		/* Do it. */
		cprintf(VERBOSE, "[V]: beginning monitor...\n");
		monitor(bssid, passive, source, channel, mode);
		cprintf(VERBOSE, "[V]: monitor exited\n");
		printf("\n");
	}

	ret_val = EXIT_SUCCESS;

end:
	globule_deinit();
	sql_cleanup();
	if(bssid) free(bssid);
	if(out_file) free(out_file);
	if(wpsmon.fp) fclose(wpsmon.fp);
	return ret_val;
}
Example #4
0
/*int pcap_compile(pcap_t * p, struct bpf_program * fp, char * str, int optimize, bpf_u_int32 netmask)
			fp:这是一个传出参数,存放编译后的bpf
			str:过滤表达式
			optimize:是否需要优化过滤表达式
			metmask:简单设置为0即可
		  */
void Capture::setfilter(string s){
	  pcap_compile(device, &filter, s.c_str(), 1, 0);
	  pcap_setfilter(device, &filter);
}
Example #5
0
void ICMPSniffer::run()
{
    char dev[DEV_MAX] ;			/* set device name */
    strcpy(dev,global_dev);
    char errbuf[PCAP_ERRBUF_SIZE];		/* error buffer */
    /* find a capture device if not specified by dev */
    //dev = pcap_lookupdev(errbuf);
    if (dev == NULL)
        return;

    /* get network number and mask associated with capture device */
    bpf_u_int32 mask;			/* subnet mask */
    bpf_u_int32 net;			/* ip */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
        return;

    /* open capture device */
    pcap_t *handle;				/* packet capture handle */
    handle = pcap_open_live(dev, SNAP_LEN, 0, 1000, errbuf); // needn't to be promiscuous
    if (handle == NULL)
        return;

    /* make sure we're capturing on an Ethernet device [2] */
    if (pcap_datalink(handle) != DLT_EN10MB)
        return;

    /* compile the filter expression */
    struct bpf_program fp;			/* compiled filter program (expression) */
    char filter_exp[] = "icmp";
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1)
        return;

    /* apply the compiled filter */
    if (pcap_setfilter(handle, &fp) == -1)
        return;

    /* now we can start capturing packets */
    struct pcap_pkthdr header;	/* The header that pcap gives us */
    //const struct libnet_ethernet_hdr *ethernet; /* The ethernet header */
    const struct libnet_ipv4_hdr *ip; /* The IP header */
    const struct libnet_icmpv4_hdr *icmp; /* The ICMP header */
    const u_char *packet;   // the actual packet we picked
    u_int size_ip;
    while(!m_stop){
        packet = pcap_next(handle,&header);
        if( NULL==packet )
            continue;
        //ethernet = (struct libnet_ethernet_hdr*)(packet);
        ip = (struct libnet_ipv4_hdr*)(packet + LIBNET_ETH_H);
        size_ip = IP_SIZE(ip);
        icmp = (struct libnet_icmpv4_hdr*)(packet + LIBNET_ETH_H + size_ip);
        unsigned int ipSource = ip->ip_src.s_addr;
        //unsigned short ipID = ntohs(ip->ip_id);
        unsigned short icmpID = ntohs(icmp->hun.echo.id);
        // check whether the packet is corresponding to our sender
        QList<IPID_Info>::iterator start=m_info.begin(), last=m_info.end();
        while(start!=last){
            // check if the response is corresponding to my ping
            if((*start).ip==ipSource && //(*start).IPid==ipID && //!!!!!!!!!!!!! sina don't reply the same!
                    (*start).ICMPid==icmpID){
                emit pingFounded(ipSource,0,PROTOCOL_ICMP);
                m_info.erase(start);    // to avoid the duplicate table row same icmp response
                break;
            }
            ++start;
        }
    }

    /* cleanup */
    pcap_freecode(&fp);
    pcap_close(handle);

    return;
}
Example #6
0
int daemon_unpackapplyfilter(pcap_t *fp, unsigned int *nread, int *plen, char *errbuf)
{
struct rpcap_filter filter;
struct rpcap_filterbpf_insn insn;
struct bpf_insn *bf_insn;
struct bpf_program bf_prog;
unsigned int i;


	if ( ( *nread+= sock_recv(fp->rmt_sockctrl, (char *) &filter, sizeof(struct rpcap_filter), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1)
	{
		// to avoid blocking on the sock_discard()
		*plen= *nread;
		return -1;
	}

	bf_prog.bf_len= ntohl(filter.nitems);

	if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
		return -1;
	}

	bf_insn= (struct bpf_insn *) malloc ( sizeof(struct bpf_insn) * bf_prog.bf_len);
	if (bf_insn == NULL)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
		return -1;
	}

	bf_prog.bf_insns= bf_insn;

	for (i= 0; i < bf_prog.bf_len; i++)
	{
		if ( ( *nread+= sock_recv(fp->rmt_sockctrl, (char *) &insn, 
			sizeof(struct rpcap_filterbpf_insn), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1)
			return -1;

		bf_insn->code= ntohs(insn.code);
		bf_insn->jf= insn.jf;
		bf_insn->jt= insn.jt;
		bf_insn->k= ntohl(insn.k);

		bf_insn++;
	}

	if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
		return -1;
	}

	if (pcap_setfilter(fp, &bf_prog) )
	{
		snprintf(errbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", fp->errbuf);
		return -1;
    }

	return 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);
}
Example #8
0
int main(int argc, char * argv[]) {

    char *ival = NULL;
    char *rval = NULL;
    char *sval = NULL;
    char *bpf = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];
    int index;
    int c;
    int rtn;
    bpf_u_int32 mask = 0;
    bpf_u_int32 net = 0;
    struct bpf_program fp;
    FILE *pcap_file = NULL;

    opterr = 0;
    while ((c = getopt (argc, argv, "i:r:s:")) != -1) {
        switch (c) {
            case 'h':
                print_help(stdout);
                exit(EXIT_SUCCESS);
                break;
            case 'i':
                ival = optarg;
                break;
            case 'r':
                rval = optarg;
                break;
            case 's':
                sval = optarg;
                break;
            case '?':
                if (optopt == 'c')
                    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                else if (isprint (optopt))
                    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf (stderr,
                            "Unknown option character `\\x%x'.\n",
                            optopt);
                print_help(stderr);

                return 1;
            default:
                abort ();
        }
    }

    printf ("i = %s, r = %s, s = %s\n", ival, rval, sval);

    for (index = optind; index < argc; index++) {
        bpf = argv[index];
        if(index > optind) {
            fprintf(stderr, "Please put BPF in quotes\n");
            exit(EXIT_FAILURE);
        }
        //printf ("Non-option argument %s\n", argv[index]);
    }

    if(rval != NULL) {
        pcap_file = fopen(rval, "r");
        if(pcap_file == NULL) {
            perror(NULL);
            exit(EXIT_FAILURE);
        }
        handle = pcap_fopen_offline(pcap_file, errbuf);
        if (handle == NULL) {
            fprintf(stderr, "Could not open pcap file: %s\n", errbuf);
            return(2);
        }
    } else {


        if(ival == NULL) {
            ival = pcap_lookupdev(errbuf);
            if(ival == NULL) {
                fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
                return(2);
            } else {
                printf("sniffing on: %s\n", ival);
            }

        }

        if (pcap_lookupnet(ival, &net, &mask, errbuf) == -1) {
            fprintf(stderr, "Couldn't get netmask for device %s: %s\n", ival, errbuf);
            net = 0;
            mask = 0;
        }

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

    if(bpf != NULL) {
        if (pcap_compile(handle, &fp, bpf, 0, net) == -1) {
            fprintf(stderr, "Couldn't parse filter %s: %s\n", bpf, pcap_geterr(handle));
            return(2);
        }

        if (pcap_setfilter(handle, &fp) == -1) {
            fprintf(stderr, "Couldn't install filter %s: %s\n", bpf, pcap_geterr(handle));
            return(2);
        }
    }

    signal(SIGINT, int_handler);
    rtn = pcap_loop(handle, -1, got_packet, (u_char*)sval);
    if(rtn == -1) {
        fprintf(stderr, "%s\n", pcap_geterr(handle));
        return EXIT_FAILURE;
    }

    pcap_close(handle);
    return EXIT_SUCCESS;
}
Example #9
0
File: net.c Project: DomChey/ptpd
/**
 * Init all network transports
 *
 * @param netPath 
 * @param rtOpts 
 * @param ptpClock 
 * 
 * @return TRUE if successful
 */
Boolean 
netInit(NetPath * netPath, RunTimeOpts * rtOpts, PtpClock * ptpClock)
{
	int temp;
	struct sockaddr_in addr;

#ifdef PTPD_PCAP
	struct bpf_program program;
	char errbuf[PCAP_ERRBUF_SIZE];
#endif

	DBG("netInit\n");

#ifdef PTPD_PCAP
	netPath->pcapEvent = NULL;
	netPath->pcapGeneral = NULL;
	netPath->pcapEventSock = -1;
	netPath->pcapGeneralSock = -1;
#endif
	netPath->generalSock = -1;
	netPath->eventSock = -1;

#ifdef PTPD_PCAP
	if (rtOpts->transport == IEEE_802_3) {
		netPath->headerOffset = PACKET_BEGIN_ETHER;
#ifdef HAVE_STRUCT_ETHER_ADDR_OCTET
		memcpy(netPath->etherDest.octet, ether_aton(PTP_ETHER_DST), ETHER_ADDR_LEN);
		memcpy(netPath->peerEtherDest.octet, ether_aton(PTP_ETHER_PEER), ETHER_ADDR_LEN);
#else
		memcpy(netPath->etherDest.ether_addr_octet, ether_aton(PTP_ETHER_DST), ETHER_ADDR_LEN);
		memcpy(netPath->peerEtherDest.ether_addr_octet, ether_aton(PTP_ETHER_PEER), ETHER_ADDR_LEN);
#endif /* HAVE_STRUCT_ETHER_ADDR_OCTET */
	} else
#endif
		netPath->headerOffset = PACKET_BEGIN_UDP;

	/* open sockets */
	if ((netPath->eventSock = socket(PF_INET, SOCK_DGRAM, 
					 IPPROTO_UDP)) < 0
	    || (netPath->generalSock = socket(PF_INET, SOCK_DGRAM, 
					      IPPROTO_UDP)) < 0) {
		PERROR("failed to initialize sockets");
		return FALSE;
	}

	if(!testInterface(rtOpts->ifaceName, rtOpts))
		return FALSE;

	netPath->interfaceInfo.addressFamily = AF_INET;

	/* the if is here only to get rid of an unused result warning. */
	if( getInterfaceInfo(rtOpts->ifaceName, &netPath->interfaceInfo)!= 1)
		return FALSE;

	/* No HW address, we'll use the protocol address to form interfaceID -> clockID */
	if( !netPath->interfaceInfo.hasHwAddress && netPath->interfaceInfo.hasAfAddress ) {
		uint32_t addr = netPath->interfaceInfo.afAddress.s_addr;
		memcpy(netPath->interfaceID, &addr, 2);
		memcpy(netPath->interfaceID + 4, &addr + 2, 2);
	/* Initialise interfaceID with hardware address */
	} else {
		    memcpy(&netPath->interfaceID, &netPath->interfaceInfo.hwAddress, 
			    sizeof(netPath->interfaceID) <= sizeof(netPath->interfaceInfo.hwAddress) ?
				    sizeof(netPath->interfaceID) : sizeof(netPath->interfaceInfo.hwAddress)
			    );
	}

	DBG("Listening on IP: %s\n",inet_ntoa(netPath->interfaceInfo.afAddress));

#ifdef PTPD_PCAP
	if (rtOpts->pcap == TRUE) {
		int promisc = (rtOpts->transport == IEEE_802_3 ) ? 1 : 0;
		if ((netPath->pcapEvent = pcap_open_live(rtOpts->ifaceName,
							 PACKET_SIZE, promisc,
							 PCAP_TIMEOUT,
							 errbuf)) == NULL) {
			PERROR("failed to open event pcap");
			return FALSE;
		}
		if (pcap_compile(netPath->pcapEvent, &program, 
				 ( rtOpts->transport == IEEE_802_3 ) ?
				    "ether proto 0x88f7":
				 ( rtOpts->ip_mode != IPMODE_MULTICAST ) ?
					 "udp port 319" :
				 "host (224.0.1.129 or 224.0.0.107) and udp port 319" ,
				 1, 0) < 0) {
			PERROR("failed to compile pcap event filter");
			pcap_perror(netPath->pcapEvent, "ptpd2");
			return FALSE;
		}
		if (pcap_setfilter(netPath->pcapEvent, &program) < 0) {
			PERROR("failed to set pcap event filter");
			return FALSE;
		}
		pcap_freecode(&program);
		if ((netPath->pcapEventSock = 
		     pcap_get_selectable_fd(netPath->pcapEvent)) < 0) {
			PERROR("failed to get pcap event fd");
			return FALSE;
		}		
		if ((netPath->pcapGeneral = pcap_open_live(rtOpts->ifaceName,
							   PACKET_SIZE, promisc,
							   PCAP_TIMEOUT,
							 errbuf)) == NULL) {
			PERROR("failed to open general pcap");
			return FALSE;
		}
		if (rtOpts->transport != IEEE_802_3) {
			if (pcap_compile(netPath->pcapGeneral, &program,
					 ( rtOpts->ip_mode != IPMODE_MULTICAST ) ?
						 "udp port 320" :
					 "host (224.0.1.129 or 224.0.0.107) and udp port 320" ,
					 1, 0) < 0) {
				PERROR("failed to compile pcap general filter");
				pcap_perror(netPath->pcapGeneral, "ptpd2");
				return FALSE;
			}
			if (pcap_setfilter(netPath->pcapGeneral, &program) < 0) {
				PERROR("failed to set pcap general filter");
				return FALSE;
			}
			pcap_freecode(&program);
			if ((netPath->pcapGeneralSock = 
			     pcap_get_selectable_fd(netPath->pcapGeneral)) < 0) {
				PERROR("failed to get pcap general fd");
				return FALSE;
			}
		}
	}
#endif

#ifdef PTPD_PCAP
	if(rtOpts->transport == IEEE_802_3) {
		close(netPath->eventSock);
		netPath->eventSock = -1;
		close(netPath->generalSock);
		netPath->generalSock = -1;
		/* TX timestamp is not generated for PCAP mode and Ethernet transport */
#ifdef SO_TIMESTAMPING
		netPath->txTimestampFailure = TRUE;
#endif /* SO_TIMESTAMPING */
	} else {
#endif
		/* save interface address for IGMP refresh */
		netPath->interfaceAddr = netPath->interfaceInfo.afAddress;

		DBG("Local IP address used : %s \n", inet_ntoa(netPath->interfaceInfo.afAddress));

		temp = 1;			/* allow address reuse */
		if (setsockopt(netPath->eventSock, SOL_SOCKET, SO_REUSEADDR, 
			       &temp, sizeof(int)) < 0
		    || setsockopt(netPath->generalSock, SOL_SOCKET, SO_REUSEADDR, 
				  &temp, sizeof(int)) < 0) {
			DBG("failed to set socket reuse\n");
		}
		/* bind sockets */
		/*
		 * need INADDR_ANY to allow receipt of multi-cast and uni-cast
		 * messages
		 */

		/* why??? */
		if (rtOpts->pidAsClockId) {
			if (inet_pton(AF_INET, DEFAULT_PTP_DOMAIN_ADDRESS, &addr.sin_addr) < 0) {
				PERROR("failed to convert address");
				return FALSE;
			}
		} else
			addr.sin_addr.s_addr = htonl(INADDR_ANY);

		addr.sin_family = AF_INET;
		addr.sin_port = htons(PTP_EVENT_PORT);
		if (bind(netPath->eventSock, (struct sockaddr *)&addr, 
			sizeof(struct sockaddr_in)) < 0) {
			PERROR("failed to bind event socket");
			return FALSE;
		}
		addr.sin_port = htons(PTP_GENERAL_PORT);
		if (bind(netPath->generalSock, (struct sockaddr *)&addr, 
			sizeof(struct sockaddr_in)) < 0) {
			PERROR("failed to bind general socket");
			return FALSE;
		}

#ifdef USE_BINDTODEVICE
#ifdef linux
		/*
		 * The following code makes sure that the data is only
		 * received on the specified interface.  Without this option,
		 * it's possible to receive PTP from another interface, and
		 * confuse the protocol.  Calling bind() with the IP address
		 * of the device instead of INADDR_ANY does not work.
		 *
		 * More info:
		 *   http://developerweb.net/viewtopic.php?id=6471
		 *   http://stackoverflow.com/questions/1207746/problems-with-so-bindtodevice-linux-socket-option
		 */

		if ( rtOpts->ip_mode != IPMODE_HYBRID )
		if (setsockopt(netPath->eventSock, SOL_SOCKET, SO_BINDTODEVICE,
				rtOpts->ifaceName, strlen(rtOpts->ifaceName)) < 0
			|| setsockopt(netPath->generalSock, SOL_SOCKET, SO_BINDTODEVICE,
				rtOpts->ifaceName, strlen(rtOpts->ifaceName)) < 0){
			PERROR("failed to call SO_BINDTODEVICE on the interface");
			return FALSE;
		}
#endif
#endif

		/* Set socket dscp */
		if(rtOpts->dscpValue) {

			if (setsockopt(netPath->eventSock, IPPROTO_IP, IP_TOS,
				 &rtOpts->dscpValue, sizeof(int)) < 0
			    || setsockopt(netPath->generalSock, IPPROTO_IP, IP_TOS,
				&rtOpts->dscpValue, sizeof(int)) < 0) {
				    PERROR("Failed to set socket DSCP bits");
				    return FALSE;
				}
		}

		/* send a uni-cast address if specified (useful for testing) */
		if(!hostLookup(rtOpts->unicastAddress, &netPath->unicastAddr)) {
	                netPath->unicastAddr = 0;
		}


		if(rtOpts->ip_mode != IPMODE_UNICAST)  {

			/* init UDP Multicast on both Default and Peer addresses */
			if (!netInitMulticast(netPath, rtOpts))
				return FALSE;

			/* set socket time-to-live  */
			if(!netSetMulticastTTL(netPath->eventSock,rtOpts->ttl) ||
			    !netSetMulticastTTL(netPath->generalSock,rtOpts->ttl))
				return FALSE;

			/* start tracking TTL */
			netPath->ttlEvent = rtOpts->ttl;
			netPath->ttlGeneral = rtOpts->ttl;
		}

#ifdef SO_TIMESTAMPING
			/* Reset the failure indicator when (re)starting network */
			netPath->txTimestampFailure = FALSE;
			/* for SO_TIMESTAMPING we're receiving transmitted packets via ERRQUEUE */
			temp = 0;
#else
			/* enable loopback */
			temp = 1;
#endif

		/* make timestamps available through recvmsg() */
		if (!netInitTimestamping(netPath,rtOpts)) {
			ERROR("Failed to enable packet time stamping\n");
			return FALSE;
		}

#ifdef SO_TIMESTAMPING
		/* If we failed to initialise SO_TIMESTAMPING, enable mcast loopback */
		if(netPath->txTimestampFailure)
			temp = 1;
#endif

			if(!netSetMulticastLoopback(netPath, temp)) {
				return FALSE;
			}

#ifdef PTPD_PCAP
	}
#endif

	/* Compile ACLs */
	if(rtOpts->timingAclEnabled) {
    		freeIpv4AccessList(&netPath->timingAcl);
		netPath->timingAcl=createIpv4AccessList(rtOpts->timingAclPermitText,
			rtOpts->timingAclDenyText, rtOpts->timingAclOrder);
	}
	if(rtOpts->managementAclEnabled) {
		freeIpv4AccessList(&netPath->managementAcl);
		netPath->managementAcl=createIpv4AccessList(rtOpts->managementAclPermitText,
			rtOpts->managementAclDenyText, rtOpts->managementAclOrder);
	}

	return TRUE;
}
Example #10
0
int main(int argc, char **argv)
{
	pcap_t *fp;
	char errbuf[PCAP_ERRBUF_SIZE];
	char *source = NULL;
	char *ofilename = NULL;
	char *filter = NULL;
	int i;
	pcap_dumper_t *dumpfile;
	struct bpf_program fcode;
	bpf_u_int32 NetMask;
	int res;
	struct pcap_pkthdr *header;
	const u_char *pkt_data;
	
#ifdef WIN32
	/* Load Npcap and its functions. */
	if (!LoadNpcapDlls())
	{
		fprintf(stderr, "Couldn't load Npcap\n");
		exit(1);
	}
#endif

	if (argc == 1)
	{
		usage();
		return -1;
	}

	/* Parse parameters */
	for(i=1;i < argc; i+= 2)
	{
		switch (argv[i] [1])
		{
			case 's':
			{
				source=argv[i+1];
			};
			break;
			
			case 'o':
			{
				ofilename=argv[i+1];
			};
			break;

			case 'f':
			{
				filter=argv[i+1];
			};
			break;
		}
	}
	
	// open a capture from the network
	if (source != NULL)
	{
		if ((fp = pcap_open_live(source,		// name of the device
			65536,								// portion of the packet to capture. 
												// 65536 grants that the whole packet will be captured on all the MACs.
			1,									// promiscuous mode (nonzero means promiscuous)
			1000,								// read timeout
			errbuf								// error buffer
			)) == NULL)
		{
			fprintf(stderr,"\nUnable to open the adapter.\n");
			return -2;
		}
	}
	else usage();

	if (filter != NULL)
	{
		// We should loop through the adapters returned by the pcap_findalldevs_ex()
		// in order to locate the correct one.
		//
		// Let's do things simpler: we suppose to be in a C class network ;-)
		NetMask=0xffffff;

		//compile the filter
		if(pcap_compile(fp, &fcode, filter, 1, NetMask) < 0)
		{
			fprintf(stderr,"\nError compiling filter: wrong syntax.\n");

			pcap_close(fp);
			return -3;
		}

		//set the filter
		if(pcap_setfilter(fp, &fcode)<0)
		{
			fprintf(stderr,"\nError setting the filter\n");

			pcap_close(fp);
			return -4;
		}

	}

	//open the dump file
	if (ofilename != NULL)
	{
		dumpfile= pcap_dump_open(fp, ofilename);

		if (dumpfile == NULL)
		{
			fprintf(stderr,"\nError opening output file\n");

			pcap_close(fp);
			return -5;
		}
	}
	else usage();

	//start the capture
 	while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
	{

		if(res == 0)
		/* Timeout elapsed */
		continue;

		//save the packet on the dump file
		pcap_dump((unsigned char *) dumpfile, header, pkt_data);

	}

	pcap_close(fp);
	pcap_dump_close(dumpfile);

	return 0;
}
Example #11
0
static void probe_host(const char *host)
{
	struct sockaddr_in sin;
	char pcap_errbuf[PCAP_ERRBUF_SIZE];
	struct pcap_pkthdr pkthdr;
	const uint8_t *data;
	struct bpf_program fp;
	pcap_t *ph;
	int fd;

	ph = pcap_create(iface, pcap_errbuf);
	if (ph == NULL) {
		perror("pcap_create");
		goto err1;
	}

	if (pcap_setnonblock(ph, 1, pcap_errbuf) == -1) {
		perror("pcap_setnonblock");
		goto err2;
	}

	if (pcap_setfilter(ph, &fp) == -1) {
		pcap_perror(ph, "pcap_setfilter");
		goto err2;
	}

	if (pcap_activate(ph) != 0) {
		pcap_perror(ph, "pcap_activate");
		goto err2;
	}

	if (pcap_compile(ph, &fp, "src host 127.0.0.1 and tcp and src port 80",
			 1, PCAP_NETMASK_UNKNOWN) == -1) {
		pcap_perror(ph, "pcap_compile");
		goto err2;
	}

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0) {
		perror("socket");
		goto err3;
	}

	memset(&sin, 0, sizeof(sin));
	sin.sin_family		= AF_INET;
	sin.sin_port		= htons(port);
	sin.sin_addr.s_addr	= inet_addr(host);

	if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
		perror("connect");
		goto err4;
	}

	for (;;) {
		data = pcap_next(ph, &pkthdr);
		if (data == NULL)
			break;
		if (parse_packet(host, data))
			break;
	}

	close(fd);

err4:
	close(fd);
err3:
	pcap_freecode(&fp);
err2:
	pcap_close(ph);
err1:
	return;
}
Example #12
0
static void process_infile(const std::string &expression,const char *device,const std::string &infile)
{
    char error[PCAP_ERRBUF_SIZE];
    pcap_t *pd=0;
    int dlt=0;
    pcap_handler handler;

#ifdef HAVE_INFLATER
    if(inflaters==0) inflaters = build_inflaters();
#endif

    if (infile!=""){
        std::string file_path = infile;
        // decompress input if necessary
#ifdef HAVE_INFLATER
        for(inflaters_t::const_iterator it = inflaters->begin(); it != inflaters->end(); it++) {
            if((*it)->appropriate(infile)) {
                int fd = (*it)->invoke(infile);
                file_path = ssprintf("/dev/fd/%d", fd);
                if(fd < 0) {
                    std::cerr << "decompression of '" << infile << "' failed" << std::endl;
                    exit(1);
                }
                if(access(file_path.c_str(), R_OK)) {
                    std::cerr << "decompression of '" << infile << "' is not available on this system" << std::endl;
                    exit(1);
                }
                break;
            }
        }
#endif
	if ((pd = pcap_open_offline(file_path.c_str(), error)) == NULL){	/* open the capture file */
	    die("%s", error);
	}
	dlt = pcap_datalink(pd);	/* get the handler for this kind of packets */
	handler = find_handler(dlt, infile.c_str());
    } else {
	/* if the user didn't specify a device, try to find a reasonable one */
	if (device == NULL){
	    if ((device = pcap_lookupdev(error)) == NULL){
		die("%s", error);
	    }
	}

	/* make sure we can open the device */
	if ((pd = pcap_open_live(device, SNAPLEN, !opt_no_promisc, 1000, error)) == NULL){
	    die("%s", error);
	}
#if defined(HAVE_SETUID) && defined(HAVE_GETUID)
	/* drop root privileges - we don't need them any more */
	if(setuid(getuid())){
	    perror("setuid");
	}
#endif
	/* get the handler for this kind of packets */
	dlt = pcap_datalink(pd);
	handler = find_handler(dlt, device);
    }

    DEBUG(20) ("filter expression: '%s'",expression.c_str());

    /* install the filter expression in libpcap */
    struct bpf_program	fcode;
    if (pcap_compile(pd, &fcode, expression.c_str(), 1, 0) < 0){
	die("%s", pcap_geterr(pd));
    }

    if (pcap_setfilter(pd, &fcode) < 0){
	die("%s", pcap_geterr(pd));
    }

    /* initialize our flow state structures */

    /* set up signal handlers for graceful exit (pcap uses onexit to put
     * interface back into non-promiscuous mode
     */
    portable_signal(SIGTERM, terminate);
    portable_signal(SIGINT, terminate);
#ifdef SIGHUP
    portable_signal(SIGHUP, terminate);
#endif

    /* start listening or reading from the input file */
    if (infile == "") DEBUG(1) ("listening on %s", device);
    if (pcap_loop(pd, -1, handler, (u_char *)tcpdemux::getInstance()) < 0){
	
	die("%s: %s", infile.c_str(),pcap_geterr(pd));
    }
}
Example #13
0
int main(int argc, char *argv[])
{
    int n; 
    char errbuf[LIBNET_ERRBUF_SIZE];
    /* pcap variables */
    char perrbuf[PCAP_ERRBUF_SIZE];
    char *dev ="eth0";   /* default if */
    char filter[MAXTEXT]; 
    u_short sport;      /* remote port from which syn-ack is coming */
    struct bpf_program fp;      /* hold compiled program     */
    bpf_u_int32 maskp;          /* subnet mask               */
    bpf_u_int32 netp;           /* ip                        */
    void usage(char *);

    /* Initialize the library.  Root priviledges are required.  */
    l = libnet_init(
            LIBNET_RAW4,                            /* injection type */
            NULL,                                   /* network interface */
            errbuf);                                /* errbuf */

    if (l == NULL)
    {
        fprintf(stderr, "libnet_init() failed: %s\n", errbuf);
        exit(EXIT_FAILURE);
    }

    libnet_seed_prand(l);
    tcp = 0; 
    ip = 0;

    if (argc != 5) {
                usage(argv[0]);
                exit(EXIT_FAILURE);
    }

    while ((n = getopt(argc, argv, "p:i:")) != EOF)
    {
        switch (n)
        {
         case 'p':
           sport = (u_short) atoi(optarg);  /* local port */
           break;
         case 'i':
           dev = optarg;  /* device */
           break;
         default:
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    pcap_lookupnet(dev,&netp,&maskp,perrbuf);  

    /* open device for reading in promiscuous mode */ 
    descr = pcap_open_live(dev,BUFSIZ,1,-1,perrbuf);
    if(descr == NULL)
    { printf("pcap_open_live(): %s\n",perrbuf); exit(1); }

    /* Lets try and compile the program.. non-optimized */
    sprintf(filter, "src port %d and tcp[13] == 18", sport); /* only SYN-ACK */
    /* printf("The filter is: %s\n", filter);  */
    if(pcap_compile(descr,&fp,filter,0,netp) == -1)
    { fprintf(stderr,"Error calling pcap_compile\n"); exit(1); }

    /* set the compiled program as the filter */
    if(pcap_setfilter(descr,&fp) == -1)
    { fprintf(stderr,"Error setting filter\n"); exit(1); }

    pcap_loop(descr,-1,my_callback,NULL);
    pcap_close(descr);

    libnet_destroy(l);

    return (EXIT_SUCCESS);
}
Example #14
0
int main(int argc, char *argv[])
{
	int ret;
	char* file_name = NULL;
	char* dev = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program comp_filter_exp;		/* The compiled filter expression */
	char filter_exp[] = "ether dst 91:E0:F0:00:0e:80";	/* The filter expression */
	struct pcap_pkthdr header;	/* header pcap gives us */
	const u_char* packet;		/* actual packet */

	signal(SIGINT, sigint_handler);

	int c;
	while((c = getopt(argc, argv, "hi:f:")) > 0) 
	{
		switch (c) 
		{
		case 'h': 
			help();
			break;
		case 'i':
			dev = strdup(optarg);
			break;
		case 'f':
			file_name = strdup(optarg);
			break;
		default:
          		fprintf(stderr, "Unrecognized option!\n");
		}
	}

	if ((NULL == dev) || (NULL == file_name))
		help();

	if (create_socket())
	{
		fprintf(stderr, "Socket creation failed.\n");
		return (errno);
	}

	report_domain_status();

	fprintf(stdout,"Waiting for talker...\n");
	await_talker();	

#ifdef DEBUG
	fprintf(stdout,"Send ready-msg...\n");
#endif
	send_ready();
		
#ifdef LIBSND
	SF_INFO* sf_info = (SF_INFO*)malloc(sizeof(SF_INFO));

	memset(sf_info, 0, sizeof(SF_INFO));
	
	sf_info->samplerate = SAMPLES_PER_SECOND;
	sf_info->channels = CHANNELS;
	sf_info->format = SF_FORMAT_WAV | SF_FORMAT_PCM_24;

	if (0 == sf_format_check(sf_info))
	{
		fprintf(stderr, "Wrong format.");
		return -1;
	}
			
	if (NULL == (snd_file = sf_open(file_name, SFM_WRITE, sf_info)))
	{
		fprintf(stderr, "Could not create file.");
		return -1;
	}
	fprintf(stdout,"Created file called %s\n", file_name);	
#endif

#ifdef PCAP		
	/** session, get session handler */
	/* take promiscuous vs. non-promiscuous sniffing? (0 or 1) */
	handle = pcap_open_live(dev, BUFSIZ, 1, -1, errbuf);
	if (NULL == handle) 
	{
		fprintf(stderr, "Could not open device %s: %s\n", dev, errbuf);
		return -1;
	}

#ifdef DEBUG
	fprintf(stdout,"Got session handler.\n");
#endif
	/* compile and apply filter */
	if (-1 == pcap_compile(handle, &comp_filter_exp, filter_exp, 0, PCAP_NETMASK_UNKNOWN))
	{
		fprintf(stderr, "Could not parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return -1;
	}

	if (-1 == pcap_setfilter(handle, &comp_filter_exp)) 
	{
		fprintf(stderr, "Could not install filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return -1;
	}

#ifdef DEBUG
	fprintf(stdout,"Compiled and applied filter.\n");
#endif

	/** loop forever and call callback-function for every received packet */
	pcap_loop(handle, -1, pcap_callback, NULL);
#endif

	return 0;
}
Example #15
0
int main (int argc, char *argv[]) {
    char           *dev = NULL;
    char		errbuf    [ERRBUF_SIZE];	/* Error string */
    struct bpf_program fp;	/* The compiled filter */
    char		filter_exp[] = "ether proto 0x88d9"; //"port 80";	/* The filter expression */
    bpf_u_int32	mask;	/* Our netmask */
    bpf_u_int32	net;	/* Our IP */
    struct pcap_pkthdr header;
    const u_char   *packet;
    int c,i;
    libnet_t       *l;
    libnet_ptag_t   eth_ptag = 0;
    u_char buf[0x100];
    struct itimerspec tspec;

    memset(&tspec, 0, sizeof(tspec));
    tspec.it_value.tv_sec = 3;

    while ((c = getopt(argc, argv, "t:i:hvu")) != EOF) {
        switch (c) {
        case 'i': // interface
            dev = optarg;
            break;
        case 't': // timeout
            i = atoi(optarg);
            if( i>0 ) {
#ifndef __linux__
                if( i > PCAP_PERIOD ) i-=PCAP_PERIOD-10; // try to be more precise
#endif
                tspec.it_value.tv_sec = i/1000;
                tspec.it_value.tv_nsec = (i%1000)*1000000;
            }
            break;
        case 'v': // verbosity
            verbose++;
            break;
        case 'u': // unicode support
            unicode = 1;
            break;
        case 'h': // show usage
            usage(argv[0]);
            exit(EXIT_SUCCESS);
        default:
            exit(EXIT_FAILURE);
        }
    }
    argc -= optind;
    argv += optind;

    if( argc > 1 ) {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }
    if( argc == 1 ) {
        if( strlen(argv[0]) != 17 ) {
            fprintf(stderr, "Invalid MAC-address: '%s'\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        mac_to_find = argv[0];
    }

    setlinebuf(stdout);

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

    printf("interface %s\n",dev);

    l = libnet_init(LIBNET_LINK, dev, errbuf);
    if (l == NULL) {
        fprintf(stderr, "libnet_init() failed: %s", errbuf);
        exit(EXIT_FAILURE);
    }

    /* Find the properties for the device */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
        fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
        net = 0;
        mask = 0;
    }

    struct ether_addr *ha = NULL;
    if ((ha = (struct ether_addr *) libnet_get_hwaddr(l)) == NULL) {
        fprintf(stderr, "%s", libnet_geterror(l));
        exit(EXIT_FAILURE);
    }

    // LLTP magic packet
    char* payload = "\x01\x00\x00\x00\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00";
    char* hwdst   = "\xff\xff\xff\xff\xff\xff";

    memcpy(buf,payload,18);
    memcpy(buf+10, ha, 6);

    gettimeofday(&start_time, NULL);
    memcpy(buf+16, &start_time.tv_sec, 2); // emulate sequence number

    eth_ptag = libnet_build_ethernet(
                   hwdst, /* ethernet destination */
                   ha->ether_addr_octet,
                   /* ethernet source */
                   0x88d9,        /* protocol type */
                   buf,       /* payload */
                   18,    /* payload size */
                   l,     /* libnet handle */
                   0);    /* libnet id */
    if (eth_ptag == -1) {
        fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }
    /*
     * Write it to the wire.
     */
    c = libnet_write(l);

    if (c == -1) {
        fprintf(stderr, "Write error: %s\n", libnet_geterror(l));
        libnet_destroy(l);
        exit(EXIT_FAILURE);
    }

    /* Open the session in promiscuous mode */
    pcap_handle = pcap_open_live(dev, BUFSIZ, 1, PCAP_PERIOD, errbuf);
    if (pcap_handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        libnet_destroy(l);
        return (2);
    }
    /* Compile and apply the filter */
    if (pcap_compile(pcap_handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle));
        libnet_destroy(l);
        return (2);
    }
    if (pcap_setfilter(pcap_handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(pcap_handle));
        libnet_destroy(l);
        return (2);
    }

    signal(SIGALRM, on_alarm);

    gettimeofday(&start_time, NULL);

    timer_create(CLOCK_MONOTONIC, NULL, &timer_id);
    timer_settime(timer_id, 0, &tspec, NULL);

    // don't know why, but pcap_dispatch does not return control to main after
    // timeout expires. so, we use nonblocking pcap on linux.
#ifdef __linux__
    pcap_setnonblock(pcap_handle, 1, errbuf);
#endif

    while( !do_stop ) {
        pcap_dispatch(pcap_handle, -1, got_packet, NULL);
#ifdef __linux__
        usleep(1000);
#endif
    }

    pcap_close(pcap_handle);

    i = tv_diff2msec(NULL);

    printf("found %d hosts in %d.%d seconds", nhosts, i/1000, i%1000);

    if( mac_to_find && !mac_found ) {
        printf(", but '%s' is not found.\n", mac_to_find);
    } else {
        puts("");
    }

    return (0);
}
Example #16
0
int main(int argc, char *argv[])
{
    pcap_t *handle;                 /* Session handle */
    char errbuf[PCAP_ERRBUF_SIZE];	/* Error string */
    struct bpf_program fp;          /* The compiled filter */
    char filter_exp[255] = "";           /* The filter expression */
    bpf_u_int32 mask;               /* Our netmask */
    bpf_u_int32 net;                /* Our IP */
    
    
    int i;
    for (i=1 ; i<argc ; i++)
    {
        if (strcmp(argv[i], "-i") == 0)
        {
            dev = argv[i+1];
            i = i + 1;
        }
        else if (strcmp(argv[i], "--victim-ip") == 0)
        {
            victim_ip = argv[i+1];
            i = i + 1;
        }
        else if (strcmp(argv[i], "--victim-ethernet") == 0)
        {
            victim_ethernet = argv[i+1];
            i = i + 1;
            
        }
        
        else if (strcmp(argv[i], "--relayer-ip") == 0)
        {
            relayer_ip = argv[i+1];
            i = i + 1;
        }
        
        else if (strcmp(argv[i], "--relayer-ethernet") == 0)
        {
            relayer_ethernet = argv[i+1];
            i = i + 1;
        }

        else
        {
            printf("%s\n", argv[i-1]);
            printf("Invalid Commandline parameter: %s\n", argv[i]);
            return 1;
        }
    }
    
    if (victim_ethernet == NULL || relayer_ethernet == NULL)
    {
        fprintf(stderr, "You have to specify both victim and relayer ethernet address\n");
        exit(1);
    }
    
    if (victim_ip == NULL || relayer_ip == NULL)
    {
        fprintf(stderr, "No IP specified for either victim or realyer\n");
        exit(1);
    }
    
    

    /**************
     * INIT STATE *
     **************/
    printf("    Initilizing Reflector\n");

    if (dev == NULL) {
        dev = pcap_lookupdev(errbuf);
    }
    
    if (dev == NULL) {
        fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
        return(2);
    }
    
    /* Find the properties for the device */
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
        fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
        net = 0;
        mask = 0;
    }
    
    /* Open the session in promiscuous mode */
    handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
    if (handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        exit(1);
    }
    
    /* Generate filter: dst (VIC or REL) this way we get the
     * information to the victim and to the relay so we can
     * reflecting part later. */ 
    strcat(filter_exp, "dst (");
    strcat(filter_exp, relayer_ip);
    strcat(filter_exp, " or ");
    strcat(filter_exp, victim_ip);
    strcat(filter_exp, ")");
    
    printf("    Filter Added: %s\n", filter_exp);
    
    /* Compile and apply the filter */
    if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
        exit(1);
    }
    if (pcap_setfilter(handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
        exit(1);
    }
    
    
    /*******************
     * LISTENING STATE *
     *    Grab packets *
     *******************/
    printf("    Start Listening for packets\n");
    pcap_loop(handle, -1, got_packet, NULL);
    pcap_close(handle);
    
    return(0);
    
}
Example #17
0
int main(int argc, char *argv[])
{
	char *mode = argv[0];       /* Name of this binary, cc-mon or bw-mon? */
	char *dev = argv[1];			  /* The device to sniff on */
	char *filter_exp = argv[2];	/* The filter expression */
	
	char errbuf[PCAP_ERRBUF_SIZE];	/* Error string */
	struct bpf_program fp;			/* The compiled filter */
	pcap_t *handle;					    /* Session handle */
	bpf_u_int32 mask;				    /* Our netmask */
	bpf_u_int32 net;				    /* Our IP */
	struct pcap_pkthdr hdr;			/* The header that pcap gives us */
	const u_char *packet;			  /* The actual packet */
	pthread_t reporter; 			  /* timed reporting of measurements */
	
	if (argc < 3)
		usage(mode);
	
	// print given command, so that we can log everything by redirecting to a file
	printf("%s ",argv[0]);
	printf("%s ",argv[1]);
	printf("%s\n\n",argv[2]);
	
	// remove possible prepended paths
	mode += (strlen(mode) - strlen("cc-mon"));

	/* signal handler will close nfq hooks on exit */
	if(signal(SIGINT, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);
	if(signal(SIGHUP, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);
	if(signal(SIGTERM, sig_handler) == SIG_IGN)
		signal(SIGINT, SIG_IGN);

	/* Find the properties for the device */
	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
		net = 0;
		mask = 0;
	}
	/* Open the session, no promiscuous mode: they're our packets */
	handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
	if (handle == NULL) {
		fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
		return(2);
	}
	/* Compile and apply the filter */
	if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
		fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return(2);
	}
	if (pcap_setfilter(handle, &fp) == -1) {
		fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return(2);
	}

	/* init time spec */
	gettimeofday(&last_time, NULL);
	gettimeofday(&first_time, NULL);

	/* loop in chosen mode until sigint */
	if (0 == strcmp("bw-mon", mode)) {
		pthread_create(&reporter, NULL, reporter_thread, NULL);
		pcap_loop(handle, -1, throughput_cb, NULL);
	}
	else {
		pcap_loop(handle, -1, metadata_cb, NULL);
	}

	pcap_close(handle);

	exit(0);
}
Example #18
0
int main()
{
    char errbuf[PCAP_ERRBUF_SIZE];
    char *dev;
    pcap_t *handle;
    struct bpf_program fp; // compiled filter program

     bpf_u_int32 maskp;             //subnet mask
     bpf_u_int32 netp;             // ip


    /* Get a device */
    dev = pcap_lookupdev(errbuf);
    if(NULL == dev)
    {
        printf("Error : [%s]\n", errbuf);
        exit(1);
    }
    else
    {
        printf("===========================================\n");
        printf("Network Device Name : [%s]\n", dev);
        printf("===========================================\n");
    }

     /* Get the network address and mask */
     pcap_lookupnet(dev, &netp, &maskp, errbuf);

    /* open device for reading in promiscuous mode */
    handle = pcap_open_live(dev, 1500, 1, 1000, errbuf);

    if(NULL == handle)  // failed to open device
    {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        exit(EXIT_FAILURE);
    }

    else  // check if it is ethernet
    {
        if (pcap_datalink(handle) != DLT_EN10MB)
        {
            fprintf(stderr, "%s is not an Ethernet\n", dev);
            exit(EXIT_FAILURE);
        }
        else
        {
            /* compile the filter expression */
            if (pcap_compile(handle, &fp, "ip", 0, netp) == -1)
            {
                fprintf(stderr, "Couldn't parse filter %s: %s\n",
                "ip", pcap_geterr(handle));
                exit(EXIT_FAILURE);
            }
        }
    }

    /* apply the compiled filter */
    if (pcap_setfilter(handle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n",
            "ip", pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }


    /* loop */
    pcap_loop(handle, 0, got_packet, NULL);

    return 0;
}
Example #19
0
void *networkScan(void *arg)
{
	bpf_u_int32 netaddr=0, mask=0;    /* To Store network address and netmask   */ 
	struct bpf_program filter;        /* Place to store the BPF filter program  */ 
	char errbuf[PCAP_ERRBUF_SIZE];    /* Error buffer                           */ 
	pcap_t *descr = NULL;             /* Network interface handler              */
	char *ethernet = DEVICENAME;
	device_info dev_info;				/*my ethernet address*/
	device_info gate_info;
	NodeStatus node_status;			//노드 정보
	network_grub_args *n_args = 0;
	sendkill_grub_args k_args;

	pthread_t t_id1 = 0;
	pthread_t t_id2 = 0;
	int state1 = 0;
	int state2 = 0;
	receiver_grub_args grub;
	int i;

	memset(&node_status, 0, sizeof(NodeStatus));

	n_args = (network_grub_args*)arg;

	memset(errbuf,0,PCAP_ERRBUF_SIZE); 
	/* Open network device for packet capture */ 
	if ((descr = pcap_open_live(ethernet, MAXBYTES2CAPTURE, 0,  512, errbuf))==NULL){
		fprintf(stderr, "1ERROR: %s\n", errbuf);
		exit(1);
	}

	/* Look up info from the capture device. */ 
	if( pcap_lookupnet(ethernet , &netaddr, &mask, errbuf) == -1){
		fprintf(stderr, "2ERROR: %s\n", errbuf);
		exit(1);
	}

	/* Compiles the filter expression into a BPF filter program */ 
	if ( pcap_compile(descr, &filter, "tcp or arp", 1, mask) == -1){
		fprintf(stderr, "3ERROR: %s\n", pcap_geterr(descr) );
		exit(1);
	}

	/* Load the filter program into the packet capture device. */ 
	if (pcap_setfilter(descr,&filter) == -1){
		fprintf(stderr, "4ERROR: %s\n", pcap_geterr(descr) );
		exit(1);
	}

	get_device_info(&dev_info);

	k_args.n_args = n_args;
	k_args.gate_info = &gate_info;
	k_args.descr = descr;

	while(1) {			/* get gateway*/
		const unsigned char *packet = NULL; //packet
		struct pcap_pkthdr *p_pkthdr = 0;

		packet = make_arp_packet(dev_info, n_args->g_ip);

		pcap_sendpacket(descr, packet, 42);
		if (pcap_next_ex(descr, &p_pkthdr, &packet) != 1) {
			continue;
		}
		if(gateway_get(packet, n_args->g_ip, k_args.gate_info))
			break;
	}

	printf("GateWay MAC: ");
	for(i=0; i<6;i++) {
		printf("%02X:", k_args.gate_info->macaddr[i]);
	}

	printf("\nGateWay IP: ");
	for(i=0; i<4;i++) {
		printf("%d.", k_args.gate_info->ipaddr[i]);
	}
	puts("");

	grub.p_descr = descr;
	grub.p_node_status = &node_status;
	memcpy( (char*)&grub+8, (unsigned char*)&dev_info+6, 4);

	state1 = pthread_create(&t_id1, NULL, receiver, &grub);
	// puts("thread start");
	if (state1 != 0) {
		fprintf(stderr, "pthread_create() error\n");
		return 0;
	}

	state2 = pthread_create(&t_id2, NULL, send_kill_packet, &k_args);
	// puts("thread start");
	if (state2 != 0) {
		fprintf(stderr, "pthread_create() error\n");
		return 0;
	}

	// puts("thread start2");
	while(1) {
		traffic_flag = 0;
		memset(&node_status, 0, sizeof(NodeStatus));
		send_arp_packet(descr, dev_info);
		
		sleep(1);
		printf("network node status!!!!\n");
		for(i=1; i<255; i++) {
			if(node_status.node[i].status == 1) {
				printf("%6d", i);
			} else {
				printf("%6d", 0);
			}

			if(i%15 == 0)
				puts("");
		}
		puts("");

		traffic_flag = 1;

		sleep(30);
	}
	printf("main function exit\n");
	return 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;
}
Example #21
0
int passive_main(int argc, char *argv[])
{
	register int c, i;             /* Temporary variable   */
	bpf_u_int32 mask;              /* our netmask          */
	bpf_u_int32  net;              /* our IP adx           */
	uint32_t     npolls;           /* Number of pcap polls */
	char errbuf[PCAP_ERRBUF_SIZE]; /* pcap error buffer    */
	char *filter = NULL;           /* pcap filter          */
	pcap_t *handle;	               /* pcap handle          */
	struct bpf_program program;    /* BPF filter program   */

	npolls = NPOLLS_DEFAULT;
	port_threshold = PORT_THRESHOLD_DEFAULT;

	/* This is a trick to have long options only as this is the standard
       for how netstr works. However, if one wanted to unglue this piece
       it wouldn't be too difficult                                      */
	while (1) {
		static struct option long_options[] = {
			{"if", required_argument, 0, 'i'},
			{"threshold", required_argument, 0, 'T'},
			{"polls", required_argument, 0, 'p'},
			{"no-verify", no_argument, 0, 'V'},
			{"extra", no_argument, 0, 'X'},
			{0, 0, 0, 0}
		};

		int option_index = 0;

		c = getopt_long(argc, argv, "", long_options, &option_index);

		if (c == -1)
			break;

		switch (c) {
		case 'i':
			pcap_dev = optarg;
			break;
		case 'T':
			port_threshold = u_int_check(optarg);
			break;
		case 'p':
			npolls = u_int_check(optarg);
			break;
		case 'V':
			verify_port = 0;
			break;
		case 'X':
			xflag = 1;
			break;
		case 'u':
			printf("%s\n", PASSIVE_USAGE);
			return EXIT_SUCCESS;
			break;
		default:
			printf("%s\n", PASSIVE_USAGE);
			return EXIT_FAILURE;
			break;
		}
	}

	isroot_uid(); /* call utils  isroot_uid? */

	/* Strip off any none getopt arguments for pcap filter */
	if (!filter)
		filter = copy_argv(&argv[optind]);

	/* Initialize the interface to listen on */
	if ((!pcap_dev)
	    && ((pcap_dev = pcap_lookupdev(errbuf)) == NULL)) {
		fprintf(stderr, "%s\n", errbuf);
		return EXIT_FAILURE;
	}

	if ((handle = pcap_open_live(pcap_dev, 68, 0, 0, errbuf)) == NULL) {
		fprintf(stderr, "%s\n", errbuf);
		return EXIT_FAILURE;
	}

	pcap_lookupnet(pcap_dev, &net, &mask, errbuf);	/* Get netinfo */

	if (filter) {
		if (pcap_compile(handle, &program, filter, 0, net) == -1) {
			fprintf(stderr, "Error - `IP: pcap_compile() IP'\n");
			return EXIT_FAILURE;
		}

		if (pcap_setfilter(handle, &program) == -1) {
			fprintf(stderr, "Error - `IP: pcap_setfilter()'\n");
			return EXIT_FAILURE;
		}

		pcap_freecode(&program);
	}

	printf("Starting capturing engine on %s...\n", pcap_dev);
	pcap_loop(handle, npolls, passive_pcap4, NULL);
	printf("Closing capturing engine...\n");
	pcap_close(handle);
	print_hosts();

	return EXIT_SUCCESS;
}
Example #22
0
int
open_interface(char *iname)
{
	int i, j, x = 1;
	struct ifreq ifr;
	struct bpf_program fp;
	struct sockaddr_in baddr;
	char errbuf[PCAP_ERRBUF_SIZE], file[32], buf[256];

	if (if_num >= IF_MAX - 1)
		process_error(EX_RES, "too many interfaces");

	logd(LOG_DEBUG, "Trying to open interface: %s", iname);

	/* If we already have the interface, bind to the current server then */
	for (i = 0; i < if_num; i++) {
		if (strcmp(ifs[i]->name, iname) == 0) {
			/* If the interface is already binded to this server
			 * (appears twice). Ignore it. */
			if (ifs[i]->srv_num != srv_num) {
				ifs[i]->srv_num++;
				ifs[i]->srvrs = realloc(ifs[i]->srvrs, ifs[i]->srv_num * sizeof(int));
				ifs[i]->srvrs[ifs[i]->srv_num - 1] = srv_num - 1;
			}
			return 1;
		}
	}

	ifs[if_num] = malloc(sizeof(struct interface));
	if (ifs[if_num] == NULL)
		process_error(EX_MEM, "malloc");

	ifs[if_num]->idx = if_num;
	strlcpy(ifs[if_num]->name, iname, INTF_NAME_LEN);

	if (!get_mac(iname, (char *)ifs[if_num]->mac) ||
	    !get_ip(iname, &ifs[if_num]->ip, &ifs[if_num]->mask)) {
		free(ifs[if_num]);
		return 0;
	}
	ifs[i]->srv_num = 1;
	ifs[i]->srvrs = malloc(ifs[i]->srv_num * sizeof(int));
	if (ifs[i]->srvrs == NULL)
		process_error(EX_MEM, "malloc");
	ifs[i]->srvrs[0] = srv_num - 1;

	/* Looking for a free BPF device and open it */
	for (j = 0; j < 255; j++) {
		snprintf(file, sizeof(file), "/dev/bpf%d", j);
		ifs[if_num]->bpf = open(file, O_WRONLY);
		if (ifs[if_num]->bpf != -1 || errno != EBUSY)
			break;
	}
	/* Bind BPF to an interface */
	bzero(&ifr, sizeof(ifr));
	strlcpy(ifr.ifr_name, iname, sizeof(ifr.ifr_name));
	if (ioctl(ifs[if_num]->bpf, BIOCSETIF, (char *)&ifr) < 0)
		process_error(EX_RES, "Can't BIOCSETIF");

	if ((ifs[if_num]->cap = pcap_open_live(iname, max_packet_size, 0, 100, errbuf)) == NULL)
		process_error(EX_RES, "pcap_open_live(%s): %s", iname, errbuf);
	if (pcap_compile(ifs[if_num]->cap, &fp, "udp and dst port bootps", 0, 0) < 0)
		process_error(EX_RES, "pcap_compile");
	if (pcap_setfilter(ifs[if_num]->cap, &fp) < 0)
		process_error(EX_RES, "pcap_setfilter");

	if ((ifs[if_num]->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
		process_error(EX_RES, "socket for listener at %s: %s", iname, strerror(errno));

	if (setsockopt(ifs[if_num]->fd, SOL_SOCKET, SO_BROADCAST, (char *)&x, sizeof(x)) < 0)
		process_error(EX_RES, "setsockopt: SO_BROADCAST");
	if (setsockopt(ifs[if_num]->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&x, sizeof(x)) < 0)
		process_error(EX_RES, "setsockopt: SO_REUSEADDR");

	bzero(&baddr, sizeof(baddr));
	baddr.sin_family = AF_INET;
	baddr.sin_port = bootps_port;
	memcpy(&baddr.sin_addr.s_addr, &ifs[if_num]->ip, sizeof(ip_addr_t));
	if (bind(ifs[if_num]->fd, (struct sockaddr *)&baddr, sizeof(baddr)) < 0)
		process_error(EX_RES, "bind: %s", strerror(errno));

	logd(LOG_WARNING, "Listen at %s: %s/%s, %s", iname, print_ip(ifs[if_num]->ip, buf),
	     print_ip(ifs[if_num]->mask, buf + 16), print_mac(ifs[if_num]->mac, buf + 32));

	if_num++;
	return 1;
}
Example #23
0
int main ( int argc , char *argv[] )
{
	/* parameters parsing */
	int c;

	/* pcap */
	char 			errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program 	fp;
	char 			filter_exp[] = "ip and tcp";
	char 			*source = 0;
	char 			*filter = filter_exp;
	const unsigned char	*packet = 0;
	struct pcap_pkthdr 	header;

	/* packet dissection */
	struct ip	*ip;
	unsigned int	error;

	/* extra */
	unsigned int ipf,tcps;

	fprintf( stderr, "\n###########################" );
	fprintf( stderr, "\n#     libntoh Example     #" );
	fprintf( stderr, "\n# ----------------------- #" );
	fprintf( stderr, "\n# Written by Chema Garcia #" );
	fprintf( stderr, "\n# ----------------------- #" );
	fprintf( stderr, "\n#  http://safetybits.net  #" );
	fprintf( stderr, "\n#   [email protected]  #" );
	fprintf( stderr, "\n###########################\n" );

	fprintf( stderr, "\n[i] libntoh version: %s\n", ntoh_version() );

	if ( argc < 3 )
	{
		fprintf( stderr, "\n[+] Usage: %s <options>\n", argv[0] );
		fprintf( stderr, "\n+ Options:" );
		fprintf( stderr, "\n\t-i | --iface <val> -----> Interface to read packets from" );
		fprintf( stderr, "\n\t-f | --file <val> ------> File path to read packets from" );
		fprintf( stderr, "\n\t-F | --filter <val> ----> Capture filter (default: \"ip and tcp\")" );
		fprintf( stderr, "\n\t-c | --client ----------> Receive client data");
		fprintf( stderr, "\n\t-s | --server ----------> Receive server data\n\n");
		exit( 1 );
	}

	/* check parameters */
	while ( 1 )
	{
		int option_index = 0;
		static struct option long_options[] =
		{
		{ "iface" , 1 , 0 , 'i' } ,
		{ "file" , 1 , 0 , 'f' } ,
		{ "filter" , 1 , 0 , 'F' } ,
		{ "client" , 0 , 0 , 'c' },
		{ "server" , 0 , 0 , 's' },
		{ 0 , 0 , 0 , 0 } };

		if ( ( c = getopt_long( argc, argv, "i:f:F:cs", long_options, &option_index ) ) < 0 )
			break;

		switch ( c )
		{
			case 'i':
				source = optarg;
				handle = pcap_open_live( optarg, 65535, 1, 0, errbuf );
				break;

			case 'f':
				source = optarg;
				handle = pcap_open_offline( optarg, errbuf );
				break;

			case 'F':
				filter = optarg;
				break;

			case 'c':
				receive |= RECV_CLIENT;
				break;

			case 's':
				receive |= RECV_SERVER;
				break;
		}
	}

	if ( !receive )
		receive = (RECV_CLIENT | RECV_SERVER);

	if ( !handle )
	{
		fprintf( stderr, "\n[e] Error loading %s: %s\n", source, errbuf );
		exit( -1 );
	}

	if ( pcap_compile( handle, &fp, filter, 0, 0 ) < 0 )
	{
		fprintf( stderr, "\n[e] Error compiling filter \"%s\": %s\n\n", filter, pcap_geterr( handle ) );
		pcap_close( handle );
		exit( -2 );
	}

	if ( pcap_setfilter( handle, &fp ) < 0 )
	{
		fprintf( stderr, "\n[e] Cannot set filter \"%s\": %s\n\n", filter, pcap_geterr( handle ) );
		pcap_close( handle );
		exit( -3 );
	}
	pcap_freecode( &fp );

	/* verify datalink */
	if ( pcap_datalink( handle ) != DLT_EN10MB )
	{
		fprintf ( stderr , "\n[e] libntoh is independent from link layer, but this example only works with ethernet link layer\n");
		pcap_close ( handle );
		exit ( -4 );
	}

	fprintf( stderr, "\n[i] Source: %s / %s", source, pcap_datalink_val_to_description( pcap_datalink( handle ) ) );
	fprintf( stderr, "\n[i] Filter: %s", filter );

	fprintf( stderr, "\n[i] Receive data from client: ");
	if ( receive & RECV_CLIENT )
		fprintf( stderr , "Yes");
	else
		fprintf( stderr , "No");

	fprintf( stderr, "\n[i] Receive data from server: ");
	if ( receive & RECV_SERVER )
		fprintf( stderr , "Yes");
	else
		fprintf( stderr , "No");

	signal( SIGINT, &shandler );
	signal( SIGTERM, &shandler );

	/*******************************************/
	/** libntoh initialization process starts **/
	/*******************************************/

	ntoh_init ();

	if ( ! (tcp_session = ntoh_tcp_new_session ( 0 , 0 , &error ) ) )
	{
		fprintf ( stderr , "\n[e] Error %d creating TCP session: %s" , error , ntoh_get_errdesc ( error ) );
		exit ( -5 );
	}

	fprintf ( stderr , "\n[i] Max. TCP streams allowed: %d" , ntoh_tcp_get_size ( tcp_session ) );

	if ( ! (ipv4_session = ntoh_ipv4_new_session ( 0 , 0 , &error )) )
	{
		ntoh_tcp_free_session ( tcp_session );
		fprintf ( stderr , "\n[e] Error %d creating IPv4 session: %s" , error , ntoh_get_errdesc ( error ) );
		exit ( -6 );
	}

	fprintf ( stderr , "\n[i] Max. IPv4 flows allowed: %d\n\n" , ntoh_ipv4_get_size ( ipv4_session ) );

	/* capture starts */
	while ( ( packet = pcap_next( handle, &header ) ) != 0 )
	{
		/* get packet headers */
		ip = (struct ip*) ( packet + sizeof ( struct ether_header ) );
		if ( (ip->ip_hl * 4 ) < sizeof(struct ip) )
			continue;

		/* it is an IPv4 fragment */
		if ( NTOH_IPV4_IS_FRAGMENT(ip->ip_off) )
			send_ipv4_fragment ( ip , &ipv4_callback );
		/* or a TCP segment */
		else if ( ip->ip_p == IPPROTO_TCP )
			send_tcp_segment ( ip , &tcp_callback );
	}

	tcps = ntoh_tcp_count_streams( tcp_session );
	ipf = ntoh_ipv4_count_flows ( ipv4_session );

	/* no streams left */
	if ( ipf + tcps > 0 )
	{
		fprintf( stderr, "\n\n[+] There are currently %i stored TCP stream(s) and %i IPv4 flow(s). You can wait them to get closed or press CTRL+C\n" , tcps , ipf );
		pause();
	}

	shandler( 0 );

	//dummy return
	return 0;
}
Example #24
0
int main(int argc, char *argv[])
{
        pcap_if_t *alldevs, *dev;
        pcap_if_t dev2;
	char errbuf[PCAP_ERRBUF_SIZE];
        int i=0;
        int totaldev = 0;

	struct bpf_program fp;		/* The compiled filter expression */
	char filter_exp[] = "";	/* The filter expression */
	bpf_u_int32 mask;		/* The netmask of our sniffing device */
	bpf_u_int32 net;		/* The IP of our sniffing device */

        int pid;
        /*
        pid = fork();
        if (pid < 0)
        {
             printf("fork failed!\n");
             exit(1);
        }
        else if (pid == 0)
             execl("node", "server.js", (char *) 0);
        */
        pid = fork();
        if (pid < 0)
        {
             printf("fork failed!\n");
             exit(1);
        }
        else if (pid == 0)
        {
             execl("libpy/data_entry.py", (char *) 0);
             exit(1);
        }

        pid = fork();
        if (pid < 0)
        {
             printf("fork failed!\n");
             exit(1);
        }
        else if (pid == 0)
        {
             system("node server.js");
             exit(1);
        } 
        parse_ignorelist();

        if (pcap_findalldevs(&alldevs, errbuf) == -1)
        {
            fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
            exit(1);
        }
        /*
	dev = pcap_lookupdev(errbuf);
	if (dev == NULL) {
		fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
		return(2);
	}
	printf("Device: %s\n", dev);
        */
        for(dev=alldevs; dev; dev=dev->next)
        { 
            totaldev++;
            printf("%d. %s", ++i, dev->name);
            if (dev->description)
                printf(" (%s)\n", dev->description);
            else
                printf(" (No description available)\n");
        }
        printf("Total Devices %d\n", totaldev);
        int no;
        printf("Enter choice\t");
        scanf("%d",&no);
        if(no < 1 || no > totaldev)
        {
            printf("\nInterface number out of range.\n");
            /* Free the device list */
            pcap_freealldevs(alldevs);
            return -1;
        }
            /* Jump to the selected adapter */
        for(dev=alldevs, i=0; i<no-1 ;dev=dev->next, i++);

        printf("%s",dev->name);
        printf("%s",dev->addresses->addr); 
        pcap_t *handle;
        handle = pcap_open_live(dev->name, BUFSIZ, 1, 1000, errbuf);
        if (handle == NULL) {
            fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
            pcap_freealldevs(alldevs);
	    return(2);
	}
         // To get net and mask of the interface
        if (pcap_lookupnet(dev->name, &net, &mask, errbuf) == -1) {
	    fprintf(stderr, "Can't get netmask for device %s\n", dev->name);
	    net = 0;
	    mask = 0;
	}

	if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
	    fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
            pcap_freealldevs(alldevs);
	    return(2);
	}
	if (pcap_setfilter(handle, &fp) == -1) {
	    fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
            pcap_freealldevs(alldevs);
	    return(2);
	}
       
        findmac(dev->name, &hwaddr);

        /* we don't need any more the device list. Free it */
        pcap_freealldevs(alldevs);

        //pcap_loop(handle, 10, parse_packet, NULL);
        while (1==1)
            pcap_loop(handle, 1, parse_packet, NULL);


        /*
        ####To travese a packet using pcap_next
        
	struct pcap_pkthdr header;	// The header that pcap gives us 
	const u_char *packet;		// The actual packet 
	// Grab a packet 
	packet = pcap_next(handle, &header);
	// Print its length
	printf("Jacked a packet with length of [%d]\n", header.len);
	// And close the session 
	pcap_close(handle);
        */

	return(0);
}
Example #25
0
int
main(int argc, char** argv)
{
    const char* inFile = "-";  // default to stdin
    const char* hostIP = NULL; // default to no filter on IP
    const char* port   = NULL; // default to not filter on port

    bool doRX       = true;  // default to showing pkts RX by ip and port
    bool doParse    = false; // default to no parsing
    bool doExecute  = false; // default to no execute
    bool doClassify = false; // default to no classify
    bool verbose    = false; // default to not verbose
    bool doAllRtcp  = false; // default to only MUX/TIP

    LibTip::MediaType mType = LibTip::VIDEO; // default to video

    char* filterString = NULL; // default to no user filter string

    uint8_t  profile = 1; // default to CTS-1000 profile
    
    const char* usageString =
        "\n"
        "[--file file]\n"
        "[--ip IP]\n"
        "[--port port]\n"
        "[--xmit]\n"
        "[--parse]\n"
        "[--exec]\n"
        "[--classify]\n"
        "[--verbose]\n"
        "[--allrtcp]\n"
        "[--audio]\n"
        "[--filter pcap_filter_string]\n"
        "[--profile 1 (CTS1000) | 2 (T1-CTS1000) | 3 (CTS3000)]\n";

    char* progName = argv[0];
    while (true) {
        int c = -1;

        static struct option long_options[] = {
            { "file",    1, 0, 'a' },
            { "ip",      1, 0, 'b' },
            { "port",    1, 0, 'c' },
            { "parse",   0, 0, 'd' },
            { "exec",    0, 0, 'e' },
            { "verbose", 0, 0, 'f' },
            { "audio",   0, 0, 'g' },
            { "xmit",    0, 0, 'h' },
            { "filter",  1, 0, 'i' },
            { "profile", 1, 0, 'j' },
            { "classify",0, 0, 'k' },
            { "allrtcp", 0, 0, 'l' },
            { NULL,      0, 0, 0 }
        };

        c = getopt_long_only(argc, argv, "", long_options, NULL);
        if (c == -1) {
            break;
        }

        switch (c) {
        case 'a':
            inFile = optarg;
            break;

        case 'b':
            hostIP = optarg;
            break;

        case 'c':
            port = optarg;
            break;
            
        case 'd':
            doParse = true;
            break;

        case 'e':
            doExecute = true;
            break;

        case 'f':
            verbose = true;
            break;

        case 'g':
            mType = LibTip::AUDIO;
            break;

        case 'h':
            doRX = false;
            break;

        case 'i':
            filterString = optarg;
            break;

        case 'j':
            if (sscanf(optarg, "%hhu", &profile) != 1) {
                printf("ERROR:  invalid profile '%s'\n", optarg);
            }
            break;

        case 'k':
            doClassify = true;
            break;
            
        case 'l':
            doAllRtcp = true;
            break;

        case '?':
            printf("usage:  %s %s", progName, usageString);
            return 0;
        }
    }

    // must give us something to do
    if (!doParse && !doExecute && !doClassify) {
        printf("ERROR:  must specify either --parse or --execute or --classify\n");
        printf("usage:  %s %s", progName, usageString);
        return 1;
    }
    
    // create an tip instance for executing the packet trace
    PcapExecPacketTransmit xmit;
    LibTip::CTip tip(xmit);
    
    // configure with requested profile
    if (profile == 1) {
        LibTip::CSingleScreenProfile::Configure(tip.GetTipSystem(), false, false);
    } else if (profile == 2) {
        LibTip::CSingleScreenExtendedReachProfile::Configure(tip.GetTipSystem(), false);
    } else {
        LibTip::CTripleScreenProfile::Configure(tip.GetTipSystem(), false, false);
    }

    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* pcap = pcap_open_offline(inFile, errbuf);
    if (pcap == NULL) {
        printf("ERROR opening pcap file:  '%s'\n", errbuf);
        return 1;
    }

    char filter_exp[2048] = { '\0' };

    if (filterString == NULL) {
        // default filter, only look at UDP
        sprintf(filter_exp, "ip proto \\udp");
        if (hostIP != NULL) {
            if (doRX) {
                sprintf(filter_exp, "%s && dst host %s", filter_exp, hostIP);
            } else {
                sprintf(filter_exp, "%s && src host %s", filter_exp, hostIP);
            }
        }
        if (port != NULL) {
            if (doRX) {
                sprintf(filter_exp, "%s && dst port %s", filter_exp, port);
            } else {
                sprintf(filter_exp, "%s && src port %s", filter_exp, port);
            }            
        }
        
    } else {
        strncpy(filter_exp, filterString, sizeof(filter_exp));
    }

    struct bpf_program fp;
    if (pcap_compile(pcap, &fp, filter_exp, 0, 0) == -1) {
        printf("ERROR:  couldn't compile filter '%s': '%s'\n",
               filter_exp, pcap_geterr(pcap));
        return 1;
    }
    if (pcap_setfilter(pcap, &fp) == -1) {
        printf("ERROR:  Couldn't set filter '%s': '%s'\n",
               filter_exp, pcap_geterr(pcap));
        return 1;
    }

    if (doExecute) {
        tip.StartTipNegotiate(mType);
    }
    
    uint32_t pid = 0;
    
    while (1) {
        struct pcap_pkthdr header;
        uint8_t* packet = (uint8_t*) pcap_next(pcap, &header);
        if (packet == NULL) {
            break;
        }

        pid++;
        
        if (header.len > header.caplen) {
            printf("WARNING:  ignoring packet # %u b/c it is truncated\n", pid);
            continue;
        }
        
        if (doParse) {
            parse_packet(packet, header, verbose, doAllRtcp, mType);
        }

        if (doExecute) {
            exec_packet(packet, header, mType, tip);
        }

        if (doClassify) {
            classify_packet(packet, header);
        }
    }
    
    pcap_close(pcap);
    return 0;
}
Example #26
0
File: snif.c Project: cfultz/synner
void startSniffing(char *dev)
{

  char errbuf[PCAP_ERRBUF_SIZE]; 
  


/*get local IP address
gotta loop through all ifaces...boooo
*/

 struct ifaddrs *ifap, *ifa;
 struct sockaddr_in *sa;
 char *addr;

    getifaddrs (&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
             if(strcmp(ifa->ifa_name, dev)==0)
             {
             	sd->s_addr = sa->sin_addr.s_addr;
             	//myip = addr;
             	
             	 struct in_addr a;
 				 a.s_addr = sd->s_addr;
  					char *remote = inet_ntoa(a);
  
 						 sprintf(sd->s_addr_c,"%s",inet_ntoa(a));
             	
             }
            //printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
        }
    }

    freeifaddrs(ifap);




struct bpf_program fp;	

 bpf_u_int32 net;

   pcap_t *handle;

   //Set the TCPDUMP flags set SYN only for now
  // char filter_exp[] = "tcp[tcpflags] & (tcp-syn) != 0";
  char filter_exp[] = "";
 

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



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


if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
 fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
 
}

if (pcap_setfilter(handle, &fp) == -1) {
 fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
   exit(-1);
}
 
 
   printf("Started pcap on iface: %s\n", dev);
 
   pcap_loop(handle,0,do_packet,NULL);
 
   printf("Pcap thread ended. %s\n", dev);

}
Example #27
0
/*
 * process an input file or device
 * May be repeated.
 * If start is false, do not initiate new connections
 */
static void process_infile(const std::string &expression,const char *device,const std::string &infile)
{
    char error[PCAP_ERRBUF_SIZE];
    pcap_t *pd=0;
    int dlt=0;
    pcap_handler handler;

    if (infile!=""){
        std::string file_path = infile;
        // decompress input if necessary
#ifdef HAVE_INFLATER
        for(std::vector<inflater>::const_iterator it = inflaters.begin(); it != inflaters.end(); it++) {
            if(it->appropriate(infile)) {
                int fd = it->invoke(infile);
                file_path = ssprintf("/dev/fd/%d", fd);
                if(fd < 0) {
                    std::cerr << "decompression of '" << infile << "' failed" << std::endl;
                    exit(1);
                }
                if(access(file_path.c_str(), R_OK)) {
                    std::cerr << "decompression of '" << infile << "' is not available on this system" << std::endl;
                    exit(1);
                }
                break;
            }
        }
#endif
	if ((pd = pcap_open_offline(file_path.c_str(), error)) == NULL){	/* open the capture file */
	    die("%s", error);
	}
	dlt = pcap_datalink(pd);	/* get the handler for this kind of packets */
	handler = find_handler(dlt, infile.c_str());
    } else {
	/* if the user didn't specify a device, try to find a reasonable one */
	if (device == NULL){
	    if ((device = pcap_lookupdev(error)) == NULL){
		die("%s", error);
	    }
	}

	/* make sure we can open the device */
	if ((pd = pcap_open_live(device, SNAPLEN, !opt_no_promisc, 1000, error)) == NULL){
	    die("%s", error);
	}
#if defined(HAVE_SETUID) && defined(HAVE_GETUID)
	/* drop root privileges - we don't need them any more */
	if(setuid(getuid())){
	    perror("setuid");
	}
#endif
	/* get the handler for this kind of packets */
	dlt = pcap_datalink(pd);
	handler = find_handler(dlt, device);
    }

    /* If DLT_NULL is "broken", giving *any* expression to the pcap
     * library when we are using a device of type DLT_NULL causes no
     * packets to be delivered.  In this case, we use no expression, and
     * print a warning message if there is a user-specified expression
     */
#ifdef DLT_NULL_BROKEN
    if (dlt == DLT_NULL && expression != ""){
	DEBUG(1)("warning: DLT_NULL (loopback device) is broken on your system;");
	DEBUG(1)("         filtering does not work.  Recording *all* packets.");
    }
#endif /* DLT_NULL_BROKEN */

    DEBUG(20) ("filter expression: '%s'",expression.c_str());

    /* install the filter expression in libpcap */
    struct bpf_program	fcode;
    if (pcap_compile(pd, &fcode, expression.c_str(), 1, 0) < 0){
	die("%s", pcap_geterr(pd));
    }

    if (pcap_setfilter(pd, &fcode) < 0){
	die("%s", pcap_geterr(pd));
    }

    /* initialize our flow state structures */

    /* set up signal handlers for graceful exit (pcap uses onexit to put
     * interface back into non-promiscuous mode
     */
    portable_signal(SIGTERM, terminate);
    portable_signal(SIGINT, terminate);
#ifdef SIGHUP
    portable_signal(SIGHUP, terminate);
#endif

    /* start listening or reading from the input file */
    if (infile == "") DEBUG(1) ("listening on %s", device);
    if (pcap_loop(pd, -1, handler, (u_char *)tcpdemux::getInstance()) < 0){
	
	die("%s: %s", infile.c_str(),pcap_geterr(pd));
    }
}
Example #28
0
int
main (int argc, char *argv[])
{
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;
  pcap_t* pcap;
  int   offline=0;
  char* iface=NULL;
  char* fname=NULL;
  int   slen=SNAPLEN;
  int   rs=RINGSIZE;
  char  errbuf[PCAP_ERRBUF_SIZE];
  int   promisc=PROMISC;
  double  rate=1.0;

  client_name = strrchr(argv[0], '/');
  if(!client_name)
    client_name=argv[0];
  else
    client_name++;

  int opt;
  while ((opt = getopt(argc, argv, "c:n:s:pi:r:t:b:")) != -1) {
    switch (opt) {
    case 'c':
        client_name=optarg;
        break;
    case 'n':
        server_name=optarg;
        options |= JackServerName;
        break;
    case 's':
        slen=atoi(optarg);
        break;
    case 'p':
        promisc=0;
        break;
    case 'i':
        iface=optarg;
        break;
    case 'r':
        fname=optarg;
        break;
    case 't':
        rate=atof(optarg);
        break;
    case 'b':
        rs=atoi(optarg);
        break;
    case '?':
        usage(argv[0],0);
        break;
    default: /* '?' */
        printf("Invalid option %c\n",opt);
        usage(argv[0],EXIT_FAILURE);
    }
  }

  /* open the pcap source */
  if ((iface && fname) || (!iface && !fname)) {
    printf("Please specify either a interface or a dump file as packet source\n");
    usage(argv[0],EXIT_FAILURE);
  }

  if (iface) {
    pcap = pcap_open_live(iface, slen, promisc, 0, errbuf);
    if (!pcap) {
      printf("Failed to open pcap source %s: %s\n", iface, errbuf);
      exit(EXIT_FAILURE);
    }
  }

  if (fname) {
    pcap = pcap_open_offline(fname, errbuf);
    if (!pcap) {
      printf("Failed to open dump file %s: %s\n", iface, errbuf);
      exit(EXIT_FAILURE);
    }
    offline=1;
  }

  /* set bpf filter */
  if (optind < argc) {
    int   i,s;
    char* bpf_str;
    struct bpf_program bpf_prog;

    for (s=0, i=optind; i<argc; i++) {
      s += strlen(argv[i]) + 1;
    }

    bpf_str = malloc(s);
    if (!bpf_str) {
      printf("Failed to malloc space for bpf filter\n");
      exit(EXIT_FAILURE);
    }

    bpf_str[0]=0;
    for (i=optind; i<argc; i++) {
      strcat(bpf_str,argv[i]);
      strcat(bpf_str," ");
    }

    printf("Setting bpf filter to %s\n", bpf_str);

    if (0>pcap_compile(pcap, &bpf_prog, bpf_str, 1, 0)) {
      printf("Failed to compile bpf filter\n");
      exit(EXIT_FAILURE);
    }

    if (0>pcap_setfilter(pcap, &bpf_prog)) {
      printf("Failed to set bpf filter\n");
      exit(EXIT_FAILURE);
    }

    pcap_freecode(&bpf_prog);
    free(bpf_str);
  }

  /* allocate ringbuffer */
  rb=jack_ringbuffer_create (rs*sizeof(jack_default_audio_sample_t));
  if (!rb) {
    printf("Failed to allocate ringbuffer\n");
    exit(EXIT_FAILURE);
  }

	/* open a client connection to the JACK server */
	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate. 
	 */

	printf ("engine sample rate: %" PRIu32 "\n",
		jack_get_sample_rate (client));

	/* create two ports */

	output_port = jack_port_register (client, "output",
					  JACK_DEFAULT_AUDIO_TYPE,
					  JackPortIsOutput, 0);

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* read packets from pcap source and write it into the ringbuffer */
  char    *buf;
  struct  pcap_pkthdr *h;
  u_int   pcnt=0;
  struct  timeval toff, tnow;
  
  /* mark offset for calculation on first packet */
  toff.tv_sec = -1;

  /* main loop: get packets from pcap source */
	while (0 <= pcap_next_ex(pcap, &h, (const u_char**) &buf)) {
    size_t  s;
    
    if (!buf) break;
    pcnt++;

    /* 
     * if we are reading from a file we sleep in the loop until the timestamp
     * of the packet is reached.
     */
    if (offline) for(;;) {
      struct timeval dt;
      
      gettimeofday(&tnow, NULL);
      
      /* initialize toff on first packet */
      if(toff.tv_sec == -1) {
        tvmov(toff,h->ts);
        tvsub(toff,tnow);
        tvnrm(toff);
      }

      tvmov(dt,h->ts);
      tvsub(dt,tnow);
      tvsub(dt,toff);
      tvnrm(dt);

      if (dt.tv_sec < 0 ) {
        break;
      }
      else if (dt.tv_sec > 0) {
        sleep(dt.tv_sec);
      }
      else {
        usleep(dt.tv_usec);
      }
    }

    /* check available buffer space */
    s = jack_ringbuffer_write_space(rb);
    if (!s)
      continue;

    /* truncate packet if there is not enough space in the buffer */
    if (s > h->caplen)
      s = h->caplen;

    /* write into the ringbuffer and get the next packet */
    jack_ringbuffer_write(rb,buf,s);
	}

	jack_client_close (client);
  
  struct  pcap_stat  ps;
  if(!pcap_stats(pcap, &ps)) {
    printf(
      "%d packets captured\n"
      "%d received by filter\n"
      "%d packets dropped by kernel\n",
      ps.ps_recv, pcnt, ps.ps_drop
    );
  }
  else {
    pcap_perror(pcap,"Failed to optain packet statistics");
  }
	exit (0);
}
Example #29
0
int main(int argc, char *argv[])
{
	struct bpf_program fcode;
	pcap_handler printer;
	char ebuf[PCAP_ERRBUF_SIZE];
	int c,i,snaplen=512,size,packetcnt;
	bpf_u_int32 myself, localnet, netmask;
	unsigned char *pcap_userdata;

	filter_rule = argv[1];
	signal(SIGINT,sig_int);

	opterr =0;
	if(argc-1 <1)
	{
		usage();
		exit(1);
	}

	while( (c=getopt(argc,argv,"i:c:pher")) != -1) {
		switch(c) {
			case 'i' :
				device = optarg;
				break;
			case 'p' :
				pflag = 1;
				break;
			case 'c':
				cflag = 1;
				packetcnt = atoi(optarg);
				if(packetcnt <=0) {
					fprintf(stderr, "invalid pacet number %s",optarg);
					exit(1);
				}
				break;
			case 'e':
				eflag =1;
				break;
			case 'r':
				rflag =1;
				break;
			case 'h':
				usage();
				exit(1);
		}
	}

	if(device == NULL) {
		if( (device = pcap_lookupdev(ebuf) ) ==NULL)
		{
			perror(ebuf);
			exit(-1);
		}
	}
	fprintf(stdout,"device = %s\n", device);

	pd = pcap_open_live(device , snaplen, PROMISCOUS, 1000, ebuf);
	if(pd == NULL) {
		perror(ebuf);
		exit(-1);
	}

	i = pcap_snapshot(pd);
	if(snaplen <i) {
		perror(ebuf);
		exit(-1);
		}
	if(pcap_lookupnet(device, &localnet, &netmask, ebuf) <0) {
		perror(ebuf);
		exit(-1);
	}

	setuid(getuid());

	if(pcap_compile(pd, &fcode, filter_rule , 0, netmask)<0) {
		perror(ebuf);
		exit(-1);
	}

	if(pcap_setfilter(pd, &fcode) <0) {
		perror(ebuf);
		exit(-1);
	}

	fflush(stderr);

	printer = lookup_printer(pcap_datalink(pd));
	pcap_userdata = 0;
	if(pcap_loop(pd,packetcnt, printer, pcap_userdata) <0) {
		perror("pcap_loop error");
		exit(-1);
	}
	
	pcap_close(pd);
	exit(0);
}
Example #30
0
/*
 * Uses the current compiled filter on the interface
 * Parameters:
		none
 * Returns: 0 on success, -1 on error
*/
int Interface::setFilter() {
	int res = pcap_setfilter(handle, &fp);
	pcap_freecode(&fp);
	return res;
}