コード例 #1
0
ファイル: pcap_fopen.cpp プロジェクト: 52M/npcap
/** Prints packet timestaps regardless of format*/
int _tmain(int argc, _TCHAR* argv[])
{
    char errbuf[PCAP_ERRBUF_SIZE];
    wchar_t cmd[1024];
    wchar_t tshark_path[MAX_PATH];
    wchar_t file_path[MAX_PATH];

    if ( argc != 3 ) {
        wprintf(L"Prints packet timestaps regardless of format.\n");
        wprintf(L"Usage:\n\t%ls <tshark path> <trace file>\n", argv[0]);
        return 1;
    }

    // conversion to short path name in case there are spaces
    if ( ! GetShortPathNameW(argv[1], tshark_path, MAX_PATH) || 
         ! GetShortPathNameW(argv[2], file_path, MAX_PATH) )
    {
        printf("Failed to convert paths to short form.");
        return 1;
    }

    // create tshark command, which will make the trace conversion and print in libpcap format to stdout
    if ( swprintf_s(cmd, 1024, L"%ls -r %ls -w - -F libpcap", tshark_path, file_path) < 0 ) {
        wprintf(L"Failed to create command\n");
        return 1;
    }

    // start tshark
    FILE *tshark_out = _wpopen(cmd, L"rb");
    if ( tshark_out == NULL ) {
        strerror_s(errbuf, PCAP_ERRBUF_SIZE, errno);
        printf("Failed run tshark: %s\n", errbuf);
        wprintf(L"Command: %ls", cmd);
        return 1;
    }

    // open stdout from tshark
    pcap_t *pcap = pcap_fopen_offline(tshark_out, errbuf);
    if ( pcap == NULL ) {
        printf("Error opening stream from tshark: %s\n", errbuf);
        return 1;
    }

    // print information about every packet int trace
    struct pcap_pkthdr hdr;
    while ( pcap_next(pcap, &hdr) ) {
        printf("packet: ts: %u.%06u,  len: %4u,  caplen: %4u\n", hdr.ts.tv_sec, hdr.ts.tv_usec, hdr.len, hdr.caplen);
    }

    // clean up
    pcap_close(pcap);
    _pclose(tshark_out);
    return 0;
}
コード例 #2
0
static ifreader_t
interface_open(const char *target, int channel)
{
    interface_handle_t *handle;
    char errbuf[PCAP_ERRBUF_SIZE];

    handle = (interface_handle_t *) calloc(1, sizeof(interface_handle_t));
    if(!handle)
        return NULL;

    handle->capture_packets = false;

    handle->pf = fopen(target, "r");
    if(handle->pf == NULL) {
        fprintf(stderr, "Cannot open target %s: %s\n", target, strerror(errno));
        free(handle);
        return NULL;
    }
    handle->pc = pcap_fopen_offline(handle->pf, errbuf);
    if(handle->pc == NULL) {
        fprintf(stderr, "Cannot read target %s: %s\n", target, errbuf);
        fclose(handle->pf);
        free(handle);
        return NULL;
    }

    ifreader_t instance = interfacemgr_create_handle(target);
    instance->interface_data = handle;

    if(pcap_datalink(handle->pc) == DLT_EN10MB) {
        instance->ethernet = true;
    } else if(pcap_datalink(handle->pc) == DLT_IEEE802_15_4 ) {
        instance->ethernet = false;
        instance->fcs = true;
    } else if ( pcap_datalink(handle->pc) == DLT_IEEE802_15_4_NOFCS) {
        instance->ethernet = false;
        instance->fcs = false;
    } else {
        fprintf(stderr,
                "This program only supports 802.15.4 and Ethernet encapsulated 802.15.4 sniffers (DLT: %d)\n",
                pcap_datalink(handle->pc));
        free(handle);
        return NULL;
    }
    handle->first_offset = ftell(handle->pf);
    return instance;
}
コード例 #3
0
ファイル: savefile.c プロジェクト: ajinkya93/OpenBSD
pcap_t *
pcap_open_offline(const char *fname, char *errbuf)
{
	pcap_t *p;
	FILE *fp;

	if (fname[0] == '-' && fname[1] == '\0')
		fp = stdin;
	else {
		fp = fopen(fname, "r");
		if (fp == NULL) {
			snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", fname,
			    pcap_strerror(errno));
			return (NULL);
		}
	}
	p = pcap_fopen_offline(fp, errbuf);
	if (p == NULL) {
		if (fp != stdin)
			fclose(fp);
	}
	return (p);
}
コード例 #4
0
int main(int argc, char *argv[])
{
	const char *from_dev = NULL;			/* Capture from device */
	const char *from_file = NULL;			/* Read from pcap file */
	int from_stdin = 0;				/* Read from stdin */
	
	pcap_t *in;					/* PCAP input handle */
	
	int limit = -1;					/* How many packets to sniff */
	
	char errbuf[PCAP_ERRBUF_SIZE];			/* Error buffer */

	char *to_file = NULL;				/* PCAP output file */
	
	char *pcap_filter = NULL;			/* PCAP filter string */
	char *radius_filter = NULL;
	int port = 1812;
	
	struct bpf_program fp;				/* Holds compiled filter */
	bpf_u_int32 ip_mask = PCAP_NETMASK_UNKNOWN;	/* Device Subnet mask */
	bpf_u_int32 ip_addr = 0;			/* Device IP */
	
	char buffer[1024];

	int opt;
	FR_TOKEN parsecode;
	const char *radius_dir = RADIUS_DIR;
	
	fr_debug_flag = 2;
	log_dst = stdout;

	/*
	 *  Get options
	 */
	while ((opt = getopt(argc, argv, "c:d:Ff:hi:I:p:qr:s:Svw:xX")) != EOF) {
		switch (opt)
		{
		case 'c':
			limit = atoi(optarg);
			if (limit <= 0) {
				fprintf(stderr, "radsniff: Invalid number of packets \"%s\"\n", optarg);
				exit(1);
			}
			break;
		case 'd':
			radius_dir = optarg;
			break;
		case 'F':
			from_stdin = 1;
			to_stdout = 1;
			break;
		case 'f':
			pcap_filter = optarg;
			break;
		case 'h':
			usage(0);
			break;
		case 'i':
			from_dev = optarg;
			break;
		case 'I':
			from_file = optarg;
			break;
		case 'p':
			port = atoi(optarg);
			break;
		case 'q':
			if (fr_debug_flag > 0) {
				fr_debug_flag--;
			}
			break;
		case 'r':
			radius_filter = optarg;
			break;
		case 's':
			radius_secret = optarg;
			break;
		case 'S':
			do_sort = 1;
			break;
		case 'v':
			INFO(log_dst, "%s %s\n", radsniff_version, pcap_lib_version());
			exit(0);
			break;
		case 'w':
			to_file = optarg;
			break;
		case 'x':
		case 'X':
		  	fr_debug_flag++;
			break;
		default:
			usage(64);
		}
	}
	
	/* What's the point in specifying -F ?! */
	if (from_stdin && from_file && to_file) {
		usage(64);
	}
	
	/* Can't read from both... */
	if (from_file && from_dev) {
		usage(64);
	}
	
	/* Reading from file overrides stdin */
	if (from_stdin && (from_file || from_dev)) {
		from_stdin = 0;
	}
	
	/* Writing to file overrides stdout */
	if (to_file && to_stdout) {
		to_stdout = 0;
	}
	
	/*
	 *  If were writing pcap data stdout we *really* don't want to send
	 *  logging there as well.
	 */
 	log_dst = to_stdout ? stderr : stdout;

#if !defined(HAVE_PCAP_FOPEN_OFFLINE) || !defined(HAVE_PCAP_DUMP_FOPEN)
	if (from_stdin || to_stdout) {
		fprintf(stderr, "radsniff: PCAP streams not supported.\n");
		exit(64);
	}
#endif

	if (!pcap_filter) {
		pcap_filter = buffer;
		snprintf(buffer, sizeof(buffer), "udp port %d or %d or %d",
			 port, port + 1, 3799);
	}
	
	/*
	 *  There are times when we don't need the dictionaries.
	 */
	if (!to_stdout) {
		if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
			fr_perror("radsniff");
			exit(64);
		}
	}

	if (radius_filter) {
		parsecode = userparse(radius_filter, &filter_vps);
		if (parsecode == T_OP_INVALID) {
			fprintf(stderr, "radsniff: Invalid RADIUS filter \"%s\" (%s)\n", radius_filter, fr_strerror());
			exit(64);
		}
		
		if (!filter_vps) {
			fprintf(stderr, "radsniff: Empty RADIUS filter \"%s\"\n", radius_filter);
			exit(64);
		}

		filter_tree = rbtree_create((rbcmp) fr_packet_cmp, free, 0);
		if (!filter_tree) {
			fprintf(stderr, "radsniff: Failed creating filter tree\n");
			exit(1);
		}
	}

	/*
	 *  Setup the request tree
	 */
	request_tree = rbtree_create((rbcmp) fr_packet_cmp, free, 0);
	if (!request_tree) {
		fprintf(stderr, "radsniff: Failed creating request tree\n");
		exit(1);
	}

	/*
	 *  Allocate a null packet for decrypting attributes in CoA requests
	 */
	nullpacket = rad_alloc(NULL, 0);
	if (!nullpacket) {
		fprintf(stderr, "radsniff: Out of memory\n");
		exit(1);
	}

	/*
	 *  Get the default capture device
	 */
	if (!from_stdin && !from_file && !from_dev) {
		from_dev = pcap_lookupdev(errbuf);
		if (!from_dev) {
			fprintf(stderr, "radsniff: Failed discovering default interface (%s)\n", errbuf);
			exit(1);
		}

		INFO(log_dst, "Capturing from interface \"%s\"\n", from_dev);
	}
	
	/*
	 *  Print captures values which will be used
	 */
	if (fr_debug_flag > 2) {
				DEBUG1(log_dst, "Sniffing with options:\n");
		if (from_dev)	DEBUG1(log_dst, "  Device		   : [%s]\n", from_dev);
		if (limit > 0)	DEBUG1(log_dst, "  Capture limit (packets)  : [%d]\n", limit);
				DEBUG1(log_dst, "  PCAP filter	      : [%s]\n", pcap_filter);
				DEBUG1(log_dst, "  RADIUS secret	    : [%s]\n", radius_secret);
		if (filter_vps){DEBUG1(log_dst, "  RADIUS filter	    :\n");
			vp_printlist(log_dst, filter_vps);
		}
	}

	/*
	 *  Figure out whether were doing a reading from a file, doing a live
	 *  capture or reading from stdin.
	 */
	if (from_file) {
		in = pcap_open_offline(from_file, errbuf);
#ifdef HAVE_PCAP_FOPEN_OFFLINE
	} else if (from_stdin) {
		in = pcap_fopen_offline(stdin, errbuf);
#endif
	} else if (from_dev) {
		pcap_lookupnet(from_dev, &ip_addr, &ip_mask, errbuf);
		in = pcap_open_live(from_dev, 65536, 1, 1, errbuf);
	} else {
		fprintf(stderr, "radsniff: No capture devices available\n");
	}
	
	if (!in) {
		fprintf(stderr, "radsniff: Failed opening input (%s)\n", errbuf);
		exit(1);
	}

	if (to_file) {
		out = pcap_dump_open(in, to_file);
		if (!out) {
			fprintf(stderr, "radsniff: Failed opening output file (%s)\n", pcap_geterr(in));
			exit(1);
		}
#ifdef HAVE_PCAP_DUMP_FOPEN
	} else if (to_stdout) {
		out = pcap_dump_fopen(in, stdout);
		if (!out) {
			fprintf(stderr, "radsniff: Failed opening stdout (%s)\n", pcap_geterr(in));
			exit(1);
		}
#endif
	}

	/*
	 *  Apply the rules
	 */
	if (pcap_compile(in, &fp, pcap_filter, 0, ip_mask) < 0) {
		fprintf(stderr, "radsniff: Failed compiling PCAP filter (%s)\n", pcap_geterr(in));
		exit(1);
	}
	
	if (pcap_setfilter(in, &fp) < 0) {
		fprintf(stderr, "radsniff: Failed applying PCAP filter (%s)\n", pcap_geterr(in));
		exit(1);
	}

	/*
	 *  Enter the main capture loop...
	 */
	pcap_loop(in, limit, got_packet, NULL);
	
	/*
	 *  ...were done capturing.
	 */
	pcap_close(in);
	if (out) {
		pcap_dump_close(out);
	}
	
	if (filter_tree) {
		rbtree_free(filter_tree);
	}
	
	INFO(log_dst, "Done sniffing\n");
	
	return 0;
}
コード例 #5
0
ファイル: mydump.c プロジェクト: mjsalerno/mydump
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;
}
コード例 #6
0
ファイル: pcap.c プロジェクト: bgmilne/freeradius-server
/** Open a PCAP handle abstraction
 *
 * This opens interfaces for capture or injection, or files/streams for reading/writing.
 * @param pcap created with fr_pcap_init.
 * @return 0 on success, -1 on error.
 */
int fr_pcap_open(fr_pcap_t *pcap)
{
	switch (pcap->type) {
	case PCAP_INTERFACE_OUT:
	case PCAP_INTERFACE_IN:
	{
#if defined(HAVE_PCAP_CREATE) && defined(HAVE_PCAP_ACTIVATE)
		pcap->handle = pcap_create(pcap->name, pcap->errbuf);
		if (!pcap->handle) {
			fr_strerror_printf("%s", pcap->errbuf);
			return -1;
		}
		if (pcap_set_snaplen(pcap->handle, SNAPLEN) != 0) {
		create_error:
			fr_strerror_printf("%s", pcap_geterr(pcap->handle));
			pcap_close(pcap->handle);
			pcap->handle = NULL;
			return -1;
		}
		if (pcap_set_timeout(pcap->handle, PCAP_NONBLOCK_TIMEOUT) != 0) {
			goto create_error;
		}
		if (pcap_set_promisc(pcap->handle, pcap->promiscuous) != 0) {
			goto create_error;
		}

		if (pcap_set_buffer_size(pcap->handle, SNAPLEN *
					 (pcap->buffer_pkts ? pcap->buffer_pkts : PCAP_BUFFER_DEFAULT)) != 0) {
			goto create_error;
		}
		if (pcap_activate(pcap->handle) != 0) {
			goto create_error;
		}
#else
		/*
		 *	Alternative functions for libpcap < 1.0
		 */
		pcap->handle = pcap_open_live(pcap->name, SNAPLEN, pcap->promiscuous, PCAP_NONBLOCK_TIMEOUT,
					      pcap->errbuf);
		if (!pcap->handle) {
			fr_strerror_printf("%s", pcap->errbuf);
			return -1;
		}
#endif
		/*
		 *	Despite accepting an errbuff, pcap_setnonblock doesn't seem to write
		 *	error message there in newer versions.
		 */
		if (pcap_setnonblock(pcap->handle, true, pcap->errbuf) != 0) {
			fr_strerror_printf("%s", *pcap->errbuf != '\0' ?
					   pcap->errbuf : pcap_geterr(pcap->handle));
			pcap_close(pcap->handle);
			pcap->handle = NULL;
			return -1;
		}

		pcap->fd = pcap_get_selectable_fd(pcap->handle);
		pcap->link_layer = pcap_datalink(pcap->handle);
#ifndef __linux__
		{
			int value = 1;
			if (ioctl(pcap->fd, BIOCIMMEDIATE, &value) < 0) {
				fr_strerror_printf("Failed setting BIOCIMMEDIATE: %s", fr_syserror(errno));
			}
		}
#endif
	}
		break;

	case PCAP_FILE_IN:
		pcap->handle = pcap_open_offline(pcap->name, pcap->errbuf);
		if (!pcap->handle) {
			fr_strerror_printf("%s", pcap->errbuf);

			return -1;
		}
		pcap->fd = pcap_get_selectable_fd(pcap->handle);
		pcap->link_layer = pcap_datalink(pcap->handle);
		break;

	case PCAP_FILE_OUT:
		if (pcap->link_layer < 0) {
			pcap->link_layer = DLT_EN10MB;
		}
		pcap->handle = pcap_open_dead(pcap->link_layer, SNAPLEN);
		if (!pcap->handle) {
			fr_strerror_printf("Unknown error occurred opening dead PCAP handle");

			return -1;
		}
		pcap->dumper = pcap_dump_open(pcap->handle, pcap->name);
		if (!pcap->dumper) {
			fr_strerror_printf("%s", pcap_geterr(pcap->handle));

			return -1;
		}
		break;

#ifdef HAVE_PCAP_FOPEN_OFFLINE
	case PCAP_STDIO_IN:
		pcap->handle = pcap_fopen_offline(stdin, pcap->errbuf);
		if (!pcap->handle) {
			fr_strerror_printf("%s", pcap->errbuf);

			return -1;
		}
		pcap->fd = pcap_get_selectable_fd(pcap->handle);
		pcap->link_layer = pcap_datalink(pcap->handle);
		break;
#else
	case PCAP_STDIO_IN:
		fr_strerror_printf("This version of libpcap does not support reading pcap data from streams");

		return -1;
#endif
#ifdef HAVE_PCAP_DUMP_FOPEN
	case PCAP_STDIO_OUT:
		pcap->handle = pcap_open_dead(DLT_EN10MB, SNAPLEN);
		pcap->dumper = pcap_dump_fopen(pcap->handle, stdout);
		if (!pcap->dumper) {
			fr_strerror_printf("%s", pcap_geterr(pcap->handle));

			return -1;
		}
		break;
#else
	case PCAP_STDIO_OUT:
		fr_strerror_printf("This version of libpcap does not support writing pcap data to streams");

		return -1;
#endif
	case PCAP_INVALID:
	default:
		fr_assert(0);
		fr_strerror_printf("Bad handle type (%i)", pcap->type);
		return -1;
	}

	return 0;
}
コード例 #7
0
ファイル: capture.c プロジェクト: git-hulk/tcprstat
int
offline_capture(FILE *fcapture) {
    struct bpf_program bpf;
    char errbuf[PCAP_ERRBUF_SIZE];
    char filter[300];
    char ports_str[256];
    char **ports;
    int r, n_ports;

    pcap = pcap_fopen_offline(fcapture, errbuf);
    if (!pcap) {
        LOGGER(ERROR, "pcap: %s\n", errbuf);
        return 1;
        
    }
    
    if(port) {
        int i, n = 0 ;
        ports = split_string(port, strlen(port), ",", 1, &n_ports);
        if(n_ports > 10) {
            LOGGER(ERROR, "it's unscientific to listen so many ports.\n", errbuf);
            return 1;
        }
       
        n = snprintf(ports_str, 256, "tcp port %s", ports[0]);
        
        for(i = 1; i < n_ports; i++) {
            n += snprintf(ports_str + n, 256, " or tcp port %s", ports[i]);
        }
        split_string_free(ports, n_ports);
    }

    // Capture only TCP
    if (global_options.server && n_ports) {
        sprintf(filter, "host %s and (%s)", global_options.server, ports_str);
    } else if (global_options.server && !n_ports) {
        sprintf(filter, "host %s", global_options.server);
    } else if (!global_options.server && n_ports) {
        sprintf(filter, "(%s)", ports_str);
    } else {
        sprintf(filter, "tcp");
    }

    if (pcap_compile(pcap, &bpf, filter, 1, 0)) {
        LOGGER(ERROR, "pcap: %s\n", pcap_geterr(pcap));
        return 1;
        
    }
    
    if (pcap_setfilter(pcap, &bpf)) {
        LOGGER(ERROR, "pcap: %s\n", pcap_geterr(pcap));
        return 1;
        
    }
    
    // The -1 here stands for "infinity"
    r = pcap_loop(pcap, -1, process_packet, (unsigned char *) pcap);
    if (r == -1) {
        LOGGER(ERROR, "pcap: %s\n", pcap_geterr(pcap));
        return 1;
        
    }
    
    return 1;
    
}
コード例 #8
0
PcapInterface::PcapInterface(const char *name) : NetworkInterface(name) {
  char pcap_error_buffer[PCAP_ERRBUF_SIZE];
  struct stat buf;

  pcap_handle = NULL, pcap_list = NULL;
  
  if((stat(name, &buf) == 0) || (name[0] == '-')) {
    /*
      The file exists so we need to check if it's a 
      text file or a pcap file
    */

    if(strcmp(name, "-") == 0) {
      /* stdin */
      pcap_handle = pcap_fopen_offline(stdin, pcap_error_buffer);
      pcap_datalink_type = DLT_EN10MB;
    } else if((pcap_handle = pcap_open_offline(ifname, pcap_error_buffer)) == NULL) {
      if((pcap_list = fopen(name, "r")) == NULL) {
	ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to open file %s", name);
	exit(0);
      }	else
	read_pkts_from_pcap_dump = true;
    } else {
      char *slash = strrchr(ifname, '/');

      if(slash) {
	char *old = ifname;
	ifname = strdup(&slash[1]);
	free(old);
      }
      
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "Reading packets from pcap file %s...", ifname);
      read_pkts_from_pcap_dump = true, purge_idle_flows_hosts = false;      
      pcap_datalink_type = pcap_datalink(pcap_handle);
    }
  } else {
    pcap_handle = pcap_open_live(ifname, ntop->getGlobals()->getSnaplen(),
				 ntop->getPrefs()->use_promiscuous(),
				 500, pcap_error_buffer);  

    if(pcap_handle) {
      char *bl = strrchr(ifname, 
#ifdef WIN32
			 '\\'
#else
			 '/'
#endif
			 );
      
      if(bl != NULL) {
	char *tmp = ifname;
	ifname = strdup(&bl[1]);
	free(tmp);
      }
      
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "Reading packets from interface %s...", ifname);
      read_pkts_from_pcap_dump = false;
      pcap_datalink_type = pcap_datalink(pcap_handle);
    }
  }
  
  if(ntop->getPrefs()->are_ixia_timestamps_enabled())
    ntop->getTrace()->traceEvent(TRACE_WARNING, "Hardware timestamps are supported only on PF_RING capture interfaces");
}
コード例 #9
0
ファイル: nfpcapd.c プロジェクト: jmagudo/nfdump
static pcap_dev_t *setup_pcap_Ffile(FILE *fp, char *filter, int snaplen) {
pcap_t 		*handle;
pcap_dev_t	*pcap_dev;
char errbuf[PCAP_ERRBUF_SIZE];
uint32_t	linkoffset, linktype;

	dbg_printf("Enter function: %s\n", __FUNCTION__);
	
	if ( !fp ) 
		return NULL;

	handle = pcap_fopen_offline(fp, errbuf);
	if (handle == NULL) {
		LogError("Couldn't attach FILE handle %s", errbuf);
		return NULL;
	}

	if ( filter ) {
		struct bpf_program filter_code;
		bpf_u_int32 netmask = 0;
		// Compile and apply the filter
		if (pcap_compile(handle, &filter_code, filter, 0, netmask) == -1) {
			LogError("Couldn't parse filter %s: %s", filter, pcap_geterr(handle));
			return NULL;
		}
		if (pcap_setfilter(handle, &filter_code) == -1) {
			LogError("Couldn't install filter %s: %s", filter, pcap_geterr(handle));
			return NULL;
		}
	}

	linkoffset = 0;
	linktype   = pcap_datalink(handle);
	switch ( linktype ) {
		case DLT_RAW: 
			linkoffset = 0; 
			break;
		case DLT_PPP: 
			linkoffset = 2;
			break;
		case DLT_NULL: 
			linkoffset = 4;
			break;
		case DLT_LOOP: 
			linkoffset = 14; 
			break;
		case DLT_EN10MB: 
			linkoffset = 14; 
			break;
		case DLT_LINUX_SLL: 
			linkoffset = 16; 
			break;
		case DLT_IEEE802_11: 
			linkoffset = 22; 
			break;
		default:
			LogError("Unsupported data link type %i", linktype);
			return NULL;
	}

	pcap_dev = (pcap_dev_t *)calloc(1, sizeof(pcap_dev_t));
	if ( !pcap_dev ) {
		LogError("malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror(errno) );
		return NULL;
	}	

	pcap_dev->handle	 = handle;
	pcap_dev->snaplen	 = snaplen;
	pcap_dev->linkoffset = linkoffset;
	pcap_dev->linktype	 = linktype;

	return pcap_dev;

} // End of setup_pcap_file
コード例 #10
0
ファイル: pcap.c プロジェクト: Distrotech/freeradius-server
/** Open a PCAP handle abstraction
 *
 * This opens interfaces for capture or injection, or files/streams for reading/writing.
 * @param pcap created with fr_pcap_init.
 * @return 0 on success, -1 on error.
 */
int fr_pcap_open(fr_pcap_t *pcap)
{
	switch (pcap->type) {
		case PCAP_INTERFACE_OUT:
		case PCAP_INTERFACE_IN:
			pcap->handle = pcap_open_live(pcap->name, SNAPLEN, true, PCAP_NONBLOCK_TIMEOUT,
						      pcap->errbuf);
			if (!pcap->handle) {
				fr_strerror_printf("%s", pcap->errbuf);

				return -1;
			}

			pcap->fd = pcap_get_selectable_fd(pcap->handle);

#ifndef __linux__
			{
				int value = 1;
				if (ioctl(pcap->fd, BIOCIMMEDIATE, &value) < 0) {
					fr_strerror_printf("Failed setting BIOCIMMEDIATE: %s", fr_syserror(errno));
				}
			}
#endif

			break;
		case PCAP_FILE_IN:
			pcap->handle = pcap_open_offline(pcap->name, pcap->errbuf);
			if (!pcap->handle) {
				fr_strerror_printf("%s", pcap->errbuf);

				return -1;
			}
			break;
		case PCAP_FILE_OUT:
			pcap->handle = pcap_open_dead(DLT_EN10MB, SNAPLEN);
			pcap->dumper = pcap_dump_open(pcap->handle, pcap->name);
			if (!pcap->dumper) {
				fr_strerror_printf("%s", pcap->errbuf);

				return -1;
			}
			break;
#ifdef HAVE_PCAP_FOPEN_OFFLINE
		case PCAP_STDIO_IN:
			pcap->handle = pcap_fopen_offline(stdin, pcap->errbuf);
			if (!pcap->handle) {
				fr_strerror_printf("%s", pcap->errbuf);

				return -1;
			}
			break;
#else
		case PCAP_STDIO_IN:
			fr_strerror_printf("This version of libpcap does not support reading pcap data from streams");

			return -1;
#endif
#ifdef HAVE_PCAP_DUMP_FOPEN
		case PCAP_STDIO_OUT:
			pcap->handle = pcap_open_dead(DLT_EN10MB, SNAPLEN);
			pcap->dumper = pcap_dump_fopen(pcap->handle, stdout);
			if (!pcap->dumper) {
				fr_strerror_printf("%s", pcap_geterr(pcap->handle));

				return -1;
			}
			break;
#else
		case PCAP_STDIO_OUT:
			fr_strerror_printf("This version of libpcap does not support writing pcap data to streams");

			return -1;
#endif
		case PCAP_INVALID:
		default:
			fr_assert(0);
			return -1;
	}

	return 0;
}
コード例 #11
0
int main(int argc,char *argv[])
{
	char *dev,errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *handle;				/* Session handle */
	struct bpf_program fp;			/* compiled filter expression */
	char filter_exp[]="ether proto \\ip";	//"ip proto \\udp or \\tcp or \\icmp";	/* Filter expression */
	bpf_u_int32 mask;			/* netmask of sniffing device */
	bpf_u_int32 net;			/* IP address of const struct pcap_pkthdrsniffing device */
        struct sigaction *act_alarm,*act_int;
	
	struct pcap_pkthdr header;
	const u_char *packet=NULL;


	act_alarm=(struct sigaction*)malloc(sizeof(struct sigaction));
	act_int=(struct sigaction*)malloc(sizeof(struct sigaction));	
	memset(act_alarm,'\0',sizeof(act_alarm));
	memset(act_int,'\0',sizeof(act_int));
	
	act_alarm->sa_handler=alarm_printhandler;	
	sigemptyset(&act_alarm->sa_mask);
	act_alarm->sa_flags=0;	
	sigaction(SIGALRM,act_alarm,NULL);
	
	act_int->sa_handler=INT_handler;
	sigemptyset(&act_int->sa_mask);
	act_int->sa_flags=0;
	sigaction(SIGINT,act_int,NULL);	
	
	
	if(gettimeofday(&current_time,NULL) != 0)
	{
		fprintf(stderr,"Error in gettimeofday(): %s\n",strerror(errno));
		exit(1);
	} 
	
	/* Handle commandline here */
	
	memset(interface,'\0',sizeof(interface));
	memset(filename,'\0',sizeof(filename));
	memset(my_ip,'\0',sizeof(my_ip));

	handle_commandline(argc,argv);
	
	newvalue=(struct itimerval*)malloc(sizeof(struct itimerval));
	newvalue->it_interval.tv_sec=epoch;
	newvalue->it_interval.tv_usec=0;
	newvalue->it_value.tv_sec=epoch;
	newvalue->it_value.tv_usec=0;
	setitimer(ITIMER_REAL,newvalue,NULL);  

	/* fetch ip address */
	getifaddrs(&addr);
	while(addr)
	{
		if(addr->ifa_addr && addr->ifa_addr->sa_family == AF_INET && strcmp(addr->ifa_name,interface)==0)
		{
			struct sockaddr_in *paddr = (struct sockaddr_in *)addr->ifa_addr;
			//fprintf(stdout,"%s %s\n",addr->ifa_name,inet_ntoa(paddr->sin_addr));  //project
			strcpy(filename,inet_ntoa(paddr->sin_addr));
			strcpy(my_ip,inet_ntoa(paddr->sin_addr));
			break;
		}
		addr = addr->ifa_next;
	}
	//printf("Filename: %s",filename);
	if(epoch == 0)
	{
		epoch=1;	// default is 1 sec
	}
	if(interface[0] == '\0')
	{
		dev=" ";
	}
	else
	{
		dev=interface;
	}
	
	//fprintf(stdout,"Device is %s\n",dev);
	
	/* Lookup network */
	if(pcap_lookupnet(dev,&net,&mask,errbuf) == -1)
	{
		 //fprintf(stderr, "Can't get netmask for device %s\n", dev);
		 net = 0;
		 mask = 0;
	} 
	//printf("IP: %d\n",net);
	//printf("Mask: %d\n",mask);	

	 /* Opening device for sniffing */
	if(read_file == NULL)
	{
								
		if((handle=pcap_create(dev,errbuf)) == NULL)
		{
			fprintf(stderr,"Error in pcap_create: %s",errbuf);
			exit(1);
		}
		if(pcap_set_promisc(handle,5) == PCAP_ERROR_ACTIVATED || pcap_set_timeout(handle,epoch*1000) == PCAP_ERROR_ACTIVATED )
		{
			fprintf(stderr,"Capture handle already activated");
			exit(1);
		}
		
		pcap_activate(handle);  
		
	}
	else
	{
		filer=fopen(read_file,"r");
		/* block the alarm handler too */
		sigaddset(&act_alarm->sa_mask,SIGALRM);
		sigprocmask(SIG_BLOCK,&act_alarm->sa_mask,NULL);		
		if(filer == NULL)
		{
			perror("Error in fopen file");
			exit(1);
		}
				
		handle=pcap_fopen_offline(filer,errbuf);
		if(handle == NULL)
		{
			fprintf(stderr,"Error in pcap_open_offline(): %s",errbuf);
			exit(1);
		}
		
	}
	if(write_file != NULL)
	{
		filew=fopen(write_file,"w");			
	}
		
	if(handle == NULL)
	{
		fprintf(stderr,"Couldn't open device %s: %s\n",dev,errbuf);
		exit(1);
	}
	
	
	/* Determine the type of link-headers the device provides */
	if(pcap_datalink(handle) != DLT_EN10MB)
	{
		fprintf(stderr,"Usage: ./traffana -v [-r filename] [-i interface] [-T epoch] [-w filename]\n");
		exit(1);
	}

	/* Complie 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);
	}

	/* Set filter */
	if (pcap_setfilter(handle, &fp) == -1) 
	{
		 fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
		 exit(1);
	}
	/* set the diection */
	//pcap_setdirection(handle,PCAP_D_IN);

	
	

	/* Grab the packets */
	if(read_file == NULL)
	{
		err_loop=pcap_loop(handle,-1,got_packet,(u_char *)filew);	// count -1 or 0 for infinity packets AND pass argument the name
									// of th file
		if(err_loop == -1)
		{
			pcap_perror(handle,errbuf);
			fprintf(stderr,"Error in pcap_loop(): %s\n",errbuf);
			exit(1);
		}
	}
	
	if(read_file !=NULL)
	{
		
		while((packet = pcap_next(handle,&header))!=NULL)
		{
			got_packet(0,&header,packet);
		}
	}

	/* Close session */
	
	if(read_file != NULL)
	{
		print_readfile_stats(sec1,usec1);	/* to read the last epoch */	
	}
	pcap_freecode(&fp);
	pcap_close(handle);
	return 0;

}
コード例 #12
0
ファイル: pcap_fopen.cpp プロジェクト: nmap/npcap
/** Prints packet timestaps regardless of format*/
int _tmain(int argc, _TCHAR* argv[])
{
    char errbuf[PCAP_ERRBUF_SIZE];
    _TCHAR cmd[1024];
    _TCHAR tshark_path[MAX_PATH];
    _TCHAR file_path[MAX_PATH];

    /* Load Npcap and its functions. */
    if (!LoadNpcapDlls())
    {
        fprintf(stderr, "Couldn't load Npcap\n");
        exit(1);
    }

    if ( argc != 3 ) {
        _tprintf(_T("Prints packet timestaps regardless of format.\n"));
        _tprintf(_T("Usage:\n\t%s <tshark path> <trace file>\n"), argv[0]);
        return 1;
    }

    // conversion to short path name in case there are spaces
    if ( ! GetShortPathName(argv[1], tshark_path, MAX_PATH) || 
         ! GetShortPathName(argv[2], file_path, MAX_PATH) )
    {
        _tprintf(_T("Failed to convert paths to short form."));
        return 1;
    }

    // create tshark command, which will make the trace conversion and print in libpcap format to stdout
    if ( _stprintf_s(cmd, 1024, _T("%s -r %s -w - -F libpcap"), tshark_path, file_path) < 0 ) {
        _tprintf(_T("Failed to create command\n"));
        return 1;
    }

    // start tshark
    FILE *tshark_out = _tpopen(cmd, _T("rb"));
    if ( tshark_out == NULL ) {
        strerror_s(errbuf, PCAP_ERRBUF_SIZE, errno);
        printf("Failed run tshark: %s\n", errbuf);
        _tprintf(_T("Command: %s"), cmd);
        return 1;
    }

    // open stdout from tshark
    pcap_t *pcap = pcap_fopen_offline(tshark_out, errbuf);
    if ( pcap == NULL ) {
        printf("Error opening stream from tshark: %s\n", errbuf);
        return 1;
    }

    // print information about every packet int trace
    struct pcap_pkthdr hdr;
    while ( pcap_next(pcap, &hdr) ) {
        printf("packet: ts: %u.%06u,  len: %4u,  caplen: %4u\n", hdr.ts.tv_sec, hdr.ts.tv_usec, hdr.len, hdr.caplen);
    }

    // clean up
    pcap_close(pcap);
    _pclose(tshark_out);
    return 0;
}