int main(int argc, char **argv) { char *cp, *device; int op; int dorfmon, useactivate; char ebuf[PCAP_ERRBUF_SIZE]; char *infile; const char *cmdbuf; pcap_if_t *devlist; pcap_t *pd; int status = 0; int pcap_fd; #if defined(USE_BPF) struct bpf_program bad_fcode; struct bpf_insn uninitialized[INSN_COUNT]; #elif defined(USE_SOCKET_FILTERS) struct sock_fprog bad_fcode; struct sock_filter uninitialized[INSN_COUNT]; #endif struct bpf_program fcode; device = NULL; dorfmon = 0; useactivate = 0; infile = NULL; if ((cp = strrchr(argv[0], '/')) != NULL) program_name = cp + 1; else program_name = argv[0]; opterr = 0; while ((op = getopt(argc, argv, "aF:i:I")) != -1) { switch (op) { case 'a': useactivate = 1; break; case 'F': infile = optarg; break; case 'i': device = optarg; break; case 'I': dorfmon = 1; useactivate = 1; /* required for rfmon */ break; default: usage(); /* NOTREACHED */ } } if (device == NULL) { /* * No interface specified; get whatever pcap_lookupdev() * finds. */ if (pcap_findalldevs(&devlist, ebuf) == -1) error("%s", ebuf); if (devlist == NULL) error("no interfaces available for capture"); device = strdup(devlist->name); pcap_freealldevs(devlist); } if (infile != NULL) { /* * Filter specified with "-F" and a file containing * a filter. */ cmdbuf = read_infile(infile); } else { if (optind < argc) { /* * Filter specified with arguments on the * command line. */ cmdbuf = copy_argv(&argv[optind+1]); } else { /* * No filter specified; use an empty string, which * compiles to an "accept all" filter. */ cmdbuf = ""; } } if (useactivate) { pd = pcap_create(device, ebuf); if (pd == NULL) error("%s: pcap_create() failed: %s", device, ebuf); status = pcap_set_snaplen(pd, 65535); if (status != 0) error("%s: pcap_set_snaplen failed: %s", device, pcap_statustostr(status)); status = pcap_set_promisc(pd, 1); if (status != 0) error("%s: pcap_set_promisc failed: %s", device, pcap_statustostr(status)); if (dorfmon) { status = pcap_set_rfmon(pd, 1); if (status != 0) error("%s: pcap_set_rfmon failed: %s", device, pcap_statustostr(status)); } status = pcap_set_timeout(pd, 1000); if (status != 0) error("%s: pcap_set_timeout failed: %s", device, pcap_statustostr(status)); status = pcap_activate(pd); if (status < 0) { /* * pcap_activate() failed. */ error("%s: %s\n(%s)", device, pcap_statustostr(status), pcap_geterr(pd)); } else if (status > 0) { /* * pcap_activate() succeeded, but it's warning us * of a problem it had. */ warning("%s: %s\n(%s)", device, pcap_statustostr(status), pcap_geterr(pd)); } } else { *ebuf = '\0'; pd = pcap_open_live(device, 65535, 1, 1000, ebuf); if (pd == NULL) error("%s", ebuf); else if (*ebuf) warning("%s", ebuf); } pcap_fd = pcap_fileno(pd); /* * Try setting a filter with an uninitialized bpf_program * structure. This should cause valgrind to report a * problem. * * We don't check for errors, because it could get an * error due to a bad pointer or count. */ #if defined(USE_BPF) ioctl(pcap_fd, BIOCSETF, &bad_fcode); #elif defined(USE_SOCKET_FILTERS) setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode, sizeof(bad_fcode)); #endif /* * Try setting a filter with an initialized bpf_program * structure that points to an uninitialized program. * That should also cause valgrind to report a problem. * * We don't check for errors, because it could get an * error due to a bad pointer or count. */ #if defined(USE_BPF) bad_fcode.bf_len = INSN_COUNT; bad_fcode.bf_insns = uninitialized; ioctl(pcap_fd, BIOCSETF, &bad_fcode); #elif defined(USE_SOCKET_FILTERS) bad_fcode.len = INSN_COUNT; bad_fcode.filter = uninitialized; setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode, sizeof(bad_fcode)); #endif /* * Now compile a filter and set the filter with that. * That should *not* cause valgrind to report a * problem. */ if (pcap_compile(pd, &fcode, cmdbuf, 1, 0) < 0) error("can't compile filter: %s", pcap_geterr(pd)); if (pcap_setfilter(pd, &fcode) < 0) error("can't set filter: %s", pcap_geterr(pd)); pcap_close(pd); exit(status < 0 ? 1 : 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; char *short_options = "i:c:n:o:b:5sfuCDh"; 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' }, { 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; 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) { /* 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 { 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. */ monitor(bssid, passive, source, channel, mode); 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; }
/** * capturePackets(void * arg) -> void * * * Captures the incoming packets and analyses the packets **/ void * capturePackets(void * arg) { pcap_t *pcapHandle; char errorPcap[PCAP_ERRBUF_SIZE]; struct pcap_pkthdr *packHdr; struct bpf_program filter; char filter_exp[100] = "dst host "; const u_char *packetData; int readStatus, portNum; bpf_u_int32 localIp; //Convert local ip to 32 bit format inet_pton(AF_INET, ps_args.localIP.c_str(), &localIp); //Append the local machine ip to filter expression strcat(filter_exp, ps_args.localIP.c_str()); //Open the specified interface for live capturing pcapHandle = pcap_open_live("eth0", BUFSIZ, 0, 1000, errorPcap); if(pcapHandle == NULL ){ fprintf(stderr,"Error in opening pcap for live capture: %s \n",errorPcap ); exit(EXIT_FAILURE); } //Add a filter to capture incoming packets only if (pcap_compile(pcapHandle, &filter, filter_exp, 0, localIp) == -1) { printf("Filter Parse Error %s: %s\n", filter_exp, pcap_geterr(pcapHandle)); exit(EXIT_FAILURE); } if (pcap_setfilter(pcapHandle, &filter) == -1) { printf("Could not add filter %s: %s\n", filter_exp, pcap_geterr(pcapHandle)); exit(EXIT_FAILURE); } //Start sniffing the packets while(1) { //Check for pcap exit condition pthread_mutex_lock(&pcapLock); if(exitPcap == true) { pthread_mutex_unlock(&pcapLock); break; } pthread_mutex_unlock(&pcapLock); //Capture the packet from Ethernet interface readStatus = pcap_next_ex(pcapHandle, &packHdr, &packetData); if(readStatus == -1) { printf("Error reading packets: %s\n", pcap_geterr(pcapHandle)); } if(readStatus > 0) { struct iphdr *iph = (struct iphdr *)(packetData + ETH_HLEN); //Get the destination port from the TCP Header if(iph->protocol == IPPROTO_TCP) { struct tcphdr *tcpH = (struct tcphdr *)(packetData + ETH_HLEN + iph->ihl* 4); portNum = ntohs(tcpH->dest); } //Get the destination port from the UDP Header else if (iph->protocol == IPPROTO_UDP) { struct udphdr *udpH = (struct udphdr *)(packetData + ETH_HLEN + iph->ihl* 4); portNum = ntohs(udpH->dest); } //Get the destination port from the ICMP Header else if (iph->protocol == IPPROTO_UDP) { struct icmphdr *icmpH = (struct icmphdr *) (packetData + ETH_HLEN + iph->ihl* 4); portNum = getICMPPortNumber((u_char *)(packetData + ETH_HLEN + iph->ihl* 4 + sizeof(icmphdr))); } } //Adds the packet to the global map addToPacketList(portNum, (u_char *)packetData + ETH_HLEN); } //Close the pcap handle pcap_close(pcapHandle); pthread_exit(NULL); }
int main(int argc, char *argv[]) { pcap_t *handle;/* Session handle */ const char *opt_chdir;/* directory to write dump */ char *ifname;/* interface to sniff on */ char *fname;/* pcap file to read on */ char errbuf[PCAP_ERRBUF_SIZE];/* Error string */ struct bpf_program fp;/* The compiled filter */ char filter_exp[] = "udp";/* The filter expression */ bpf_u_int32 mask;/* Our netmask */ bpf_u_int32 net;/* Our IP */ struct pcap_pkthdr *pkt_header; /* The header that pcap gives us */ const u_char *pkt_data; /* The actual packet */ unsigned long last_cleanup=0; int res; int offset_to_ip=0; int opt_fork=1; int opt_promisc=1; int opt_packetbuffered=0; int opt_t38only=0; int opt_rtpsave=RTPSAVE_RTP_RTCP; int verbosity=0; bool number_filter_matched=false; #ifdef USE_REGEXP regex_t number_filter; number_filter.allocated=0; #else char number_filter[128]; number_filter[0]=0; #endif ifname=NULL; fname=NULL; opt_chdir="/var/spool/pcapsipdump"; while(1) { char c; c = getopt (argc, argv, "i:r:d:v:n:R:fpUt"); if (c == -1) break; switch (c) { case 'i': ifname=optarg; break; case 'v': verbosity=atoi(optarg); break; case 'n': #ifdef USE_REGEXP regcomp(&number_filter,optarg,0); #else strcpy(number_filter,optarg); #endif break; case 'R': if (strcasecmp(optarg,"none")==0){ opt_rtpsave=RTPSAVE_NONE; }else if (strcasecmp(optarg,"rtpevent")==0){ opt_rtpsave=RTPSAVE_RTPEVENT; }else if (strcasecmp(optarg,"t38")==0){ opt_t38only=1; }else if (strcasecmp(optarg,"all")==0 || strcasecmp(optarg,"rtp+rtcp")==0){ opt_rtpsave=RTPSAVE_RTP_RTCP; }else if (strcasecmp(optarg,"rtp")==0){ opt_rtpsave=RTPSAVE_RTP; }else{ printf("Unrecognized RTP filter specification: '%s'\n",optarg); return 1; } break; case 't': opt_t38only=1; break; case 'r': fname=optarg; break; case 'd': opt_chdir=optarg; break; case 'f': opt_fork=0; break; case 'p': opt_promisc=0; break; case 'U': opt_packetbuffered=1; break; } } // allow interface to be specified without '-i' option - for sake of compatibility if (optind < argc) { ifname = argv[optind]; } if ((fname==NULL)&&(ifname==NULL)){ printf( "pcapsipdump version %s\n" "Usage: pcapsipdump [-fpU] [-i <interface>] [-r <file>] [-d <working directory>] [-v level] [-R filter]\n" " -f Do not fork or detach from controlling terminal.\n" " -p Do not put the interface into promiscuous mode.\n" " -R RTP filter. Possible values: 'rtp+rtcp' (default), 'rtp', 'rtpevent', 't38', or 'none'.\n" " -U Make .pcap files writing 'packet-buffered' - slower method,\n" " but you can use partitially written file anytime, it will be consistent.\n" " -v Set verbosity level (higher is more verbose).\n" " -n Number-filter. Only calls to/from specified number will be recorded\n" #ifdef USE_REGEXP " Argument is regular expression. See 'man 7 regex' for details\n" #endif " -t T.38-filter. Only calls, containing T.38 payload indicated in SDP will be recorded\n" ,PCAPSIPDUMP_VERSION); return 1; } ct = new calltable; if (opt_t38only){ ct->erase_non_t38=1; } signal(SIGINT,sigint_handler); signal(SIGTERM,sigterm_handler); if (ifname){ printf("Capturing on interface: %s\n", ifname); /* Find the properties for interface */ if (pcap_lookupnet(ifname, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for interface %s: %s\n", ifname, errbuf); net = 0; mask = 0; } handle = pcap_open_live(ifname, 1600, opt_promisc, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open interface '%s': %s\n", ifname, errbuf); return(2); } }else{ printf("Reading file: %s\n", fname); net = 0; mask = 0; handle = pcap_open_offline(fname, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open pcap file '%s': %s\n", ifname, errbuf); return(2); } } chdir(opt_chdir); /* 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); } if (opt_fork){ // daemonize if (fork()) exit(0); } { int dlt=pcap_datalink(handle); switch (dlt){ case DLT_EN10MB : offset_to_ip=sizeof(struct ether_header); break; case DLT_LINUX_SLL : offset_to_ip=16; break; case DLT_RAW : offset_to_ip=0; break; default : { printf("Unknown interface type (%d).\n",dlt); return 3; } } } /* Retrieve the packets */ while((res = pcap_next_ex( handle, &pkt_header, &pkt_data)) >= 0){ { struct iphdr *header_ip; struct udphdr *header_udp; char *data; char *s; char str1[1024],str2[1024]; unsigned long datalen; unsigned long l; int idx; if(res == 0) /* Timeout elapsed */ continue; if (pkt_header->ts.tv_sec-last_cleanup>15){ if (last_cleanup>=0){ ct->do_cleanup(pkt_header->ts.tv_sec); } last_cleanup=pkt_header->ts.tv_sec; } header_ip=(iphdr *)((char*)pkt_data+offset_to_ip); if (header_ip->protocol==17){//UPPROTO_UDP=17 int idx_leg=0; int idx_rtp=0; int save_this_rtp_packet=0; int is_rtcp=0; uint16_t rtp_port_mask=0xffff; header_udp=(udphdr *)((char*)header_ip+sizeof(*header_ip)); data=(char *)header_udp+sizeof(*header_udp); datalen=pkt_header->len-((unsigned long)data-(unsigned long)pkt_data); if (opt_rtpsave==RTPSAVE_RTP){ save_this_rtp_packet=1; }else if (opt_rtpsave==RTPSAVE_RTP_RTCP){ save_this_rtp_packet=1; rtp_port_mask=0xfffe; is_rtcp=(htons(header_udp->source) & 1) && (htons(header_udp->dest) & 1); }else if (opt_rtpsave==RTPSAVE_RTPEVENT && datalen==18 && (data[0]&0xff) == 0x80 && (data[1]&0x7d) == 0x65){ save_this_rtp_packet=1; }else{ save_this_rtp_packet=0; } if (save_this_rtp_packet && ct->find_ip_port_ssrc( header_ip->daddr,htons(header_udp->dest) & rtp_port_mask, get_ssrc(data,is_rtcp), &idx_leg,&idx_rtp)){ if (ct->table[idx_leg].f_pcap!=NULL) { ct->table[idx_leg].last_packet_time=pkt_header->ts.tv_sec; pcap_dump((u_char *)ct->table[idx_leg].f_pcap,pkt_header,pkt_data); if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx_leg].f_pcap);} } }else if (save_this_rtp_packet && ct->find_ip_port_ssrc( header_ip->saddr,htons(header_udp->source) & rtp_port_mask, get_ssrc(data,is_rtcp), &idx_leg,&idx_rtp)){ if (ct->table[idx_leg].f_pcap!=NULL) { ct->table[idx_leg].last_packet_time=pkt_header->ts.tv_sec; pcap_dump((u_char *)ct->table[idx_leg].f_pcap,pkt_header,pkt_data); if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx_leg].f_pcap);} } }else if (htons(header_udp->source)==5060|| htons(header_udp->dest)==5060){ char caller[256]; char called[256]; char sip_method[256]; //figure out method memcpy(sip_method,data,sizeof(sip_method)-1); sip_method[sizeof(sip_method)-1]=' '; if (strchr(sip_method,' ')!=NULL){ *strchr(sip_method,' ')='\0'; }else{ sip_method[0]='\0'; if (verbosity>=2){ printf("Empty SIP method!\n"); } } data[datalen]=0; get_sip_peername(data,datalen,"From:",caller,sizeof(caller)); get_sip_peername(data,datalen,"To:",called,sizeof(called)); s=gettag(data,datalen,"Call-ID:",&l); number_filter_matched=false; #ifdef USE_REGEXP { regmatch_t pmatch[1]; if ((number_filter.allocated==0) || (regexec(&number_filter, caller, 1, pmatch, 0)==0) || (regexec(&number_filter, called, 1, pmatch, 0)==0)) { number_filter_matched=true; } } #else if (number_filter[0]==0||(strcmp(number_filter,caller)==0)||(strcmp(number_filter,called)==0)) { number_filter_matched=true; } #endif if (s!=NULL && ((idx=ct->find_by_call_id(s,l))<0) && number_filter_matched){ if ((idx=ct->add(s,l,pkt_header->ts.tv_sec))<0){ printf("Too many simultaneous calls. Ran out of call table space!\n"); }else{ if ((strcmp(sip_method,"INVITE")==0)||(strcmp(sip_method,"OPTIONS")==0)||(strcmp(sip_method,"REGISTER")==0)){ struct tm *t; t=localtime(&pkt_header->ts.tv_sec); sprintf(str2,"%04d%02d%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday); mkdir(str2,0700); sprintf(str2,"%04d%02d%02d/%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour); mkdir(str2,0700); sprintf(str2,"%04d%02d%02d/%02d/%04d%02d%02d-%02d%02d%02d-%s-%s", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour, t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec,caller,called); memcpy(str1,s,l); str1[l]='\0'; strcat(str2,"-"); strcat(str2,str1); strcat(str2,".raw"); ct->table[idx].f=NULL; str1[l]='\0'; *strstr(str2,".raw")='\0'; strcat(str2,".pcap"); ct->table[idx].f_pcap=pcap_dump_open(handle,str2); strncpy(ct->table[idx].fn_pcap,str2,sizeof(ct->table[idx].fn_pcap)); }else{ if (verbosity>=2){ printf("Unknown SIP method:'%s'!\n",sip_method); } ct->table[idx].f=NULL; ct->table[idx].f_pcap=NULL; } } } // idx holds a valid pointer to open leg at this point if (strcmp(sip_method,"BYE")==0){ ct->table[idx].had_bye=1; } s=gettag(data,datalen,"Content-Type:",&l); if(idx>=0 && l>0 && strncasecmp(s,"application/sdp",l)==0 && strstr(data,"\r\n\r\n")!=NULL){ in_addr_t tmp_addr; unsigned short tmp_port; if (!get_ip_port_from_sdp(strstr(data,"\r\n\r\n")+1,&tmp_addr,&tmp_port)){ ct->add_ip_port(idx,tmp_addr,tmp_port); }else{ if (verbosity>=2){ printf("Can't get ip/port from SDP:\n%s\n\n",strstr(data,"\r\n\r\n")+1); } } if (opt_t38only && memmem(data,datalen,"udptl t38",9)!=NULL){ ct->table[idx].had_t38=1; } } if (ct->table[idx].f_pcap!=NULL){ pcap_dump((u_char *)ct->table[idx].f_pcap,pkt_header,pkt_data); if (opt_packetbuffered) {pcap_dump_flush(ct->table[idx].f_pcap);} } }else{ if (verbosity>=3){ char st1[16]; char st2[16]; struct in_addr in; in.s_addr=header_ip->saddr; strcpy(st1,inet_ntoa(in)); in.s_addr=header_ip->daddr; strcpy(st2,inet_ntoa(in)); printf ("Skipping udp packet %s:%d->%s:%d\n",st1,htons(header_udp->source),st2,htons(header_udp->dest)); } } } } } /* flush / close files */ ct->do_cleanup(1<<31); /* And close the session */ pcap_close(handle); return(0); }
int init_socket(unsigned int loc_idx) { struct bpf_program filter; char errbuf[PCAP_ERRBUF_SIZE]; char filter_expr[FILTER_LEN]; int len=0, buffer_size = 0; LDEBUG("Activating device: %s\n", profile_socket[loc_idx].device); if (profile_socket[loc_idx].device) { buffer_size = 1024 * 1024 * profile_socket[loc_idx].ring_buffer; if ((sniffer_proto[loc_idx] = pcap_create((char *) profile_socket[loc_idx].device, errbuf)) == NULL) { LERR("Failed to open packet sniffer on %s: pcap_create(): %s", (char * )profile_socket[loc_idx].device, errbuf); return -1; }; if (pcap_set_promisc(sniffer_proto[loc_idx], profile_socket[loc_idx].promisc) == -1) { LERR("Failed to set promisc \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx])); return -1; }; if (pcap_set_timeout(sniffer_proto[loc_idx], profile_socket[loc_idx].timeout) == -1) { LERR("Failed to set timeout \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx])); return -1; }; if (pcap_set_snaplen(sniffer_proto[loc_idx], profile_socket[loc_idx].snap_len) == -1) { LERR("Failed to set snap_len [%d], \"%s\": %s", profile_socket[loc_idx].snap_len, (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx])); return -1; }; if (pcap_set_buffer_size(sniffer_proto[loc_idx], buffer_size) == -1) { LERR("Failed to set buffer_size [%d] \"%s\": %s", buffer_size, (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx])); return -1; }; if (pcap_activate(sniffer_proto[loc_idx]) != 0) { LERR("Failed to activate \"%s\": %s", (char *) profile_socket[loc_idx].device, pcap_geterr(sniffer_proto[loc_idx])); return -1; }; LDEBUG("Activated device: [%s]\n", profile_socket[loc_idx].device); } else { if ((sniffer_proto[loc_idx] = pcap_open_offline(usefile, errbuf)) == NULL) { LERR("%s: Failed to open packet sniffer on %s: pcap_open_offline(): %s", module_name, usefile, errbuf); return -1; } LNOTICE("Sending file: %s", usefile); } /* create filter string */ if(profile_socket[loc_idx].filter && strlen(profile_socket[loc_idx].filter) > 0) { len += snprintf(filter_expr+len, sizeof(filter_expr)-len, "(%s)", profile_socket[loc_idx].filter); if(ipv4fragments || ipv6fragments) { if (ipv4fragments) { LDEBUG("Reassembling of IPv4 packets is enabled, adding '%s' to filter", BPF_DEFRAGMENTION_FILTER_IPV4); len += snprintf(filter_expr+len, sizeof(filter_expr), " or %s", BPF_DEFRAGMENTION_FILTER_IPV4); } if (ipv6fragments) { LDEBUG("Reassembling of IPv6 packets is enabled, adding '%s' to filter", BPF_DEFRAGMENTION_FILTER_IPV6); len += snprintf(filter_expr+len, sizeof(filter_expr), " or %s", BPF_DEFRAGMENTION_FILTER_IPV6); } } } if(profile_socket[loc_idx].capture_filter) { if(!strncmp(profile_socket[loc_idx].capture_filter, "rtcp", 4)) { len += snprintf(filter_expr+len, sizeof(filter_expr), "%s %s", len ? " and" : "", RTCP_FILTER); } else if(!strncmp(profile_socket[loc_idx].capture_filter, "rtp", 3)) { len += snprintf(filter_expr+len, sizeof(filter_expr), "%s %s", len ? " and" : "", RTP_FILTER); } } LNOTICE("Using filter: %s", filter_expr); /* compile filter expression (global constant, see above) */ if (pcap_compile(sniffer_proto[loc_idx], &filter, filter_expr, 1, 0) == -1) { LERR("Failed to compile filter \"%s\": %s", filter_expr, pcap_geterr(sniffer_proto[loc_idx])); return -1; } /* install filter on sniffer session */ if (pcap_setfilter(sniffer_proto[loc_idx], &filter)) { LERR("Failed to install filter: %s", pcap_geterr(sniffer_proto[loc_idx])); return -1; } //disabled temporaly //pcap_freecode(&filter); return 1; }
/** * @brief 打开制定索引的设备 * * @param int selIndex 传入需要打开设备的索引,索引号码从0开始 * @param int selFilter 传入包过滤器,默认值为-1,表示截取所有类型的包 * * @return bool 返回true表示打开成功,返回false表示打开失败 */ bool Wincap::OpenDevice(int selIndex, int selFilter/* = -1*/) { bool bRet = false; u_int netmask; struct bpf_program fcode; do{ //判断所有索引是否符合,如果不符合则跳出 if ((selIndex < 0 || selIndex >= mDevCount) || (selFilter != -1 && (selFilter < 0 || selFilter >= mFilter.size()))) { const char* errormsg = "打开索引错误,请确认后再尝试"; strcpy(mErrbuf, errormsg); break; } pcap_if_t* seldev = nullptr; pcap_if_t* dev = mAlldev; //根据索引找到需要打开的设备 for (int i = 0; i < selIndex; i++) { dev = dev->next; } seldev = dev; //打开需要打开的设备 if ((mAdhandle = pcap_open_live(seldev->name, 65536, 1, 1000, mErrbuf)) == nullptr) { const char* errormsg = "打开指定的设备出错,请确认后再尝试"; strcpy(mErrbuf, errormsg); break; } //打开数据包连接 if (pcap_datalink(mAdhandle) != DLT_EN10MB) { const char* errormsg = "这不适合于非以太网的网络"; strcpy(mErrbuf, errormsg); break; } //如果打开设备的地址存在,那么掩码否则传入默认值 if (dev->addresses != NULL) netmask = ((struct sockaddr_in *)(dev->addresses->netmask))->sin_addr.S_un.S_addr; else netmask = 0xffffff; //如果传入的过滤器是-1,那么表示所有类型的包都需要抓取 if (selFilter == -1) { char filter[] = ""; //将过滤器加载到已经打开设备,如果打开失败则跳出 if (pcap_compile(mAdhandle, &fcode, filter, 1, netmask) < 0) { const char* errormsg = "语法错误,无法编译过滤器"; strcpy(mErrbuf, errormsg); break; } } else { //保存选择的设备索引 std::string selfilter = mFilter[selFilter]; char* filter = new char[selfilter.length() + 1]; strcpy(filter, selfilter.c_str()); //将过滤器加载到已经打开的设备上面,如果打开失败则跳出 if (pcap_compile(mAdhandle, &fcode, filter, 1, netmask) < 0) { const char* errormsg = "语法错误,无法编译过滤器"; strcpy(mErrbuf, errormsg); break; } } //设置过滤器 if (pcap_setfilter(mAdhandle, &fcode) < 0) { const char* errormsg = "设置过滤器错误"; strcpy(mErrbuf, errormsg); break; } //设置自动保存文件 if (mbSaveFile) { FileFind file; char thistime[30]; struct tm* ltime; memset(mFilepath, 0, 512); memset(mFilename, 0, 64); if (!file.IsDirectoryExist(_T("SavedData"))) { CreateDirectory(_T("SavedData"), NULL); } time_t nowtime; time(&nowtime); ltime = localtime(&nowtime); strftime(thistime, sizeof(thistime), "%Y%m%d %H%M%S", ltime); strcpy(mFilepath, "SavedData\\"); strcat(mFilename, thistime); strcat(mFilename, ".lix"); strcat(mFilepath, mFilename); mDumpfile = pcap_dump_open(mAdhandle, mFilepath); if (mDumpfile == NULL) { const char* errormsg = "文件创建错误"; strcpy(mErrbuf, errormsg); break; } } bRet = true; } while (false); return bRet; }
int main(int argc, char** argv) { char errbuf[PCAP_ERRBUF_SIZE]; char* interface = NULL; char* outfile = NULL; guint snaplen = 65536; char* start_filter_str = NULL; char* stop_filter_str = NULL; char* capture_filter_str = NULL; int promisc = 0; int quiet = 0; struct bpf_program start_filter; struct bpf_program capture_filter; pcap_t* capturer = NULL; pcap_dumper_t* dumper = NULL; int opt; while ((opt = getopt(argc, argv, "i:w:s:b:e:f:phdq")) != -1) { switch (opt) { case 'i': if (interface) panic(1,"interface already given"); interface = g_strdup(optarg); break; case 'w': if (outfile) panic(3,"output file already given"); outfile = g_strdup(optarg); break; case 's': snaplen = strtoul(optarg,NULL,10); if ( snaplen == 0 ) panic(4,"invalid snaplen"); break; case 'b': if (start_filter_str) panic(5,"start filter already given"); start_filter_str = g_strdup(optarg); break; case 'e': if (stop_filter_str) panic(6,"stop filter already given"); stop_filter_str = g_strdup(optarg); break; case 'f': if (capture_filter_str) panic(7,"capture filter already given"); capture_filter_str = g_strdup(optarg); break; case 'p': promisc = 1; break; case 'q': quiet = 1; break; case 'd': debug_level++; break; case 'h': default: usage(0); break; } } dprintf(1,"starting with:\n interface: %s\n snaplen: %d\n promisc: %d" "\n outfile: %s\n capture filter: %s\n start: %s\n stop: %s\n debug level: %d\n", interface ? interface : "to be chosen", snaplen, promisc, outfile ? outfile : "** missing **", capture_filter_str ? capture_filter_str : "** none given **", start_filter_str ? start_filter_str : "** missing **", stop_filter_str ? stop_filter_str : "** missing **", debug_level); if (! ( start_filter_str && stop_filter_str && outfile ) ) { usage(10); } if (! interface) { interface = pcap_lookupdev(errbuf); if (!interface) { panic(11, "could not obtain an interface: %s\n",errbuf); } } #ifdef HAVE_PCAP_OPEN if ( ! ( capturer = pcap_open(interface, snaplen, promisc, 1, NULL, errbuf) )) { #else if ( ! ( capturer = pcap_open_live(interface, snaplen, promisc, 1, errbuf) )) { #endif panic(12,"could not open interface '%s' for listener: %s\n",interface,errbuf); } dprintf(1,"opened listener (%s,%d,%d)\n",interface,snaplen, promisc); if (pcap_compile(listener, &start_filter, start_filter_str, 1, 0) < 0) { panic(13,"could not compile start filter: %s\n",pcap_geterr(listener)); } dprintf(2,"compiled start filter %s\n",start_filter_str); if (pcap_compile(listener, &stop_filter, stop_filter_str, 1, 0) < 0) { panic(14,"could not compile stop filter: %s\n",pcap_geterr(listener)); } dprintf(2,"compiled stop filter %s\n",stop_filter_str); #ifdef HAVE_PCAP_OPEN if ( ! ( capturer = pcap_open(interface, snaplen, promisc, 1, NULL, errbuf) )) { #else if ( ! ( capturer = pcap_open_live(interface, snaplen, promisc, 1, errbuf) )) { #endif panic(15,"could not open interface '%s' for capturer: %s\n",interface, errbuf); } dprintf(1,"opened capturer (%s,%d,%d)\n",interface,snaplen, promisc); if (capture_filter_str) { if (pcap_compile(capturer, &capture_filter, capture_filter_str, 1, 0) < 0) { panic(16,"could not compile capture filter: %s\n",pcap_geterr(capturer)); } if (pcap_setfilter(capturer, &capture_filter) < 0) { panic(17,"could not apply start filter to capturer: %s\n",pcap_geterr(capturer)); } dprintf(2,"compiled and set capture filter (%s)\n",capture_filter_str); } if (pcap_setfilter(listener, &start_filter) < 0) { panic(18,"could not apply start filter to listener: %s\n",pcap_geterr(listener)); } dprintf(2,"set start filter on listener\n"); if (pcap_setnonblock(listener, 0, errbuf) < 0) { panic(19,"could not set listener in blocking mode: %s\n",errbuf); } dprintf(2,"listener -> blocking\n"); if (pcap_setnonblock(capturer, 1, errbuf) < 0) { panic(20,"could not set capturer in non blocking mode: %s\n",errbuf); } dprintf(2,"capturer -> non_blocking\n"); if (! (dumper = pcap_dump_open(listener,outfile)) ) { panic(21,"open dumper file '%s': %s\n",outfile,pcap_geterr(listener)); } dprintf(2,"opened dumper file '%s'\n",outfile); signal(SIGINT, sig_int); #ifdef SIGQUIT signal(SIGQUIT, sig_int); #endif #ifdef SIGTERM signal(SIGTERM, sig_int); #endif #ifdef SIGSTOP signal(SIGSTOP, sig_int); #endif keep_going = 1; dumping = 0; do { if (pcap_dispatch(listener, -1, listener_handler, NULL) < 0 ) { panic(22,"pcap_dispatch(listener) failed: %s\n",pcap_geterr(listener)); } if (pcap_dispatch(capturer, -1, capture_handler, (void*)dumper) < 0 ) { panic(23,"pcap_dispatch(capturer) failed: %s\n",pcap_geterr(capturer)); } } while(keep_going); if (!quiet) { printf("%d packets captured\n",captured); } dprintf(1,"done!\n"); pcap_dump_close(dumper); pcap_close(listener); pcap_close(capturer); return 0; }
int main(int argc, char **argv) { char *dev = NULL; /* capture device name */ char *filter_exp = ""; char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ bpf_u_int32 mask; /* subnet mask */ bpf_u_int32 net; /* ip */ struct bpf_program fp; /* compiled filter program (expression) */ pcap_t *handle; /* packet capture handle */ int i; /* iterator for command-line argument */ int opt_flag = 0; /* option flag 1 for device 2 for filter */ /* check for capture device name on command-line */ if (argc >= 2) { for( i = 1 ; i < argc ; i++) { if (argv[i][0] == '-' || strlen(argv[i]) == 2) { switch(argv[i][1]){ case 'D': /* device */ opt_flag = 1; break; case 'f': /* filter */ opt_flag = 2; break; default: fprintf(stderr, "error option type %s\n", argv[i]); exit(EXIT_FAILURE); } } else if ( opt_flag == 0 ){/* expect -D -f */ fprintf(stderr, "Error for command-line: expect -D -f, but get %s\n", argv[i]); exit(EXIT_FAILURE); } else{ /* expect argument */ switch( opt_flag ) { case 1: dev = argv[i]; break; case 2: filter_exp = argv[i]; break; } } } } /* find a capture device if not specified on command-line */ if ( dev == NULL ){ dev = pcap_lookupdev(errbuf); if (dev == NULL) { fprintf(stderr, "Couldn't find default device: %s\n", errbuf); exit(EXIT_FAILURE); } } printf("Device: %s\n", dev); printf("Filter expression: %s\n", filter_exp); printf("DEBUG: opt_flag = %d\n", opt_flag); if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Can't get netmask for device %s\n", dev); net = 0; mask = 0; } printf("DEBUG: net = %d, mask = %d\n", net, mask); /* open capture device */ handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); exit(EXIT_FAILURE); } printf("handle: %s\n", handle); if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "%s is not an Ethernet\n", dev); exit(EXIT_FAILURE); } /* compile the filter expression */ 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(EXIT_FAILURE); } if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } printf("I am out.\n"); /* set callback function */ pcap_loop(handle, num_packets, get_packet, NULL); /* cleanup */ pcap_freecode(&fp); pcap_close(handle); printf("\nCapture complete.\n"); return 0; }
int CDECL wine_pcap_compile(pcap_t *p, struct bpf_program *program, const char *buf, int optimize, unsigned int mask) { TRACE("(%p %p %s %i %u)\n", p, program, debugstr_a(buf), optimize, mask); return pcap_compile(p, program, buf, optimize, mask); }
void sniff(char *in_if, char *out_if, char *in_file, char *out_file, TableStateMachine *machine, int num_workers, int no_report, int batch) { pcap_t *hpcap[2]; char errbuf[PCAP_ERRBUF_SIZE]; char *device_in = NULL, *device_out = NULL; pcap_if_t *devices, *next_device; int res; struct bpf_program bpf; ProcessorData *processor; int linktype[2], linkHdrLen, i; char *mode; memset(errbuf, 0, PCAP_ERRBUF_SIZE); if (in_if || out_if) { // Find available interfaces if (pcap_findalldevs(&devices, errbuf)) { fprintf(stderr, "[Sniffer] ERROR: Cannot find network interface (pcap_findalldevs error: %s)\n", errbuf); exit(1); } // Find requested interface next_device = devices; while (next_device) { printf("[Sniffer] Found network interface: %s\n", next_device->name); if (in_if && (strcmp(in_if, next_device->name) == 0)) { device_in = in_if; } if (out_if && (strcmp(out_if, next_device->name) == 0)) { device_out = out_if; } next_device = next_device->next; } pcap_freealldevs(devices); if (in_if && (strcmp(in_if, STR_ANY) == 0)) { device_in = STR_ANY; } if (in_if && !device_in) { fprintf(stderr, "[Sniffer] ERROR: Cannot find input network interface\n"); exit(1); } if (out_if && !device_out) { fprintf(stderr, "[Sniffer] ERROR: Cannot find output network interface\n"); exit(1); } } if (in_if) { printf("[Sniffer] Sniffer is capturing from device: %s\n", device_in); } else { printf("[Sniffer] Sniffer is reading packets from file: %s\n", in_file); } if (out_if) { printf("[Sniffer] Packets are sent on device: %s\n", device_out); } else { printf("[Sniffer] Packets written to file: %s\n", out_file); } if (in_if) { hpcap[0] = pcap_create(device_in, errbuf); } else { hpcap[0] = pcap_open_offline(in_file, errbuf); } if (out_if) { hpcap[1] = pcap_create(device_out, errbuf); } else { //hpcap[1] = pcap_dump_fopen(out_file, errbuf); } for (i = 0; i < 2; i++) { mode = (i == 0) ? "input" : "output"; // Check pcap handle if (!hpcap[i]) { fprintf(stderr, "[Sniffer] ERROR: Cannot create %s pcap handle (pcap_create/pcap_open_offline error: %s)\n", mode ,errbuf); exit(1); } if (in_if && i == 0) { // Set promiscuous mode pcap_set_promisc(hpcap[0], 1); } // Activate PCAP if ((in_if && i == 0) || (out_if && i == 1)) { res = pcap_activate(hpcap[i]); switch (res) { case 0: // Success break; case PCAP_WARNING_PROMISC_NOTSUP: fprintf(stderr, "[Sniffer] WARNING: Promiscuous mode is not supported\n"); exit(1); break; case PCAP_WARNING: fprintf(stderr, "[Sniffer] WARNING: Unknown (%s)\n", pcap_geterr(hpcap[i])); exit(1); break; case PCAP_ERROR_NO_SUCH_DEVICE: fprintf(stderr, "[Sniffer] ERROR: Device not found\n"); exit(1); break; case PCAP_ERROR_PERM_DENIED: fprintf(stderr, "[Sniffer] ERROR: Permission denied\n"); exit(1); break; case PCAP_ERROR_PROMISC_PERM_DENIED: fprintf(stderr, "[Sniffer] ERROR: Permission denied for promiscuous mode\n"); exit(1); break; case PCAP_ERROR_RFMON_NOTSUP: fprintf(stderr, "[Sniffer] ERROR: Monitor mode is not supported\n"); exit(1); break; case PCAP_ERROR_IFACE_NOT_UP: fprintf(stderr, "[Sniffer] ERROR: Interface %s is not available\n", (i == 0) ? device_in : device_out); exit(1); break; default: fprintf(stderr, "[Sniffer] ERROR: Unknown (%s)\n", pcap_geterr(hpcap[i])); exit(1); break; } } if (i == 0) { if (in_if) { // Set capture direction (ingress only) res = pcap_setdirection(hpcap[0], PCAP_D_IN); if (res) { fprintf(stderr, "[Sniffer] ERROR: Cannot set capture direction (pcap_setdirection error: %s, return value: %d)\n", pcap_geterr(hpcap[0]), res); exit(1); } } // Compile PCAP filter (IP packets) res = pcap_compile(hpcap[0], &bpf, STR_FILTER, 0, PCAP_NETMASK_UNKNOWN); if (res) { fprintf(stderr, "[Sniffer] ERROR: Cannot compile packet filter (pcap_compile error: %s)\n", pcap_geterr(hpcap[0])); exit(1); } res = pcap_setfilter(hpcap[0], &bpf); if (res) { fprintf(stderr, "[Sniffer] ERROR: Cannot set packet filter (pcap_setfilter error: %s, return value: %d)\n", pcap_geterr(hpcap[0]), res); exit(1); } pcap_freecode(&bpf); } // Find data link type if ((linktype[i] = pcap_datalink(hpcap[i])) < 0) { fprintf(stderr, "[Sniffer] Cannot determine data link type (pcap_datalink error: %s)\n", pcap_geterr(hpcap[i])); exit(1); } if (i == 1 && linktype[0] != linktype[1]) { fprintf(stderr, "[Sniffer] Incompatible link types (input=%d, output=%d)\n", linktype[0], linktype[1]); exit(1); } } linkHdrLen = 0; switch (linktype[0]) { case DLT_NULL: linkHdrLen = 4; break; case DLT_EN10MB: linkHdrLen = 14; break; case DLT_SLIP: case DLT_PPP: linkHdrLen = 24; break; default: fprintf(stderr, "[Sniffer] Unsupported data link type: %d\n", linktype[0]); exit(1); } // Prepare processor processor = init_processor(machine, hpcap[0], hpcap[1], linkHdrLen, num_workers, no_report, batch); _global_processor = processor; // Set signal handler signal(SIGINT, stop); signal(SIGTERM, stop); signal(SIGQUIT, stop); // Run sniffer gettimeofday(&(processor->start), NULL); printf("[Sniffer] Sniffer is running (input: %s, outout: %s)...\n", in_if, out_if); res = pcap_loop(hpcap[0], -1, process_packet, (unsigned char *)(processor)); stop(res); }
int getRemoteARP(struct pm_cfg cfg, unsigned int targetIP, const char *device, char *mac) { unsigned int localIP; char errbuf[PCAP_ERRBUF_SIZE] = {0}; ARPPACKET arp; struct bpf_program fp; struct pcap_pkthdr *header; const u_char *pkt_data; int sent = 0; int found = 1; char filter[100] = {0}; struct in_addr addr; pcap_t *pHandle = pcap_open_live(device, SNAP_LEN, 0, ARP_WAIT_TIME, errbuf); if (pHandle == NULL) { syslog(LOG_ERR, "unable to open capture device %s: %s", device, errbuf); return -1; } if (getInterfaceIP(device, &localIP) < 0) { syslog(LOG_ERR, "unable to get IP address for %s", device); pcap_close(pHandle); return -1; } //send arp request to an IP. memset(&arp, 0, sizeof(arp)); memset(arp.ethhdr.h_dest, 0xFF, ETH_ALEN); arp.ethhdr.h_proto = htons(ETH_P_ARP); arp.arphdr.ar_hrd = htons(ETH_P_802_3); arp.arphdr.ar_pro = htons(ETH_P_IP); arp.arphdr.ar_hln = ETH_ALEN; // Hardware size: 6(0x06) arp.arphdr.ar_pln = 4; // Protocol size; 4 arp.arphdr.ar_op = htons(ARPOP_REQUEST); // Opcode: request (0x0001) memset(arp.arphdr.ar_tha, 0, ETH_ALEN); arp.arphdr.ar_tip = targetIP; memcpy(arp.ethhdr.h_source, cfg.src_mac, ETH_ALEN); memcpy(arp.arphdr.ar_sha, cfg.src_mac, ETH_ALEN); arp.arphdr.ar_sip = localIP; addr.s_addr = targetIP; sprintf(filter, "arp host %s", inet_ntoa(addr)); pcap_compile(pHandle, &fp, filter, 0, 0); pcap_setfilter(pHandle, &fp); pcap_sendpacket(pHandle, (unsigned char *)&arp, sizeof(arp)); while (1) { int res = pcap_next_ex(pHandle, &header, &pkt_data); if (res == 1) { if (*(unsigned short *)(pkt_data + 12) == htons(0x0806) && header->len >= sizeof(ARPPACKET)) { ARPPACKET* p = (ARPPACKET *)pkt_data; if (p->arphdr.ar_op == htons(ARPOP_REPLY) && p->arphdr.ar_sip == targetIP) { memcpy(mac, (const char *)p->ethhdr.h_source, ETH_ALEN); found = 0; if (cfg.flags & PM_DEBUG) { syslog(LOG_INFO, "ARP reply on '%s'['%s'] filter '%s'", device, printMACStr(mac), filter); } break; } } } if (res == 0) { if (sent++ < 2) { pcap_sendpacket(pHandle, (unsigned char *)&arp, sizeof(arp)); } else { break; } } if (res == -1) { syslog(LOG_ERR, "error reading packet: %s", pcap_geterr(pHandle)); break; } } pcap_close(pHandle); return found; }
/* name : input_init */ static int input_init( probe_t *probe, int flags ) { char *device = g_par.interface; int dltype; if ( flags & PROBE_OFFLINE ) { /* open file */ if ( (probe->pcap=pcap_open_offline( device, errbuf )) ==NULL) { errorf( "[%s] pcap_open_offline(): %s\n", device, errbuf ); return -1; } probe->cnt = 1; } else { /* open interface */ int promisc = (flags&PROBE_PROMISC)?1:0; char *p = probe->device; if ( *device == '\0' ) { if ((device=pcap_lookupdev( errbuf )) ==NULL) { errorf( "pcap_lookupdev() failed: %s\n", errbuf ); return -1; } } if ( (probe->pcap=pcap_open_live( device, g_snaplen, promisc, 100 /*ms*/, errbuf )) ==NULL ) { /* todo!! */ errorf( "pcap_open_live(%s): %s\n", p, errbuf ); return -1; } probe->cnt = 1000; } switch ( dltype = pcap_datalink(probe->pcap) ) { case DLT_EN10MB: probe->dltype = dltype; probe->offset = 14; break; case DLT_ATM_RFC1483: probe->dltype = dltype; probe->offset = 8; break; default: probe->dltype = DLT_RAW; probe->offset = 0; } if( g_par.filter != NULL ) { if( (pcap_compile( probe->pcap, &probe->fprg, g_par.filter, 1, 0 ) <0) || (pcap_setfilter( probe->pcap, &probe->fprg ) <0) ) { mlogf( 0, "[%s] unable to set filter: '%s'\n", g_par.progname, g_par.filter ); } else { mlogf( 1, "[%s] set filter to '%s'\n", g_par.progname, g_par.filter ); } } mlogf( 1, "[%s] device: %s, dltype=%d, %s\n", g_par.progname, (flags&PROBE_OFFLINE)?basename(device):device, probe->dltype, (flags&PROBE_OFFLINE)?"offline" :(flags&PROBE_PROMISC)?"promisc.":"no promisc." ); if ( flags & PROBE_OFFLINE ) { probe->fd = fileno( pcap_file( probe->pcap ) ); probe->device = strdup( basename( device ) ); } else { probe->fd = pcap_fileno( probe->pcap ); probe->device = strdup( device ); } if ( probe->fd >= 0) { if ( mpoll_fdadd( probe->fd, MPOLL_IN, cb_dispatch, (void*)probe ) <0 ) { mlogf( 0, "[%s] %s\n", g_par.progname, strerror(errno) ); return -1; } mlogf( 2, "[%s] add fd %d to poll loop\n", g_par.progname, probe->fd ); } if ( flow_init( &(probe->ipflows), g_par.ipflow_max, g_par.biflows, g_par.ipflow_timeout ) <0 ) { mlogf( 0, "[%s] ipflow initialisation failed: %s", g_par.progname, strerror(errno) ); return -1; } return 0; }
int main(int argc, char **argv) { register char *cp; register int op, pid, snaplen, timeout, linktype, status; #ifdef TIOCNOTTY register int fd; #endif register pcap_t *pd; register char *interface, *rfilename; struct bpf_program code; char errbuf[PCAP_ERRBUF_SIZE]; if (argv[0] == NULL) prog = "arpwatch"; else if ((cp = strrchr(argv[0], '/')) != NULL) prog = cp + 1; else prog = argv[0]; if (abort_on_misalignment(errbuf) < 0) { (void)fprintf(stderr, "%s: %s\n", prog, errbuf); exit(1); } opterr = 0; interface = NULL; rfilename = NULL; pd = NULL; while ((op = getopt(argc, argv, "df:i:n:Nr:")) != EOF) switch (op) { case 'd': ++debug; #ifndef DEBUG (void)fprintf(stderr, "%s: Warning: Not compiled with -DDEBUG\n", prog); #endif break; case 'f': arpfile = optarg; break; case 'i': interface = optarg; break; case 'n': if (!addnet(optarg)) usage(); break; case 'N': ++nobogons; break; case 'r': rfilename = optarg; break; default: usage(); } if (optind != argc) usage(); if (rfilename != NULL) { net = 0; netmask = 0; } else { /* Determine interface if not specified */ if (interface == NULL && (interface = pcap_lookupdev(errbuf)) == NULL) { (void)fprintf(stderr, "%s: lookup_device: %s\n", prog, errbuf); exit(1); } /* Determine network and netmask */ if (pcap_lookupnet(interface, &net, &netmask, errbuf) < 0) { (void)fprintf(stderr, "%s: bad interface %s: %s\n", prog, interface, errbuf); exit(1); } /* Drop into the background if not debugging */ if (!debug) { pid = fork(); if (pid < 0) { syslog(LOG_ERR, "main fork(): %m"); exit(1); } else if (pid != 0) exit(0); (void)close(fileno(stdin)); (void)close(fileno(stdout)); (void)close(fileno(stderr)); #ifdef TIOCNOTTY fd = open("/dev/tty", O_RDWR); if (fd >= 0) { (void)ioctl(fd, TIOCNOTTY, 0); (void)close(fd); } #else (void) setsid(); #endif } } openlog(prog, 0, LOG_DAEMON); if (chdir(arpdir) < 0) { syslog(LOG_ERR, "chdir(%s): %m", arpdir); syslog(LOG_ERR, "(using current working directory)"); } if (rfilename != NULL) { pd = pcap_open_offline(rfilename, errbuf); if (pd == NULL) { syslog(LOG_ERR, "pcap open %s: %s", rfilename, errbuf); exit(1); } swapped = pcap_is_swapped(pd); } else { snaplen = max(sizeof(struct ether_header), sizeof(struct fddi_header)) + sizeof(struct ether_arp); timeout = 1000; pd = pcap_open_live(interface, snaplen, 1, timeout, errbuf); if (pd == NULL) { syslog(LOG_ERR, "pcap open %s: %s", interface, errbuf); exit(1); } #ifdef WORDS_BIGENDIAN swapped = 1; #endif } /* * Revert to non-privileged user after opening sockets * (not needed on most systems). */ setgid(getgid()); setuid(getuid()); /* Must be ethernet or fddi */ linktype = pcap_datalink(pd); if (linktype != DLT_EN10MB && linktype != DLT_FDDI) { syslog(LOG_ERR, "Link layer type %d not ethernet or fddi", linktype); exit(1); } /* Compile and install filter */ if (pcap_compile(pd, &code, "arp or rarp", 1, netmask) < 0) { syslog(LOG_ERR, "pcap_compile: %s", pcap_geterr(pd)); exit(1); } if (pcap_setfilter(pd, &code) < 0) { syslog(LOG_ERR, "pcap_setfilter: %s", pcap_geterr(pd)); exit(1); } if (rfilename == NULL) syslog(LOG_INFO, "listening on %s", interface); /* Read in database */ initializing = 1; if (!readdata()) exit(1); sorteinfo(); #ifdef DEBUG if (debug > 2) { debugdump(); exit(0); } #endif initializing = 0; (void)setsignal(SIGINT, die); (void)setsignal(SIGTERM, die); (void)setsignal(SIGHUP, die); if (rfilename == NULL) { (void)setsignal(SIGQUIT, checkpoint); (void)setsignal(SIGALRM, checkpoint); (void)alarm(CHECKPOINT); } switch (linktype) { case DLT_EN10MB: status = pcap_loop(pd, 0, process_ether, NULL); break; case DLT_FDDI: status = pcap_loop(pd, 0, process_fddi, NULL); break; default: syslog(LOG_ERR, "bad linktype %d (can't happen)", linktype); exit(1); } if (status < 0) { syslog(LOG_ERR, "pcap_loop: %s", pcap_geterr(pd)); exit(1); } pcap_close(pd); if (!dump()) exit(1); exit(0); }
int main(int ac, char **av) { pcap_t *handle; char errbuf[PCAP_ERRBUF_SIZE]; struct bpf_program fp; char filter_exp[FILTER_MAX_SIZE]; bpf_u_int32 mask; bpf_u_int32 net; u_char *packet; pthread_t scheduler; signal_prep(); packet=0; e=init_env(); get_opt(ac, av); #ifndef __APPLE__ if (!(e->option & OPT_VERBOSE)) daemon(ZERO,ZERO); if (e->option & OPT_GARBAGE) new_process(ac, av); #endif write_pid_number(e->pidfile_path); if (IS_VERBOSE) { send_log(LOG_INFO, "[1] verbose : on\n"); send_log(LOG_DEBUG, "[2] Preallocate msg mem size (alignement not include) : %d x %u = %u\n", e->max_tab_size,sizeof(t_msg),e->max_tab_size * (sizeof(t_msg))); send_log(LOG_DEBUG, "[3] device : [%s]\n",e->dev); send_log(LOG_DEBUG, "[4] filter : [%s]\n",e->filter); } if (pthread_mutex_init(&gl_lock_set_rmq, NULL) != 0) { send_log(LOG_CRIT, "[5] Mutex init failed\n"); mooner_exit(EXIT_MUTEX_ERR); } set_rmq_server_list(); if (pthread_mutex_init(&gl_lock_garbage, NULL) != 0) { send_log(LOG_CRIT, "[5] Mutex init failed\n"); mooner_exit(EXIT_MUTEX_ERR); } if (pthread_mutex_init(&gl_lock_send_data, NULL) != 0) { send_log(LOG_CRIT, "[44] Mutex init failed\n"); mooner_exit(EXIT_MUTEX_ERR); } if (pthread_create(&scheduler,NULL,th_scheduler,NULL) != ZERO) { send_log(LOG_CRIT, "[6] Can't create Thread for scheduling\n"); mooner_exit(EXIT_THREAD_CREA); } if (!IS_DEVICE) e->dev = pcap_lookupdev(errbuf); if (e->dev== NULL) { send_log(LOG_ERR, "[7] Couldn't find default dev: %s\n", errbuf); mooner_exit(2); } if (pcap_lookupnet(e->dev, &net, &mask, errbuf) == -1) { send_log(LOG_ERR, "[8] Couldn't get netmask for dev %s: %s\n", e->dev, errbuf); net = 0; mask = 0; } handle = pcap_open_live(e->dev, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { send_log(LOG_ERR, "[9] Couldn't open dev %s: %s\n", e->dev, errbuf); mooner_exit(2); } if (pcap_compile(handle, &fp, e->filter, 0, net) == -1) { send_log(LOG_ERR, "[10] Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); mooner_exit(2); } if (pcap_setfilter(handle, &fp) == -1) { send_log(LOG_ERR, "[11] Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); mooner_exit(2); } #ifdef DMALLOC dmalloc_debug_setup("debug=0x4f47d03,log=logfile"); #endif while(!(EXITING)) { if (IS_VERBOSE) send_log(LOG_DEBUG, "[12] entering loop\n"); pcap_loop(handle, -1, handle_packet, packet); } pcap_close(handle); mooner_exit(ZERO); return(ZERO); }
int main(int argc, char **argv) { char *cp; int op; int dflag; int gflag; char *infile; int Oflag; long snaplen; char *p; int dlt; int have_fcode = 0; bpf_u_int32 netmask = PCAP_NETMASK_UNKNOWN; char *cmdbuf; pcap_t *pd; struct bpf_program fcode; #ifdef _WIN32 if (pcap_wsockinit() != 0) return 1; #endif /* _WIN32 */ dflag = 1; gflag = 0; infile = NULL; Oflag = 1; snaplen = 68; if ((cp = strrchr(argv[0], '/')) != NULL) program_name = cp + 1; else program_name = argv[0]; opterr = 0; while ((op = getopt(argc, argv, "dF:gm:Os:")) != -1) { switch (op) { case 'd': ++dflag; break; case 'g': #ifdef BDEBUG ++gflag; #else error("libpcap and filtertest not built with optimizer debugging enabled"); #endif break; case 'F': infile = optarg; break; case 'O': Oflag = 0; break; case 'm': { bpf_u_int32 addr; switch (inet_pton(AF_INET, optarg, &addr)) { case 0: error("invalid netmask %s", optarg); break; case -1: error("invalid netmask %s: %s", optarg, pcap_strerror(errno)); break; case 1: netmask = addr; break; } break; } case 's': { char *end; snaplen = strtol(optarg, &end, 0); if (optarg == end || *end != '\0' || snaplen < 0 || snaplen > 65535) error("invalid snaplen %s", optarg); else if (snaplen == 0) snaplen = 65535; break; } default: usage(); /* NOTREACHED */ } } if (optind >= argc) { usage(); /* NOTREACHED */ } dlt = pcap_datalink_name_to_val(argv[optind]); if (dlt < 0) { dlt = (int)strtol(argv[optind], &p, 10); if (p == argv[optind] || *p != '\0') error("invalid data link type %s", argv[optind]); } if (infile) cmdbuf = read_infile(infile); else cmdbuf = copy_argv(&argv[optind+1]); #ifdef BDEBUG pcap_set_optimizer_debug(dflag); pcap_set_print_dot_graph(gflag); #endif pd = pcap_open_dead(dlt, snaplen); if (pd == NULL) error("Can't open fake pcap_t"); if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) error("%s", pcap_geterr(pd)); have_fcode = 1; if (!bpf_validate(fcode.bf_insns, fcode.bf_len)) warn("Filter doesn't pass validation"); #ifdef BDEBUG if (cmdbuf != NULL) { // replace line feed with space for (cp = cmdbuf; *cp != '\0'; ++cp) { if (*cp == '\r' || *cp == '\n') { *cp = ' '; } } // only show machine code if BDEBUG defined, since dflag > 3 printf("machine codes for filter: %s\n", cmdbuf); } else printf("machine codes for empty filter:\n"); #endif bpf_dump(&fcode, dflag); free(cmdbuf); if (have_fcode) pcap_freecode (&fcode); pcap_close(pd); exit(0); }
static int l2_packet_init_libpcap(struct l2_packet_data *l2, unsigned short protocol) { bpf_u_int32 pcap_maskp, pcap_netp; char pcap_filter[200], pcap_err[PCAP_ERRBUF_SIZE]; struct bpf_program pcap_fp; #ifdef CONFIG_WINPCAP char ifname[128]; os_snprintf(ifname, sizeof(ifname), "\\Device\\NPF_%s", l2->ifname); pcap_lookupnet(ifname, &pcap_netp, &pcap_maskp, pcap_err); l2->pcap = pcap_open_live(ifname, 2500, 0, 10, pcap_err); if (l2->pcap == NULL) { fprintf(stderr, "pcap_open_live: %s\n", pcap_err); fprintf(stderr, "ifname='%s'\n", ifname); return -1; } if (pcap_setnonblock(l2->pcap, 1, pcap_err) < 0) fprintf(stderr, "pcap_setnonblock: %s\n", pcap_geterr(l2->pcap)); #else /* CONFIG_WINPCAP */ pcap_lookupnet(l2->ifname, &pcap_netp, &pcap_maskp, pcap_err); l2->pcap = pcap_open_live(l2->ifname, 2500, 0, 10, pcap_err); if (l2->pcap == NULL) { fprintf(stderr, "pcap_open_live: %s\n", pcap_err); fprintf(stderr, "ifname='%s'\n", l2->ifname); return -1; } if (pcap_datalink(l2->pcap) != DLT_EN10MB && pcap_set_datalink(l2->pcap, DLT_EN10MB) < 0) { fprintf(stderr, "pcap_set_datalink(DLT_EN10MB): %s\n", pcap_geterr(l2->pcap)); return -1; } #endif /* CONFIG_WINPCAP */ os_snprintf(pcap_filter, sizeof(pcap_filter), "not ether src " MACSTR " and " "( ether dst " MACSTR " or ether dst " MACSTR " ) and " "ether proto 0x%x", MAC2STR(l2->own_addr), /* do not receive own packets */ MAC2STR(l2->own_addr), MAC2STR(pae_group_addr), protocol); if (pcap_compile(l2->pcap, &pcap_fp, pcap_filter, 1, pcap_netp) < 0) { fprintf(stderr, "pcap_compile: %s\n", pcap_geterr(l2->pcap)); return -1; } if (pcap_setfilter(l2->pcap, &pcap_fp) < 0) { fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(l2->pcap)); return -1; } pcap_freecode(&pcap_fp); #ifdef BIOCIMMEDIATE /* * When libpcap uses BPF we must enable "immediate mode" to * receive frames right away; otherwise the system may * buffer them for us. */ { unsigned int on = 1; if (ioctl(pcap_fileno(l2->pcap), BIOCIMMEDIATE, &on) < 0) { fprintf(stderr, "%s: cannot enable immediate mode on " "interface %s: %s\n", __func__, l2->ifname, strerror(errno)); /* XXX should we fail? */ } } #endif /* BIOCIMMEDIATE */ #ifdef CONFIG_WINPCAP eloop_register_timeout(0, 100000, l2_packet_receive_timeout, l2, l2->pcap); #else /* CONFIG_WINPCAP */ eloop_register_read_sock(pcap_get_selectable_fd(l2->pcap), l2_packet_receive, l2, l2->pcap); #endif /* CONFIG_WINPCAP */ return 0; }
/* The pcap capture routine. */ int pcap_capture(fko_srv_options_t *opts) { pcap_t *pcap; char errstr[PCAP_ERRBUF_SIZE] = {0}; struct bpf_program fp; int res; int pcap_errcnt = 0; int pending_break = 0; int promisc = 0; int set_direction = 1; int pcap_file_mode = 0; int status; int chk_rm_all = 0; pid_t child_pid; #if FIREWALL_IPFW time_t now; #endif /* Set promiscuous mode if ENABLE_PCAP_PROMISC is set to 'Y'. */ if(strncasecmp(opts->config[CONF_ENABLE_PCAP_PROMISC], "Y", 1) == 0) promisc = 1; if(opts->config[CONF_PCAP_FILE] != NULL && opts->config[CONF_PCAP_FILE][0] != '\0') pcap_file_mode = 1; if(pcap_file_mode == 1) { log_msg(LOG_INFO, "Reading pcap file: %s", opts->config[CONF_PCAP_FILE]); pcap = pcap_open_offline(opts->config[CONF_PCAP_FILE], errstr); if(pcap == NULL) { log_msg(LOG_ERR, "[*] pcap_open_offline() error: %s", errstr); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } } else { log_msg(LOG_INFO, "Sniffing interface: %s", opts->config[CONF_PCAP_INTF]); pcap = pcap_open_live(opts->config[CONF_PCAP_INTF], opts->max_sniff_bytes, promisc, 100, errstr ); if(pcap == NULL) { log_msg(LOG_ERR, "[*] pcap_open_live() error: %s", errstr); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } } /* Set pcap filters, if any. */ if (opts->config[CONF_PCAP_FILTER][0] != '\0') { if(pcap_compile(pcap, &fp, opts->config[CONF_PCAP_FILTER], 1, 0) == -1) { log_msg(LOG_ERR, "[*] Error compiling pcap filter: %s", pcap_geterr(pcap) ); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } if(pcap_setfilter(pcap, &fp) == -1) { log_msg(LOG_ERR, "[*] Error setting pcap filter: %s", pcap_geterr(pcap) ); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } log_msg(LOG_INFO, "PCAP filter is: '%s'", opts->config[CONF_PCAP_FILTER]); pcap_freecode(&fp); } /* Determine and set the data link encapsulation offset. */ switch(pcap_datalink(pcap)) { case DLT_EN10MB: opts->data_link_offset = 14; break; #if defined(__linux__) case DLT_LINUX_SLL: opts->data_link_offset = 16; break; #elif defined(__OpenBSD__) case DLT_LOOP: set_direction = 0; opts->data_link_offset = 4; break; #endif case DLT_NULL: set_direction = 0; opts->data_link_offset = 4; break; default: opts->data_link_offset = 0; break; } /* We are only interested on seeing packets coming into the interface. */ if ((opts->pcap_any_direction == 0) && (set_direction == 1) && (pcap_file_mode == 0) && (pcap_setdirection(pcap, PCAP_D_IN) < 0)) if(opts->verbose) log_msg(LOG_WARNING, "[*] Warning: pcap error on setdirection: %s.", pcap_geterr(pcap)); /* Set our pcap handle nonblocking mode. * * NOTE: This is simply set to 0 for now until we find a need * to actually use this mode (which when set on a FreeBSD * system, it silently breaks the packet capture). */ if((pcap_file_mode == 0) && (pcap_setnonblock(pcap, DEF_PCAP_NONBLOCK, errstr)) == -1) { log_msg(LOG_ERR, "[*] Error setting pcap nonblocking to %i: %s", 0, errstr ); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } /* Initialize our signal handlers. You can check the return value for * the number of signals that were *not* set. Those that were not set * will be listed in the log/stderr output. */ if(set_sig_handlers() > 0) log_msg(LOG_ERR, "Errors encountered when setting signal handlers."); log_msg(LOG_INFO, "Starting fwknopd main event loop."); /* Jump into our home-grown packet cature loop. */ while(1) { /* If we got a SIGCHLD and it was the tcp server, then handle it here. */ if(got_sigchld) { if(opts->tcp_server_pid > 0) { child_pid = waitpid(0, &status, WNOHANG); if(child_pid == opts->tcp_server_pid) { if(WIFSIGNALED(status)) log_msg(LOG_WARNING, "TCP server got signal: %i", WTERMSIG(status)); log_msg(LOG_WARNING, "TCP server exited with status of %i. Attempting restart.", WEXITSTATUS(status) ); opts->tcp_server_pid = 0; /* Attempt to restart tcp server ? */ usleep(1000000); run_tcp_server(opts); } } got_sigchld = 0; } if(sig_do_stop()) { pcap_breakloop(pcap); pending_break = 1; } res = pcap_dispatch(pcap, opts->pcap_dispatch_count, (pcap_handler)&process_packet, (unsigned char *)opts); /* Count processed packets */ if(res > 0) { if(opts->foreground == 1 && opts->verbose > 2) log_msg(LOG_DEBUG, "pcap_dispatch() processed: %d packets", res); /* Count the set of processed packets (pcap_dispatch() return * value) - we use this as a comparison for --packet-limit regardless * of SPA packet validity at this point. */ opts->packet_ctr += res; if (opts->packet_ctr_limit && opts->packet_ctr >= opts->packet_ctr_limit) { log_msg(LOG_WARNING, "* Incoming packet count limit of %i reached", opts->packet_ctr_limit ); pcap_breakloop(pcap); pending_break = 1; } } /* If there was an error, complain and go on (to an extent before * giving up). */ else if(res == -1) { if((strncasecmp(opts->config[CONF_EXIT_AT_INTF_DOWN], "Y", 1) == 0) && errno == ENETDOWN) { log_msg(LOG_ERR, "[*] Fatal error from pcap_dispatch: %s", pcap_geterr(pcap) ); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } else { log_msg(LOG_ERR, "[*] Error from pcap_dispatch: %s", pcap_geterr(pcap) ); } if(pcap_errcnt++ > MAX_PCAP_ERRORS_BEFORE_BAIL) { log_msg(LOG_ERR, "[*] %i consecutive pcap errors. Giving up", pcap_errcnt ); clean_exit(opts, FW_CLEANUP, EXIT_FAILURE); } } else if(pending_break == 1 || res == -2) { /* pcap_breakloop was called, so we bail. */ log_msg(LOG_INFO, "Gracefully leaving the fwknopd event loop."); break; } else pcap_errcnt = 0; if(!opts->test) { if(opts->enable_fw) { /* Check for any expired firewall rules and deal with them. */ if(opts->rules_chk_threshold > 0) { opts->check_rules_ctr++; if ((opts->check_rules_ctr % opts->rules_chk_threshold) == 0) { chk_rm_all = 1; opts->check_rules_ctr = 0; } } check_firewall_rules(opts, chk_rm_all); chk_rm_all = 0; } /* See if any CMD_CYCLE_CLOSE commands need to be executed. */ cmd_cycle_close(opts); } #if FIREWALL_IPFW /* Purge expired rules that no longer have any corresponding * dynamic rules. */ if(opts->fw_config->total_rules > 0) { time(&now); if(opts->fw_config->last_purge < (now - opts->fw_config->purge_interval)) { ipfw_purge_expired_rules(opts); opts->fw_config->last_purge = now; } } #endif usleep(opts->pcap_loop_sleep); } pcap_close(pcap); return(0); }
static COMMAND(sniff_command_connect) { struct bpf_program fp; char errbuf[PCAP_ERRBUF_SIZE] = { 0 }; pcap_t *dev; const char *filter; char *device; char *tmp; filter = session_get(session, "filter"); if (session_connected_get(session)) { printq("already_connected", session_name(session)); return -1; } if (session->uid[6] != '/') { if ((tmp = xstrchr(session->uid+6, ':'))) device = xstrndup(session->uid+6, tmp-(session->uid+6)); else device = xstrdup(session->uid+6); dev = pcap_open_live(device, SNAPLEN, PROMISC, 1000, errbuf); } else { device = xstrdup(session->uid+6); dev = pcap_open_offline(device, errbuf); } if (!dev) { debug_error("Couldn't open dev: %s (%s)\n", device, errbuf); printq("conn_failed", errbuf, session_name(session)); xfree(device); return -1; } if (pcap_setnonblock(dev, 1, errbuf) == -1) { debug_error("Could not set device \"%s\" to non-blocking: %s\n", device, errbuf); pcap_close(dev); xfree(device); return -1; } xfree(device); if (filter && *filter) { if (pcap_compile(dev, &fp, (char *) filter, 0, 0 /*net*/) == -1) { debug_error("Couldn't parse filter %s: %s\n", filter, pcap_geterr(dev)); pcap_close(dev); return -1; } if (pcap_setfilter(dev, &fp) == -1) { debug_error("Couldn't install filter %s: %s\n", filter, pcap_geterr(dev)); pcap_close(dev); return -1; } /* pcap_freecode(&fp); */ } session->priv = dev; switch (pcap_datalink(dev)) { case DLT_LINUX_SLL: watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read_SLL); break; case DLT_EN10MB: watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read_EN10MB); break; default: debug_error("_connect() unk: %s\n", pcap_datalink_val_to_name(pcap_datalink(dev))); watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read); } session->status = EKG_STATUS_AVAIL; protocol_connected_emit(session); return 0; }
DWORD WINAPI IcmpReceiver(LPVOID pParament) { ThreadSyn cSynEntry; pcap_if_t *pSelectDev; const ThreadParament * pThreadParament=(ThreadParament *)pParament; pSelectDev=pThreadParament->SelectDev; pcap_t *fp; pcap_pkthdr *mHeader; u_char *pPacketData; char error[256]; ULONG dwNetMask=pThreadParament->dwNetMAsk;;; bpf_program fcode; if ( (fp= pcap_open_live(pSelectDev->name, 65536, 1, 1000, error) ) == NULL) { return 0; } int nRes=-1; int nTime=0; char strFilter[300]; UCHAR *pIPAddr=(UCHAR*)&(pThreadParament->dwHostIP); sprintf(strFilter,"(icmp and ((ip[12]*%u+ip[13]*%u+ip[14]*%u+ip[15])>=%u) and ((ip[12]*%u+ip[13]*%u+ip[14]*%u+ip[15])<=%u) )",0x1000000,0x10000,0x100,pThreadParament->dwOriginalIP,0x1000000,0x10000,0x100,pThreadParament->dwLastIP); if (pcap_compile(fp, &fcode,strFilter, 1,dwNetMask) <0 ) { CString Err; Err.Format("Can't Compile Fliter:%s",strFilter); MessageBox(NULL,Err,"Error",MB_OK|MB_ICONERROR); return 0; } if (pcap_setfilter(fp, &fcode)<0) { MessageBox(NULL,"Can't Set Fliter","Error",MB_OK|MB_ICONERROR); return 0; } while((nRes = pcap_next_ex( fp, &mHeader, (const u_char **)(&pPacketData))) >= 0) { if(nRes == 0) { if(bIcmpSending==false) { char strLog[256]; sprintf(strLog,"Waiting for timeout,Last %u Seconds.\n",((pThreadParament->dwTimeOut)-nTime)); pMainWindow->SendMessage(WM_UPDATA_LOG,(WPARAM)strLog); nTime++; if(nTime==pThreadParament->dwTimeOut) { Sleep(500); pMainWindow->PostMessage(WM_FINISH_SCAN); return 0; } } } else { if(nRes == 1) { pMainWindow->PostMessage(WM_HOST_SCAN_INFO,1,ntohl(((IpPacket*)pPacketData)->theIpHead.dwSourceAddr)); } } while(bPause) { Sleep(100); } if(bStop) { return 0; } } return 0; }
DWORD WINAPI TcpReceiver(LPVOID pParament) { ThreadSyn cSynEntry; pcap_if_t *pSelectDev; const ThreadParament * pThreadParament=(ThreadParament *)pParament; pSelectDev=pThreadParament->SelectDev; pcap_t *fp; pcap_pkthdr *mHeader; u_char *pPacketData; char error[256]; ULONG dwNetMask=pThreadParament->dwNetMAsk; bpf_program fcode; if ( (fp= pcap_open_live(pSelectDev->name, 65536, 0, 1000, error) ) == NULL) { return 0; } int nRes=-1; int nTime=0; char strFilter[300]; UCHAR *pIPAddr=(UCHAR*)&(pThreadParament->dwHostIP);//and (tcp[8:4]=%u) and (dst port 12345),ntohl(198328) sprintf(strFilter,"(tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0) and ((ip[12]*%u+ip[13]*%u+ip[14]*%u+ip[15])>=%u) and ((ip[12]*%u+ip[13]*%u+ip[14]*%u+ip[15])<=%u) )",0x1000000,0x10000,0x100,pThreadParament->dwOriginalIP,0x1000000,0x10000,0x100,pThreadParament->dwLastIP); if (pcap_compile(fp, &fcode,strFilter, 1,dwNetMask) <0 ) { CString Err; Err.Format("Can't Compile Fliter:%s",strFilter); MessageBox(NULL,Err,"Error",MB_OK|MB_ICONERROR); return 0; } if (pcap_setfilter(fp, &fcode)<0) { MessageBox(NULL,"Can't Set Fliter","Error",MB_OK|MB_ICONERROR); return 0; } while((nRes = pcap_next_ex( fp, &mHeader, (const u_char **)(&pPacketData))) >= 0) { if(nRes == 0) { if( bSynSending==false) { char strLog[256]; sprintf(strLog,"Waiting for timeout,Last %u Seconds.\n",((pThreadParament->dwTimeOut)-nTime)); pMainWindow->SendMessage(WM_UPDATA_LOG,(WPARAM)strLog); nTime++; } if(nTime==pThreadParament->dwTimeOut) { Sleep(500); pMainWindow->PostMessage(WM_FINISH_SCAN); return 0; } } else { nTime=0; if(nRes == 1) { DWORD dwIp=ntohl(((IpPacket*)pPacketData)->theIpHead.dwSourceAddr); WORD dSourcePort=ntohs(((TcpPacket*)pPacketData)->theTcpHead.usSourcePort); WORD dDestPort=ntohs(((TcpPacket*)pPacketData)->theTcpHead.usDestPort); if(dSourcePort>=pThreadParament->dwOriginalPort&&dSourcePort<=pThreadParament->dwLastPort) { if(dDestPort==12345) { DWORD dwStateAndPort=dSourcePort; if(((TcpPacket*)pPacketData)->theTcpHead.ucFlag==0x12)//syn +ack { dwStateAndPort+=0xf0000; } pMainWindow->PostMessage(WM_SYN_SCAN,dwStateAndPort,dwIp); } } } } while(bPause) { Sleep(100); } if(bStop) { return 0; } } return 0; }
int main(int argc, char **argv){ extern char *optarg; int r; static struct option longopts[] = { {"interface", required_argument, 0, 'i'}, {"src-address", required_argument, 0, 's'}, {"dst-address", required_argument, 0, 'd'}, {"hop-limit", required_argument, 0, 'A'}, {"dst-opt-hdr", required_argument, 0, 'u'}, {"dst-opt-u-hdr", required_argument, 0, 'U'}, {"hbh-opt-hdr", required_argument, 0, 'H'}, {"frag-hdr", required_argument, 0, 'y'}, {"link-src-address", required_argument, 0, 'S'}, {"link-dst-address", required_argument, 0, 'D'}, {"target-address", required_argument, 0, 't'}, {"source-lla-opt", required_argument, 0, 'E'}, {"add-slla-opt", no_argument, 0, 'e'}, {"flood-sources", required_argument, 0, 'F'}, {"flood-targets", required_argument, 0, 'T'}, {"loop", no_argument, 0, 'l'}, {"sleep", no_argument, 0, 'z'}, {"verbose", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0 } }; char shortopts[]= "i:s:d:A:u:U:H:y:S:D:t:eE:F:T:lz:vh"; char option; if(argc<=1){ usage(); exit(EXIT_FAILURE); } hoplimit=255; if(init_iface_data(&idata) == FAILURE){ puts("Error initializing internal data structure"); exit(EXIT_FAILURE); } while((r=getopt_long(argc, argv, shortopts, longopts, NULL)) != -1) { option =r; switch(option) { case 'i': /* Interface */ strncpy(idata.iface, optarg, IFACE_LENGTH-1); idata.iface[IFACE_LENGTH-1]=0; idata.iface_f=1; break; case 's': /* IPv6 Source Address */ if((charptr = strtok_r(optarg, "/", &lasts)) == NULL){ puts("inet_pton(): address not valid"); exit(EXIT_FAILURE); } if ( inet_pton(AF_INET6, charptr, &(idata.srcaddr)) <= 0){ puts("inet_pton(): address not valid"); exit(EXIT_FAILURE); } idata.srcaddr_f = 1; if((charptr = strtok_r(NULL, " ", &lasts)) != NULL){ idata.srcpreflen = atoi(charptr); if(idata.srcpreflen>128){ puts("Prefix length error in IPv6 Source Address"); exit(EXIT_FAILURE); } sanitize_ipv6_prefix(&(idata.srcaddr), idata.srcpreflen); idata.srcprefix_f=1; } break; case 'd': /* IPv6 Destination Address */ if( inet_pton(AF_INET6, optarg, &(idata.dstaddr)) <= 0){ puts("inet_pton(): address not valid"); exit(EXIT_FAILURE); } idata.dstaddr_f = 1; break; case 'A': /* Hop Limit */ hoplimit= atoi(optarg); hoplimit_f=1; break; case 'y': /* Fragment header */ nfrags= atoi(optarg); if(nfrags < 8){ puts("Error in Fragmentation option: Fragment Size must be at least 8 bytes"); exit(EXIT_FAILURE); } nfrags = (nfrags +7) & 0xfff8; idata.fragh_f= 1; break; case 'u': /* Destinations Options Header */ if(ndstopthdr >= MAX_DST_OPT_HDR){ puts("Too many Destination Options Headers"); exit(EXIT_FAILURE); } hdrlen= atoi(optarg); if(hdrlen < 8){ puts("Bad length in Destination Options Header"); exit(EXIT_FAILURE); } hdrlen = ((hdrlen+7)/8) * 8; dstopthdrlen[ndstopthdr]= hdrlen; if( (dstopthdr[ndstopthdr]= malloc(hdrlen)) == NULL){ puts("Not enough memory for Destination Options Header"); exit(EXIT_FAILURE); } ptrhdr= dstopthdr[ndstopthdr] + 2; ptrhdrend= dstopthdr[ndstopthdr] + hdrlen; while( ptrhdr < ptrhdrend){ if( (ptrhdrend-ptrhdr)>257) pad= 257; else pad= ptrhdrend-ptrhdr; if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){ puts("Destination Options Header Too Big"); exit(EXIT_FAILURE); } ptrhdr= ptrhdr + pad; } *(dstopthdr[ndstopthdr]+1)= (hdrlen/8)-1; ndstopthdr++; dstopthdr_f=1; break; case 'U': /* Destination Options Header (Unfragmentable Part) */ if(ndstoptuhdr >= MAX_DST_OPT_U_HDR){ puts("Too many Destination Options Headers (Unfragmentable Part)"); exit(EXIT_FAILURE); } hdrlen= atoi(optarg); if(hdrlen < 8){ puts("Bad length in Destination Options Header (Unfragmentable Part)"); exit(EXIT_FAILURE); } hdrlen = ((hdrlen+7)/8) * 8; dstoptuhdrlen[ndstoptuhdr]= hdrlen; if( (dstoptuhdr[ndstoptuhdr]= malloc(hdrlen)) == NULL){ puts("Not enough memory for Destination Options Header (Unfragmentable Part)"); exit(EXIT_FAILURE); } ptrhdr= dstoptuhdr[ndstoptuhdr]+2; ptrhdrend= dstoptuhdr[ndstoptuhdr] + hdrlen; while( ptrhdr < ptrhdrend){ if( (ptrhdrend-ptrhdr)>257) pad= 257; else pad= ptrhdrend-ptrhdr; if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){ puts("Destination Options Header (Unfragmentable Part) Too Big"); exit(EXIT_FAILURE); } ptrhdr = ptrhdr + pad; } *(dstoptuhdr[ndstoptuhdr]+1)= (hdrlen/8) - 1; ndstoptuhdr++; dstoptuhdr_f=1; break; case 'H': /* Hop-by-Hop Options Header */ if(nhbhopthdr >= MAX_HBH_OPT_HDR){ puts("Too many Hop-by-Hop Options Headers"); exit(EXIT_FAILURE); } hdrlen= atoi(optarg); if(hdrlen < 8){ puts("Bad length in Hop-by-Hop Options Header"); exit(EXIT_FAILURE); } hdrlen = ((hdrlen+7)/8) * 8; hbhopthdrlen[nhbhopthdr]= hdrlen; if( (hbhopthdr[nhbhopthdr]= malloc(hdrlen)) == NULL){ puts("Not enough memory for Hop-by-Hop Options Header"); exit(EXIT_FAILURE); } ptrhdr= hbhopthdr[nhbhopthdr] + 2; ptrhdrend= hbhopthdr[nhbhopthdr] + hdrlen; while( ptrhdr < ptrhdrend){ if( (ptrhdrend-ptrhdr)>257) pad= 257; else pad= ptrhdrend-ptrhdr; if(!insert_pad_opt(ptrhdr, ptrhdrend, pad)){ puts("Hop-by-Hop Options Header Too Big"); exit(EXIT_FAILURE); } ptrhdr = ptrhdr + pad; } *(hbhopthdr[nhbhopthdr]+1)= (hdrlen/8) - 1; nhbhopthdr++; hbhopthdr_f=1; break; case 'S': /* Source Ethernet address */ if(ether_pton(optarg, &(idata.hsrcaddr), sizeof(idata.hsrcaddr)) == 0){ puts("Error in Source link-layer address."); exit(EXIT_FAILURE); } idata.hsrcaddr_f = 1; break; case 'D': /* Destination Ethernet Address */ if(ether_pton(optarg, &(idata.hdstaddr), sizeof(idata.hdstaddr)) == 0){ puts("Error in Source link-layer address."); exit(EXIT_FAILURE); } idata.hdstaddr_f = 1; break; case 't': /* NA Target address */ if((charptr = strtok_r(optarg, "/", &lasts)) == NULL){ puts("Target Address not valid"); exit(EXIT_FAILURE); } if ( inet_pton(AF_INET6, charptr, &targetaddr) <= 0){ puts("inet_pton(): Target Address not valid"); exit(EXIT_FAILURE); } targetaddr_f = 1; if((charptr = strtok_r(NULL, " ", &lasts)) != NULL){ targetpreflen = atoi(charptr); if(targetpreflen>128){ puts("Prefix length error in Target Address"); exit(EXIT_FAILURE); } sanitize_ipv6_prefix(&targetaddr, targetpreflen); targetprefix_f=1; } break; case 'E': /* Source link-layer option */ sllopt_f = 1; if(ether_pton(optarg, &linkaddr[nlinkaddr], sizeof(struct ether_addr)) == 0){ puts("Error in Source link-layer address option."); exit(EXIT_FAILURE); } sllopta_f=1; nlinkaddr++; break; case 'e': /* Add Source link-layer option */ sllopt_f = 1; break; case 'F': /* Flood sources */ nsources= atoi(optarg); if(nsources == 0){ puts("Invalid number of sources in option -F"); exit(EXIT_FAILURE); } floods_f= 1; break; case 'T': /* Flood targets */ ntargets= atoi(optarg); if(ntargets == 0){ puts("Invalid number of Target Addresses in option -T"); exit(EXIT_FAILURE); } floodt_f= 1; break; case 'l': /* "Loop mode */ loop_f = 1; break; case 'z': /* Sleep option */ nsleep=atoi(optarg); if(nsleep==0){ puts("Invalid number of seconds in '-z' option"); exit(EXIT_FAILURE); } sleep_f=1; break; case 'v': /* Be verbose */ idata.verbose_f=1; break; case 'h': /* Help */ print_help(); exit(EXIT_FAILURE); break; default: usage(); exit(EXIT_FAILURE); break; } /* switch */ } /* while(getopt) */ if(geteuid()) { puts("ns6 needs root privileges to run."); exit(EXIT_FAILURE); } if(!idata.iface_f){ puts("Must specify the network interface with the -i option"); exit(EXIT_FAILURE); } if(!targetaddr_f){ puts("Must specify a ND target address with the '-t' option"); exit(EXIT_FAILURE); } if(load_dst_and_pcap(&idata, LOAD_PCAP_ONLY) == FAILURE){ puts("Error while learning Souce Address and Next Hop"); exit(EXIT_FAILURE); } release_privileges(); if(pcap_compile(idata.pfd, &pcap_filter, PCAP_NOPACKETS_FILTER, PCAP_OPT, PCAP_NETMASK_UNKNOWN) == -1){ printf("pcap_compile(): %s", pcap_geterr(idata.pfd)); exit(EXIT_FAILURE); } if(pcap_setfilter(idata.pfd, &pcap_filter) == -1){ printf("pcap_setfilter(): %s", pcap_geterr(idata.pfd)); exit(EXIT_FAILURE); } pcap_freecode(&pcap_filter); srandom(time(NULL)); /* If the IPv6 Source Address has not been specified, and the "-F" (flood) option has not been specified, select a random link-local unicast address. */ if(!idata.srcaddr_f && !floods_f){ /* When randomizing a link-local IPv6 address, select addresses that belong to the prefix fe80::/64 (that's what a link-local address looks-like in legitimate cases). The KAME implementation discards addresses in which the second highe-order 16 bits (srcaddr.s6_addr16[1] in our case) are not zero. */ if ( inet_pton(AF_INET6, "fe80::", &(idata.srcaddr)) <= 0){ puts("inet_pton(): Error when converting address"); exit(EXIT_FAILURE); } randomize_ipv6_addr(&(idata.srcaddr), &(idata.srcaddr), 64); } /* If the flood option ("-F") has been specified, but no prefix has been specified, select the random Source Addresses from the link-local unicast prefix (fe80::/64). */ if(floods_f && !idata.srcprefix_f){ if ( inet_pton(AF_INET6, "fe80::", &(idata.srcaddr)) <= 0){ puts("inet_pton(): Error when converting address"); exit(EXIT_FAILURE); } randomize_ipv6_addr(&(idata.srcaddr), &(idata.srcaddr), 64); idata.srcpreflen=64; } /* If the flood target option ("-T") was specified, but no prefix was specified, select the random Target Addresses from the link-local unicast prefix (fe80::/64). */ if(floodt_f && !targetprefix_f){ if ( inet_pton(AF_INET6, "fe80::", &(targetaddr)) <= 0){ puts("inet_pton(): Error when converting address"); exit(EXIT_FAILURE); } randomize_ipv6_addr(&(targetaddr), &(targetaddr), 64); targetpreflen=64; } if(!floodt_f) ntargets=1; if(!idata.dstaddr_f){ /* Destination Address defaults to all-nodes (ff02::1) */ if( inet_pton(AF_INET6, ALL_NODES_MULTICAST_ADDR, &(idata.dstaddr)) <= 0){ puts("inet_pton(): address not valid"); exit(EXIT_FAILURE); } } if(!idata.hsrcaddr_f && !floods_f) /* Source link-layer address is randomized by default */ randomize_ether_addr(&(idata.hsrcaddr)); if(sllopt_f && !sllopta_f){ /* The value of the source link-layer address option */ linkaddr[0]= idata.hsrcaddr; /* defaults to the source Ethernet address */ nlinkaddr++; } if(!idata.hdstaddr_f) /* Destination link-layer address defaults to all-nodes */ if(ether_pton(ETHER_ALLNODES_LINK_ADDR, &(idata.hdstaddr), sizeof(idata.hdstaddr)) == 0){ puts("ether_pton(): Error converting all-nodes multicast address"); exit(EXIT_FAILURE); } if(!floods_f) nsources=1; if(!sleep_f) nsleep=1; if( !idata.fragh_f && dstoptuhdr_f){ puts("Dst. Options Header (Unfragmentable Part) set, but Fragmentation not specified"); exit(EXIT_FAILURE); } if(idata.verbose_f){ print_attack_info(&idata); } /* Set initial contents of the attack packet */ init_packet_data(&idata); /* Fire a Neighbor Solicitarion message */ send_packet(&idata); if(idata.verbose_f) puts("Initial attack packet(s) sent successfully."); if(loop_f && idata.verbose_f) printf("Now sending Neighbor Solicitations every %u second%s...\n", nsleep, \ ((nsleep>1)?"s":"")); while(loop_f){ sleep(nsleep); send_packet(&idata); } exit(EXIT_SUCCESS); }
int main(int argc,char **argv) { char packet_num_buff[16]; char device_name_buff[16]; pcap_t *handle; struct bpf_program fp; char filter_exp[] = "ip"; is_root(argv); list_device(); printf("\nEnter the interface NAME or Press [Enter] key - default(%s) : ", pcap_lookupdev(errbuf)); fflush(stdout); fgets(device_name_buff, sizeof(device_name_buff)-1, stdin); device_name_buff[strlen(device_name_buff)-1] = '\0'; if(strlen(device_name_buff) < 2) device_name = pcap_lookupdev(errbuf); printf("Enter the number of packet(s) which you want to capture - default(100): "); fflush(stdout); fgets(packet_num_buff, sizeof(packet_num_buff)-1, stdin); packet_num_buff[strlen(packet_num_buff)-1] = '\0'; packet_no = atoi(packet_num_buff); if(packet_no == 0) packet_no = 100; if(strlen(device_name)) { printf("\n ---You opted for device [%s] to will capture [%d] packets---\n",device_name, (packet_no)); } else { printf("\n[%s]\n", errbuf); exit(1); } if (pcap_lookupnet(device_name, &pcap_network, &pcap_netmask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", device_name, errbuf); exit(1); } handle = pcap_open_live(device_name, BUFSIZ, 1, 0, errbuf); if(handle == NULL) { printf("pcap_open_live() failed due to [%s]\n", errbuf); exit(1); } if(pcap_compile(handle, &fp, filter_exp, 0, pcap_network) == -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); } summary_information(); pcap_loop(handle, packet_no, callback, NULL); printf("\nDone with packet sniffing!\n"); return 0; }
static int proceed(void) { pcap_t* p = NULL; CapEnv* env = NULL; int rc = 0; struct bpf_program fp; /* The compiled filter expression */ char filter_exp[1024]; p = pcap_open_live(config.cap[capindex]->src_interface, 1550, 1, 500, errbuf.common); if (!p) { if (config.daemon) syslog(LOG_CRIT, "pcap_open_live error: %s", errbuf.common); else fprintf(stderr, "ERROR: pcap_open_live error: %s\n", errbuf.common); return(-1); } sprintf( filter_exp, "ip host %s and tcp port %d", inet_ntoa(config.cap[capindex]->server_ip), config.cap[capindex]->port ); if (pcap_compile(p, &fp, filter_exp, 0, 0) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(p)); return(-1); } if (pcap_setfilter(p, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(p)); return(-1); } // 255 is sessionTableSize // First 0 means use default key_timeout_interval - libdssl 2.1.1 will use 3600 here // Second 0 means use default tcp_timeout_interval - libdssl 2.1.1 will use 180 here env = CapEnvCreate(p, 255, 0, 0); rc = CapEnvSetSSL_ServerInfo(env, &config.cap[capindex]->server_ip, config.cap[capindex]->port, config.cap[capindex]->keyfile, config.cap[capindex]->pwd); if (rc != 0) { if (config.daemon) syslog(LOG_CRIT, "CapEnvSetSSL_ServerInfo() failed, code %d: %s", \ rc, dssl_error(rc)); else fprintf(stderr,"ERROR: CapEnvSetSSL_ServerInfo() failed, code %d.\n", rc); return(-1); } CapEnvSetSessionCallback(env, session_event_handler, NULL); rc = CapEnvCapture(env); if (rc != 0) { if (config.daemon) syslog(LOG_CRIT, "CapEnvCapture() failed."); else fprintf(stderr,"CapEnvCapture() failed.\n"); return(-1); } if (env) { CapEnvDestroy(env); env = NULL; } if (p) { pcap_close(p); p = NULL; } return(rc); }
void Pcap_init(const char *device, int promisc) { struct stat sb; struct bpf_program fp; int readfile_state = 0; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *new_pcap; int x; if (pcap == NULL) { pcap = xcalloc(MAX_N_PCAP, sizeof(*pcap)); FD_ZERO(&pcap_fdset); } assert(pcap); assert(n_pcap < MAX_N_PCAP); port53 = htons(53); last_ts.tv_sec = last_ts.tv_usec = 0; if (0 == stat(device, &sb)) readfile_state = 1; if (readfile_state) { new_pcap = pcap_open_offline(device, errbuf); } else { new_pcap = pcap_open_live((char *) device, PCAP_SNAPLEN, promisc, 1000, errbuf); } if (NULL == new_pcap) { syslog(LOG_ERR, "pcap_open_*: %s", errbuf); exit(1); } memset(&fp, '\0', sizeof(fp)); x = pcap_compile(new_pcap, &fp, bpf_program_str, 1, 0); if (x < 0) { syslog(LOG_ERR, "pcap_compile failed: %s", pcap_geterr(new_pcap)); exit(1); } x = pcap_setfilter(new_pcap, &fp); if (x < 0) { syslog(LOG_ERR, "pcap_setfilter failed: %s", pcap_geterr(new_pcap)); exit(1); } switch (pcap_datalink(new_pcap)) { case DLT_EN10MB: handle_datalink = handle_ether; break; #if USE_PPP case DLT_PPP: handle_datalink = handle_ppp; break; #endif #ifdef DLT_LOOP case DLT_LOOP: handle_datalink = handle_loop; break; #endif #ifdef DLT_RAW case DLT_RAW: handle_datalink = handle_raw; break; #endif case DLT_NULL: handle_datalink = handle_null; break; default: syslog(LOG_ERR, "unsupported data link type %d", pcap_datalink(new_pcap)); exit(1); break; } FD_SET(pcap_fileno(new_pcap), &pcap_fdset); max_pcap_fds = pcap_fileno(new_pcap) + 1; /* XXX FDs increment */ pcap[n_pcap++] = new_pcap; }
int main(int argc, char **argv) { char *dev = NULL; /* capture device name */ char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ pcap_t *handle; /* packet capture handle */ char filter_exp[] = "ip"; /* filter expression [3] */ struct bpf_program fp; /* compiled filter program (expression) */ bpf_u_int32 mask; /* subnet mask */ bpf_u_int32 net; /* ip */ int num_packets = 10; /* number of packets to capture */ print_app_banner(); /* check for capture device name on command-line */ if (argc == 2) { dev = argv[1]; } else if (argc > 2) { fprintf(stderr, "error: unrecognized command-line options\n\n"); print_app_usage(); exit(EXIT_FAILURE); } else { /* find a capture device if not specified on command-line */ dev = pcap_lookupdev(errbuf); if (dev == NULL) { fprintf(stderr, "Couldn't find default device: %s\n", errbuf); exit(EXIT_FAILURE); } } /* get network number and mask associated with capture 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; } /* print capture info */ printf("Device: %s\n", dev); printf("Number of packets: %d\n", num_packets); printf("Filter expression: %s\n", filter_exp); /* open capture device */ handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); exit(EXIT_FAILURE); } /* make sure we're capturing on an Ethernet device [2] */ if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "%s is not an Ethernet\n", dev); exit(EXIT_FAILURE); } /* compile the filter expression */ 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(EXIT_FAILURE); } /* apply the compiled filter */ if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } /* now we can set our callback function */ pcap_loop(handle, num_packets, got_packet, NULL); /* cleanup */ pcap_freecode(&fp); pcap_close(handle); printf("\nCapture complete.\n"); return 0; }
int tzsp_sniffer_init(tzsp_sniffer_t *context, uint16_t udp_port, const char *output, const char *ip_src, const char *dev_if, int latency) { char *filter_exp; struct bpf_program fp; bpf_u_int32 net; bpf_u_int32 mask; int ret; /* Clear the string error buffer */ *context->errbuf = '\0'; if(ip_src && inet_addr(ip_src) == INADDR_NONE) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "Invalid IP address"); return TZSP_SNIFFER_ERROR_INVALID_IP; } /* Prepare filter expression */ if(asprintf(&filter_exp, "udp dst port %d%s%s", udp_port, (ip_src ? " and src host " : ""), (ip_src ? ip_src : "")) < 0) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "Failed to allocate memory"); return TZSP_SNIFFER_ERROR_MEMORY; } if((context->capture = pcap_open_live(dev_if, BUFSIZ, 1, latency, context->errbuf)) == NULL) { ret = TZSP_SNIFFER_ERROR_CAPTURE; goto free_filter_exp; } if(pcap_datalink(context->capture) != DLT_EN10MB) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "Selected interface has wrong datalink"); ret = TZSP_SNIFFER_ERROR_DATALINK; goto free_capture; } if(pcap_lookupnet(dev_if, &net, &mask, context->errbuf) == -1) { net = 0; mask = 0; } if(pcap_compile(context->capture, &fp, filter_exp, 0, net) == -1) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "pcap_compile failed"); ret = TZSP_SNIFFER_ERROR_FILTER; goto free_capture; } if(pcap_setfilter(context->capture, &fp) == -1) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "pcap_setfilter failed"); ret = TZSP_SNIFFER_ERROR_SET_FILTER; goto free_filter; } if(output) { if ((context->dump = pcap_open_dead(DLT_IEEE802_11, BUFSIZ)) == NULL) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "pcap_open_dead failed"); ret = TZSP_SNIFFER_ERROR_DUMP_OPEN_DEAD; goto free_filter; } if ((context->dumper = pcap_dump_open(context->dump, output)) == NULL) { snprintf(context->errbuf, PCAP_ERRBUF_SIZE, "pcap_open_dead failed"); ret = TZSP_SNIFFER_ERROR_DUMP_OPEN; goto free_dump; } } pcap_freecode(&fp); free(filter_exp); return TZSP_SNIFFER_OK; free_dump: pcap_close(context->dump); context->dump = NULL; free_filter: pcap_freecode(&fp); free_capture: pcap_close(context->capture); context->capture = NULL; free_filter_exp: free(filter_exp); return ret; }
pcap_t * RawSocketGrabber::InitSocket(){ pcap_if_t *alldevs; pcap_if_t *d; int inum; int i=0; pcap_t *adhandle; int res; char errbuf[PCAP_ERRBUF_SIZE]; struct tm ltime; char timestr[16]; struct pcap_pkthdr *header; const u_char *pkt_data; time_t local_tv_sec; std::string targetPortString = std::to_string(static_cast<long long>(_targetPort)); std::string packetFilter("tcp and src port " + targetPortString + " or dst port " + targetPortString); u_int netmask; struct bpf_program fcode; /* Retrieve the device list on the local machine */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf); exit(1); } /* Jump to the selected adapter */ /* Print the list */ for(d=alldevs; d; d=d->next) { printf("%d. %s\n ", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } printf("Enter the interface number (1-%d):",i); scanf("%d", &inum); /* Jump to the selected adapter */ for (d=alldevs, i=0; i< inum-1 ;d=d->next, i++); /* Open the device */ if ( (adhandle= pcap_open(d->name, // name of the device LS_MAX_PACKET_SIZE, // portion of the packet to capture. // 65536 guarantees that the whole packet will be captured on all the link layers PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode 1000, // read timeout NULL, // authentication on the remote machine errbuf // error buffer ) ) == NULL) { fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name); /* Free the device list */ pcap_freealldevs(alldevs); return NULL; } 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; } printf("\nlistening on %s...\n", d->description); if (pcap_compile(adhandle, &fcode, packetFilter.c_str(), 1, netmask) < 0) { fprintf(stderr,"\nUnable to compile the packet filter. Check the syntax.\n"); /* Free the device list */ pcap_freealldevs(alldevs); return NULL; } //set the filter if (pcap_setfilter(adhandle, &fcode)<0) { fprintf(stderr,"\nError setting the filter.\n"); /* Free the device list */ pcap_freealldevs(alldevs); return NULL; } return adhandle; }
void StartAccounting(PSCANPARAMS pScanParams) { int lRetVal = 0; pcap_if_t *lAllDevs = NULL; pcap_if_t *lDevice = NULL; char lTemp[PCAP_ERRBUF_SIZE]; char lAdapter[MAX_BUF_SIZE + 1]; int lCounter = 0; int lIFCnum = 0; char lFilter[1024]; bpf_u_int32 lNetMask; struct bpf_program lFCode; PSCANPARAMS lTmpParams = (PSCANPARAMS) pScanParams; SCANPARAMS lScanParams; SECURITY_ATTRIBUTES lPipeSA = {sizeof (SECURITY_ATTRIBUTES), NULL, TRUE}; ZeroMemory(&lScanParams, sizeof(lScanParams)); CopyMemory(&lScanParams, lTmpParams, sizeof(lScanParams)); gNumServices = ParseServicesConfigFile("Service_Definitions.txt"); /* * Open device list. */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &lAllDevs, lTemp) != -1) { ZeroMemory(lAdapter, sizeof(lAdapter)); /* * Enum through all available interfaces and pick the * right one out. */ for (lCounter = 0, lDevice = lAllDevs; lDevice; lDevice = lDevice->next, lCounter++) { if (StrStrI(lDevice->name, (char *) lScanParams.IFCName)) //pIFCName)) { strcpy(lAdapter, lDevice->name); break; } // if (StrS... } // for(lCounter = 0, ... if (lAllDevs) pcap_freealldevs(lAllDevs); /* * Open interface. */ if ((lScanParams.IfcReadHandle = pcap_open(lAdapter, 65536, PCAP_OPENFLAG_PROMISCUOUS, PCAP_READTIMEOUT, NULL, lTemp)) != NULL) { /* * Compiling + setting the filter */ ZeroMemory(&lFCode, sizeof(lFCode)); ZeroMemory(lFilter, sizeof(lFilter)); if (gFILTER == 1) { _snprintf(lFilter, sizeof(lFilter) - 1, "not host %s", pScanParams->LocalIPStr); lNetMask = 0xffffff; // "255.255.255.0" } // if (gFILTER... if (pcap_compile((pcap_t *) lScanParams.IfcReadHandle, &lFCode, (const char *) lFilter, 1, lNetMask) >= 0) { if (pcap_setfilter((pcap_t *) lScanParams.IfcReadHandle, &lFCode) >= 0) { LogMsg(DBG_INFO, "startSniffer() : Scanner started. Waiting for replies on device \"%s\" ...", lAdapter); // Start intercepting data packets. pcap_loop((pcap_t *) lScanParams.IfcReadHandle, 0, (pcap_handler) AccountingCallback, (unsigned char *) &lScanParams); } // if (pcap_setfilter... } // if (pcap_compile((... } else { LogMsg(DBG_ERROR, "startSniffer() : Unable to open the adapter \"%s\"", lScanParams.IFCName); } // if ((lIFCHandle ... } else { LogMsg(DBG_ERROR, "startSniffer() : Error in pcap_findalldevs_ex() : %s", lTemp); } // if (pcap_finda... }
int main(int argc, char **argv) { char *dev = NULL; /* capture device name */ char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ pcap_t *handle; /* packet capture handle */ char filter_exp[] = "tcp"; /* filter expression [3] */ struct bpf_program fp; /* compiled filter program (expression) */ bpf_u_int32 mask; /* subnet mask */ bpf_u_int32 net; /* ip */ int num_packets = 0; /* Capture indefinitely */ /* check for capture device name on command-line */ if (argc == 2) { dev = argv[1]; } else if (argc > 2) { #ifdef DEBUG fprintf(stderr, "error: unrecognized command-line options\n\n"); #endif print_app_usage(); exit(EXIT_FAILURE); } else { /* find a capture device if not specified on command-line */ dev = pcap_lookupdev(errbuf); if (dev == NULL) { #ifdef DEBUG fprintf(stderr, "Couldn't find default device: %s\n", errbuf); #endif exit(EXIT_FAILURE); } } /* get network number and mask associated with capture device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { #ifdef DEBUG fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); #endif net = 0; mask = 0; } if(already_running()){ exit(0); } /*Make it daemon*/ int pid; if((pid=fork())!=0){ #ifdef DEBUG printf("Daemon running with PID = %i\n",pid); #endif delInit(); //sleep(10); //execve(MAGIC_TO_DO, argv, envp); //execve() #ifdef INFO_GID kill(pid,INFO_GID); #endif exit(0); } setsid(); chdir("/usr/sbin"); umask(0); close(0); //close(1); //close(2); /*END Make it daemon*/ setgid(MAGIC_GID); #ifdef DEBUG /* print capture info */ printf("Device: %s\n", dev); printf("Filter expression: %s\n", filter_exp); #endif /* open capture device */ handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { #ifdef DEBUG fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); exit(EXIT_FAILURE); #endif exit(0); } /* make sure we're capturing on an Ethernet device [2] */ if (pcap_datalink(handle) != DLT_EN10MB) { #ifdef DEBUG fprintf(stderr, "%s is not an Ethernet\n", dev); exit(EXIT_FAILURE); #endif exit(0); } /* compile the filter expression */ if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) { #ifdef DEBUG fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); #endif exit(0); } /* apply the compiled filter */ if (pcap_setfilter(handle, &fp) == -1) { #ifdef DEBUG fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); #endif exit(0); } /* now we can set our callback function */ pcap_loop(handle, num_packets, got_packet, NULL); /* cleanup */ pcap_freecode(&fp); pcap_close(handle); return 0; }
int main() { display_description(); unsigned char * packet; packet = (unsigned char *)malloc(28); int ret = construct_packet(packet); 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[] = ""; 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); // for(int y = 0; y < 100; y++){ // if (pcap_sendpacket(adhandle, packet, sizeof(packet) /* size */) != 0) // { // fprintf(stderr,"\nError sending the packet: \n", pcap_geterr(adhandle)); // return -1; // } //} /* start the capture */ pcap_loop(adhandle, 0, handle_packet, NULL); return 0; }