ipband-0.8.1/0000755000000000000000000000000011025771407011457 5ustar rootrootipband-0.8.1/error.c0000744000000000000000000000266211025771407012763 0ustar rootroot/* error.c error handling routines from Richard Stevens */ #include "ipband.h" static void err_doit(int, const char *, va_list); /* Nonfatal error related to a system call. * Print a message and return. */ void err_ret(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(1, fmt, ap); va_end(ap); return; } /* Fatal error related to a system call. * Print a message and terminate. */ void err_sys(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(1, fmt, ap); va_end(ap); exit(1); } /* Nonfatal error unrelated to a system call. * Print a message and return. */ void err_msg(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(0, fmt, ap); va_end(ap); return; } /* Fatal error unrelated to a system call. * Print a message and terminate. */ void err_quit(const char *fmt, ...) { va_list ap; va_start(ap, fmt); err_doit(0, fmt, ap); va_end(ap); exit(1); } /* Print a message and return to caller. * Caller specifies "errnoflag". */ static void err_doit(int errnoflag, const char *fmt, va_list ap) { int errno_save; char buf[MAXLINE]; errno_save = errno; /* value caller might want printed */ vsprintf(buf, fmt, ap); if (errnoflag) sprintf(buf+strlen(buf), ": %s", strerror(errno_save)); strcat(buf, "\n"); fflush(stdout); /* in case stdout and stderr are the same */ fputs(buf, stderr); fflush(NULL); /* flushes all stdio output streams */ return; } ipband-0.8.1/init.c0000744000000000000000000003624411025771407012600 0ustar rootroot/* init.c initialization routines * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" void print_usage(void) { printf("\nUsage: ipband [OPTIONS] interface\n"); printf(" -a - Averaging period in seconds. "); printf( "Default is 60.\n"); printf(" -A - Include accumulated threshold exceeded time\n"); printf(" since ipband start in the report.\n"); printf(" -b kBps - Default bandwidth threshold in kBytes.\n"); printf(" per sec. Default is 7 kBps i.e 56 kbps.\n"); printf(" -c filename - Read configuration file. Default is "); printf( "/etc/ipaband.conf.\n"); printf(" -C - Ignore configuration file\n"); printf(" -d level - Debug level: 0 - no debuging; 1 - summary;\n"); printf(" 2 - subnet stats; 3 - all packets captured.\n"); printf(" -f filterstr - Use pcap filters (see tcpdump).\n"); printf(" -F - Fork and run in background.\n"); printf(" -h - Print this help.\n"); printf(" -J number - Packet length adjustment in bytes.\n"); printf(" -l filename - E-mail report footer file.\n"); printf(" -L ip-range - Range of local ip addresses.\n"); printf(" -m maskbuts - Set number of network mask bits (1-32)\n"); printf(" for subnet traffic aggregation.\n"); printf(" Default is 24 (255.255.255.0).\n"); printf(" -M email addr - Mail report to given addresses.\n"); printf(" -o filename - Subnet report output file. Default is\n"); printf(" ipband.txt in current directory.\n"); printf(" -w filename - HTML report output file. Default is\n"); printf(" ipband.html in current directory.\n"); printf(" -P - Don't use promiscuous mode on network interface.\n"); printf(" -r - Reporting period - number of seconds\n"); printf(" banwidth threshold may be exceeded before\n"); printf(" it should be reported. Default is 300.\n"); printf(" -t number - Limit report to a given number of connections\n"); printf(" with highest byte count. Default is no limit.\n"); printf(" -T string - MTA command string for mailing reports. Default is\n"); printf(" \"/usr/sbin/sendmail -t -oi\".\n"); printf(" -v - Print version and exit.\n"); printf("\nExample:\n"); printf(" ipband eth0 -f \"net 10.10.0.0/16\" -m 24 -a 300 -r 900\n"); printf("\tWill capture packets from/to ip addresses matching\n"); printf("\t10.10.0.0/255.255.0.0, tally traffic by the third octet,\n"); printf("\tcalculate bandwidth utilization every 5 minutes and report\n"); printf("\tper host traffic every 15 minutes.\n\n"); } /* Read options from command line */ void read_options (int argc, char *argv[]) { int optchar; while(-1 != (optchar=getopt(argc,argv,"a:Ab:c:Cd:Ff:hJ:l:L:m:M:o:w:Pr:t:T:v"))) { switch (optchar) { case '?': exit(1); /* Get averaging period in seconds */ case 'a': cycle_m = atoi(optarg); break; /* Include total exceed time in the report */ case 'A' : report_aggr_m = TRUE; break; /* Bandwidth threshold in kBps */ case 'b': thresh_m = (float) atof(optarg); break; /* Read config file */ case 'c': set_defaults(); config_m = strdup(optarg); read_config(config_m); break; /* Ignore config file */ case 'C' : set_defaults(); break; /* Debugging option */ case 'd': debug_m = atoi(optarg); break; /* Do we fork? */ case 'F': fork_m = TRUE; break; /* Get pcap filter string */ case 'f': filtercmd_m = strdup (optarg); break; /* Print help */ case 'h': print_usage(); exit(0); break; /* Frame length adjustment */ case 'J': lenadj_m = atoi(optarg); break; /* Get number of subnet mask bits */ case 'm': mask_m = atoi(optarg); break; /* Get e-mail footer file name */ case 'l': mailfoot_m = strdup (optarg); break; /* Get range of local networks */ case 'L': parse_ip_range (optarg, &iplist_m, &niplist_m); break; /* Get address to mail reports to */ case 'M': mailto_m = strdup (optarg); break; /* Output file name */ case 'o': repfname_m = strdup(optarg); break; /* HTML file name */ case 'w': htmlfname_m = strdup(optarg); do_html = TRUE; break; /* Don't use promiscuous mode */ case 'P': promisc_m = FALSE; break; /* Get reporting period in seconds */ case 'r': rcycle_m = atoi(optarg); break; /* Top traffic */ case 't': top_m = atoi(optarg); break; /* MTA command string */ case 'T': mtastring_m = strdup(optarg); break; /* Print version */ case 'v': printf ("%s (compiled %s)\n", VERSION_STR, __DATE__); printf ("libpcap version %s\n", pcap_version); exit(0); default: exit(1); } } } /* Print options in use for debug purposes */ void dump_options () { printf("\n%s (compiled %s)\n", VERSION_STR, __DATE__); printf("libpcap version %s\n", pcap_version); printf("started %s",ctime(&started_m)); printf("\nOption values:\n"); printf("\tDebug level: %d\n",debug_m); printf("\tPromiscuous mode: %s\n",promisc_m?"yes":"no"); printf("\tConfiguration file: %s\n",config_m); printf("\tAveraging period (sec): %d\n",cycle_m); printf("\tReporting peroid (sec): %d\n",rcycle_m); printf("\tBandwidth threshold (kBps): %g\n",thresh_m); printf("\tPcap filter string: %s\n",filtercmd_m); printf("\tSubnet mask bits: %d\n",mask_m); printf("\tReport output file: %s\n",repfname_m?repfname_m:"ipband.txt"); printf("\tHTML output file: %s\n",htmlfname_m?htmlfname_m:"ipband.html"); printf("\tReport mail to: %s\n",mailto_m); printf("\tReport mail footer file: %s\n",mailfoot_m); printf("\tMTA string: %s\n",mtastring_m); printf("\tReport top connections: %d\n",top_m); printf("\tFrame length adjustment: %d\n",lenadj_m); printf("\n"); /* Print local network ranges */ if(iplist_m) { int i; static char buf1[20], buf2[20]; printf ("Local IP range:\n"); for (i=0;i ", cursig); err_msg("on %s",ctime(&seconds)); } /* Explain why pipe broke */ if (cursig == SIGPIPE) err_msg("SIGPIPE is received when writing to %s\n",mtastring_m); } /* Parse config file */ int read_config (char *filename) { FILE *fin = NULL; char buffer[512]; char *str; char *key, *val; fin = fopen (filename, "r"); if (NULL==fin) return errno; while ( (str=fgets(buffer, 512, fin)) ) { get_two_tok(str, &key, &val); /* Test for comment or empty line */ if (*key=='#' || *key=='\0') continue; /* Test for valid options */ if (!strcmpi("debug",key)) { debug_m = atoi(val); } else if (!strcmpi("filter",key)) { filtercmd_m = strdup(val); } else if (!strcmpi("fork",key)) { fork_m = is_true_str(val); } else if (!strcmpi("outfile",key)) { repfname_m = strdup(val); } else if (!strcmpi("htmlfile",key)) { htmlfname_m = strdup(val); do_html = TRUE; } else if (!strcmpi("htmltitle",key)) { htmltitle_m = strdup(val); } else if (!strcmpi("interface",key)) { pcapdev_m = strdup(val); } else if (!strcmpi("promisc",key)) { promisc_m = is_true_str(val); } else if (!strcmpi("average",key)) { cycle_m = atoi(val); } else if (!strcmpi("bandwidth",key)) { thresh_m = (float) atof(val); } else if (!strcmpi("accumulate",key)) { report_aggr_m = is_true_str(val); } else if (!strcmpi("report",key)) { rcycle_m = atoi(val); } else if (!strcmpi("localrange",key)) { parse_ip_range (val, &iplist_m, &niplist_m); } else if (!strcmpi("mailto",key)) { mailto_m = strdup(val); } else if (!strcmpi("mailfoot",key)) { mailfoot_m = strdup(val); } else if (!strcmpi("mtastring",key)) { mtastring_m = strdup(val); /* Strip double-quotes that might be in the config file */ if( *mtastring_m == '\"' && mtastring_m[strlen(mtastring_m)-1] == '\"' ){ mtastring_m++; mtastring_m[strlen(mtastring_m)-1] = '\0'; } } else if (!strcmpi("maskbits",key)) { mask_m = atoi(val); } else if (!strcmpi("top",key)) { top_m = atoi(val); } else if (!strcmpi("lenadj",key)) { lenadj_m = atoi(val); } else if (!strcmpi("subnet",key)) { /* Set preload flag - we are now limited to specified nets Will process option(s) later when subnet mask is known for sure */ preload_m = TRUE; } else { err_msg("ipband: Error reading ipband config file. "); err_msg(" Unrecognized option: \"%s\"", key); } /* End of test for options */ } /* End of while () looping through config file */ fclose(fin); return 1; } /* Process subnet options in config file */ int parse_subnets (char *filename, hlist_t **ha) { FILE *fin = NULL; char *str; char *key, *val; char buff[512]; fin = fopen (filename, "r"); if (NULL==fin) return errno; while ( (str=fgets(buff, 512, fin)) ) { get_two_tok(str, &key, &val); /* Find subnet options and load it into hash table */ if (!strcmpi("subnet",key)) preload_subnets(val,ha); } fclose(fin); return 1; } /* Build hash table for subnets to be monitored */ void preload_subnets(char *str, hlist_t **ha){ U_CHAR key[9]; /* Subnet key as hex string */ aggr_data_t *data, idata; int datasize, keysize; int ndata; float bwidth = 0.0; int p[4]; int netip = 0; char *buf = (char *) malloc(strlen(str)+1); int i; /* Break subnet option string into ip/bandwidth */ if (6 != sscanf(str,"%d.%d.%d.%d%s%f",&p[0],&p[1],&p[2],&p[3], buf,&bwidth) ) { err_msg("ipband: Error parsing subnet option in config file: %s\n",str); free(buf); return; } free(buf); /* Convert network address to integer */ for(i=0; i<4; i++){ netip = netip<<8; netip |= p[i]; } /* Apply mask */ netip &= mask_m; sprintf(key,"%08x",netip); /* Set bandwidth threshold for this net */ idata.band = bwidth; /* Initialize all other fields */ idata.nbyte = 0; idata.logtime = (time_t) 0; idata.exc_time = 0; idata.exc_accum = 0; /* Set size of data structures */ datasize = sizeof(aggr_data_t); keysize = sizeof(key); /* Add first instance to table */ if(!hash_finddata(ha,(U_CHAR *)&key,keysize,(U_CHAR **)&data,&ndata)){ datasize = sizeof(idata); hash_addnode(ha,(U_CHAR *)&key,keysize,(U_CHAR *)&idata,datasize); /* Key already present, update bandwidth */ } else { data->band = bwidth; } } /* Set all options to default values */ void set_defaults(void) { debug_m = FALSE; preload_m = FALSE; report_aggr_m = FALSE; do_html = FALSE; isig_m = 0; pcapoffset_m = 0; started_m = (time_t) 0; mask_m = 24; cycle_m = 60; rcycle_m = 300; thresh_m = 7.0; fork_m = FALSE; top_m = 0; promisc_m = TRUE; niplist_m = 0; lenadj_m = 0; /* These were malloc'ed by strdup and can be freed */ FREE(config_m); FREE(pcapdev_m); FREE(pcapfile_m); FREE(filtercmd_m); FREE(repfname_m); FREE(htmlfname_m); FREE(htmltitle_m); FREE(mailto_m); FREE(mailfoot_m); FREE(iplist_m); /* Reset MTA string to the default */ FREE(mtastring_m); mtastring_m = strdup(MTASTR_DEF); } /* Get list of local networks */ void parse_ip_range (char *arg_in, int **iplist, int *niplist) { char *arg_cpy = (char *) malloc (strlen(arg_in)+1); char *ipstr = (char *) malloc (strlen(arg_in)+1); char *netstr = (char *) malloc (strlen(arg_in)+1); char *range1 = NULL; char *range2 = NULL; int mask; int net; int ip1, ip2; int n; char *p; *iplist = NULL; /* Count number of ranges (equals number of : + 1 ) */ p = arg_in; n = 1; while (*p++) { if (*p==':') n++; } /* allocate storage */ *iplist = (int *) malloc (2 * n * sizeof(int)); if (*iplist==NULL) { *niplist = 0; return; } strcpy (arg_cpy, arg_in); range2 = arg_cpy; /* break string into separate ranges */ *niplist = 0; while (NULL!=range2) { /* Break arg into (1st range):(remaining ranges) */ range1 = range2; range2 = strchr(range1, ':'); if (NULL!=range2) *range2++ = '\0'; /* Look for range expressed as (lo ip)-(hi ip) */ if (2==sscanf (range1, "%[0-9.]-%[0-9.]", ipstr, netstr)) { str2ip(ipstr, &ip1, &mask); str2ip(netstr, &ip2, &mask); /* break range into (ip)/(net) */ } else if (2==sscanf (range1, "%[0-9.]/%[0-9]", ipstr, netstr)) { /* read ip address */ str2ip (ipstr, &ip1, &mask); net = atoi(netstr); if (net<0) net=0; else if (net>32) net=32; mask = 0xffffffff >> net; if (mask==-1) mask = 0; ip2 = ip1 | mask; /* Look for single ip address */ } else if (sscanf (range1, "%[0-9.].%[0-9].", ipstr, netstr)) { str2ip (ipstr, &ip1, &mask); ip2 = ip1 | mask; /* Bad input format */ } else { err_msg("ERROR: Cannot read network range argument (-l option).\n"); err_msg(" Program continues with using default network range.\n"); *niplist = 0; if (NULL!=*iplist) free (*iplist); return; } /* Store results */ (*iplist)[(*niplist)++] = ip1; (*iplist)[(*niplist)++] = ip2; } free (netstr); free (ipstr); free (arg_cpy); /* Correct double counting of niplist */ *niplist /= 2; } /* Determine if ip addresse is within one of the ranges in iplist */ int in_iprange (int ip, int *iplist, int niplist) { int i; for (i=0;i<2*niplist;i+=2) if (ip>=iplist[i] && ip<=iplist[i+1]) return 1; return 0; } /* Check option values seem reasonable */ void check_invalues () { if( cycle_m < 1 ) err_quit("ERROR: Averaging period must be positive integer\n"); if( thresh_m < 0.0 ) err_quit("ERROR: Negative banwidth threshold\n"); if( (mask_m < 0) || (mask_m > 32)) err_quit("ERROR: invalid number of mask bits\n"); if( rcycle_m < cycle_m ) err_quit("ERROR: reporting period cannot be less then averaging period\n"); if( (top_m < 0) ) err_quit("ERROR: negative per-host connection report limit\n"); } ipband-0.8.1/packets.c0000744000000000000000000002641111025771407013262 0ustar rootroot/* packets.c routines for packets processing * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" /* Store packet info in aggregate hash table, keyed by subnet Store packet info in detail table if subnet is being logged */ void storepkt (struct pcap_pkthdr *pkthdr, ip_struct_t *ip, hlist_t **ha, hlist_t **ha_d) { U_CHAR key_src[9]; /* src subnet as hex string */ U_CHAR key_dst[9]; /* dst subnet as hex string */ U_CHAR key[13]; /* detail logging key */ aggr_data_t *data, idata; data_t *data_d, idata_d; int ndata, ndata_d; int datasize, datasize_d; int keysize, keysize_d; int ip_src, ip_dst; int length; int i; int detail_flag = FALSE; /* Calculate data packet length */ length = pkthdr->len + lenadj_m; /* Get ip src and dst ip address and convert to integers */ ip_src = ip_dst = 0; for(i=0; i<4; i++){ ip_src = ip_src<<8; ip_dst = ip_dst<<8; ip_src |= (int) ip->srcip[i]; ip_dst |= (int) ip->dstip[i]; } /* Apply mask and get our key - network number */ ip_src &= mask_m; ip_dst &= mask_m; sprintf(key_src,"%08x",ip_src); sprintf(key_dst,"%08x",ip_dst); /* Store length of this packet */ idata.nbyte = (double) length; /* Set logtime to zero (when adding the key first time) meaning that we don't start detailed logging of this subnet yet */ idata.logtime = (time_t) 0; /* Initialize exceed time counters */ idata.exc_time = 0; idata.exc_accum = 0; /* Set bandwidth threshold to zero if we don't have preloaded nets */ idata.band = 0.0; /* Set size of data structures */ datasize = sizeof(aggr_data_t); keysize = sizeof(key_src); #ifdef DUMP printf("Hash table key: "); printf("src %s - dst %s len - %d\n",key_src,key_dst,length); #endif /*********************************************************************/ /* If preload_m is set, we only update and do not add new nodes */ /*********************************************************************/ /* Processing source network */ /* If local ip range specified and src network is not in that range, * don't process this network */ if (!iplist_m || (iplist_m && in_iprange(ip_src,iplist_m,niplist_m))){ /* Add first instance of source key to table */ if (! hash_finddata(ha,(U_CHAR *)&key_src,keysize, (U_CHAR **)&data,&ndata)){ if ( !preload_m ) { datasize = sizeof(idata); hash_addnode(ha,(U_CHAR *)&key_src,keysize, (U_CHAR *)&idata,datasize); } /* Key already present, update info */ } else { /* Update byte count */ data->nbyte += idata.nbyte; /* Do we log packet to detail table? */ if ( data->logtime != 0 ) detail_flag = TRUE; } } /* End of processing source network */ /* Processing destination network */ /* If local ip range specified and dst network is not in that range, * don't process this network */ if (!iplist_m || (iplist_m && in_iprange(ip_dst,iplist_m,niplist_m))) { /* If src and dst on same subnet don't log connection twice */ if ( ip_src != ip_dst ) { /* Add first instance of destination key to table */ if (! hash_finddata(ha,(U_CHAR *)&key_dst,keysize, (U_CHAR **)&data,&ndata)){ if ( !preload_m ) { datasize = sizeof(idata); hash_addnode(ha,(U_CHAR *)&key_dst,keysize, (U_CHAR *)&idata,datasize); } /* Key already present, update info */ } else { /* Update byte count */ data->nbyte += idata.nbyte; /* Do we log packet to detail table? */ if ( data->logtime != 0 ) detail_flag = TRUE; } } /* End of if not on the same subnet */ } /* End of processing destination network */ /*********************************************************************/ /* If this packet should be logged to subnet detail table */ /*********************************************************************/ if( detail_flag ) { /* Make key - order so smallest ip first store data */ if (memcmp(ip->srcip, ip->dstip, 4) < 0) { memcpy (key+ 0, ip->srcip, 4); memcpy (key+ 4, ip->dstip, 4); memcpy (key+ 8, ip->srcpt, 2); memcpy (key+10, ip->dstpt, 2); } else { memcpy (key+ 0, ip->dstip, 4); memcpy (key+ 4, ip->srcip, 4); memcpy (key+ 8, ip->dstpt, 2); memcpy (key+10, ip->srcpt, 2); } memcpy (key+12, ip->prot, 1); idata_d.nbyte = (double) length; /* Fill in subnets this packet belongs to for easier deleting */ idata_d.subnet_src = ip_src; idata_d.subnet_dst = ip_dst; /* Set size of data structures */ datasize_d = sizeof(data_t); keysize_d = sizeof(key); /* Add first instance of this key to table */ if (! hash_finddata(ha_d,(U_CHAR *)&key, keysize_d, (U_CHAR **)&data_d, &ndata_d) ) { datasize_d = sizeof(idata_d); hash_addnode(ha_d,(U_CHAR *)&key, keysize_d, (U_CHAR *)&idata_d, datasize_d); /* Key already present, update info */ } else { data_d->nbyte += idata_d.nbyte; } } /* End logging to subnet detail table */ } /* Process per-subnet aggregate hash table */ void proc_aggr (hlist_t **ha, hlist_t **ha_d) { hlist_t *t; aggr_data_t *data; FILE *outfile_m = stdout; double kbytes; float kBps; float thresh; int exc_time; hiter_t ti; /* table iterator */ if (do_html) { time_t generated; time (&generated); if (! htmltitle_m) { htmltitle_m = strdup(HTMLTITLE_DEF); } html_report("\n"); html_report("\n"); html_report("\n"); html_report("\n"); html_report(" %s\n", htmltitle_m); html_report(" \n", cycle_m); html_report(" \n"); html_report(" \n"); html_report(" \n"); html_report("\n"); html_report("\n"); html_report("\n"); html_report("\n"); html_report("\n"); html_report("\n", htmltitle_m); html_report("\n", ctime(&generated)); html_report("\n"); html_report("\n"); html_report(" \n"); html_report("\n"); html_report("
%s
Date: %s

\n"); html_report(" \n"); html_report(" \n"); html_report(" \n"); } /* Walk hash table */ for(t=hash_getfirst(ha,&ti); t; t = hash_getnext(ha,&ti)){ data = (aggr_data_t *) t->data; /* What is bandwidth threshold for this subnet */ thresh = (data->band) ? data->band : thresh_m; /* Total bytes and bandwidth */ kbytes = (data->nbyte)/1024.0; kBps = (float) kbytes/cycle_m; /* If detailed logging for this subnet in progress */ if ( (long) data->logtime != 0 ){ /* Usage still high */ if ( kBps >= thresh ) { /* How long threshold has been exceeded this cycle? */ exc_time = (int) difftime(time(NULL),data->logtime); /* Is it time to cry out loud? */ if ( exc_time >= rcycle_m ){ /* How long threshold has been exceeded so far? */ data->exc_time += exc_time; /* Accumulated exceed time since app started */ if (report_aggr_m) data->exc_accum += exc_time; subnet_report(ha_d,t->key,thresh, data->exc_time, data->exc_accum); data->logtime = 0; } /* If bandwidth dropped below limit we stop detailed logging */ } else { /* Delete subnet entries from detail log */ detail_cleanup(ha_d,t->key); /* Unset detail logging flag for this subnet */ data->logtime = 0; /* Clear exc_time for subnet */ data->exc_time = 0; } } /* End if detailed logging in progress */ /* if bandwidth threshold is exceeded for the first time we start detailed logging for this subnet setting logtime value in aggr_data_t structure to current time */ if ( kBps >= thresh && 0 == (long) data->logtime ) { data->logtime = time(NULL); } if (do_html) { html_report(" ", hex2dot(t->key)); html_report("\n",kBps); } if (2==debug_m) { /* Print subnet table */ if ( kBps > thresh && (long) data->logtime != 0) fprintf (outfile_m, "*"); else fprintf (outfile_m, " "); fprintf (outfile_m, "%-15s", hex2dot(t->key)); fprintf (outfile_m, " %7.2f kB ",kbytes); fprintf (outfile_m, " %7.2f/%6.2f kBps",kBps,thresh); fprintf (outfile_m, "\n"); } /* Clean-up */ /* If subnet is being logged - zero counters */ if ( (long) data->logtime != 0 ){ data->nbyte = 0; } else { /* If not - delete it. But *only* if we are NOT working with preloaded subnets! */ if (! preload_m ) { hash_delnode(ha, t->key, t->nkey); /* For preloaded subnets - just clear counters */ } else { data->nbyte = 0; } } } /* End of walking table */ if (do_html) { html_report("
IP address Bandwidth

%s %.2f kBps
\n"); html_report("
\n"); html_report("\n"); html_report("\n"); html_report(NULL); } if (2==debug_m) { fprintf(outfile_m,"************************************************\n"); } } /* Delete entries for specific subnet from detail hash table when bandwidth usage for that subnet drops below limit. This is a hash table function but not generic to be put in hash.c. */ void detail_cleanup (hlist_t **ha_d, U_CHAR *key) { int ip_key; int hash; int result; /* Get size of hash table */ int slots = N_HASH_SLOTS; /* from hash.h */ int ntable; int nhashbit = 1; slots--; while (slots>>=1) nhashbit++; ntable = 1 << nhashbit; /* Get subnet number in int */ sscanf(key,"%08x",&ip_key); /* Walk table */ for (hash = 0; hash < ntable; hash++) { if (NULL == ha_d[hash]) continue; result = TRUE; while (result) result = delete_next(ha_d,hash,ip_key); } /* end of walk table loop */ } ipband-0.8.1/popen.c0000744000000000000000000001061711025771407012752 0ustar rootroot/* popen.c secure popen: code mix from Richard Stevens and ntop source * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include #include #include #include "ipband.h" #define __SEC_POPEN_TOKEN " " static pid_t *childpid = NULL; /* ptr to array allocated at run-time */ static int maxfd; /* popen() substitute */ FILE * sec_popen(const char *cmd, const char *type) { char **argv, *ptr, *strtokState; char *cmdcpy = NULL; int i, pfd[2]; pid_t pid; FILE *fp; if(cmd == NULL || cmd == "") return(NULL); if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) { errno = EINVAL; /* required by POSIX.2 */ return(NULL); } if((cmdcpy = strdup(cmd)) == NULL) return(NULL); argv = NULL; if((ptr = strtok_r(cmdcpy, __SEC_POPEN_TOKEN, &strtokState)) == NULL) { free(cmdcpy); return(NULL); } for(i = 0;; i++) { if((argv = (char **)realloc(argv, (i+1) * sizeof(char*))) == NULL) { free(cmdcpy); return(NULL); } if((*(argv+i) = (char*)malloc((strlen(ptr)+1) * sizeof(char))) == NULL) { free(cmdcpy); return(NULL); } strcpy(argv[i], ptr); if((ptr = strtok_r(NULL, __SEC_POPEN_TOKEN, &strtokState)) == NULL) { if((argv = (char **) realloc(argv, (i+2) * sizeof(char*))) == NULL) { free(cmdcpy); return(NULL); } argv[i+1] = NULL; break; } } free(cmdcpy); if (childpid == NULL) { /* first time through */ /* allocate zeroed out array for child pids */ maxfd = open_max(); if ( (childpid = calloc(maxfd, sizeof(pid_t))) == NULL) return(NULL); } if (pipe(pfd) < 0) return(NULL); /* errno set by pipe() */ if ( (pid = fork()) < 0) return(NULL); /* errno set by fork() */ else if (pid == 0) { /* child */ if((getuid() != geteuid()) || (getgid() != getegid())) { /* setuid binary, drop privileges */ if (setgid(getgid()) != 0 || setuid(getuid()) != 0) err_sys("Error dropping privileges"); } if (*type == 'r') { close(pfd[0]); if (pfd[1] != STDOUT_FILENO) { dup2(pfd[1], STDOUT_FILENO); close(pfd[1]); } } else { close(pfd[1]); if (pfd[0] != STDIN_FILENO) { dup2(pfd[0], STDIN_FILENO); close(pfd[0]); } } /* close all descriptors in childpid[] */ for (i = 0; i < maxfd; i++) if (childpid[i] > 0) close(i); if(strchr(argv[0], '/') == NULL) execvp(argv[0], argv); /* search in $PATH */ else execv(argv[0], argv); _exit(127); } /* parent */ if (*type == 'r') { close(pfd[1]); if ( (fp = fdopen(pfd[0], type)) == NULL) return(NULL); } else { close(pfd[0]); if ( (fp = fdopen(pfd[1], type)) == NULL) return(NULL); } childpid[fileno(fp)] = pid; /* remember child pid for this fd */ return(fp); } int sec_pclose(FILE *fp) { int fd, stat; pid_t pid; if (childpid == NULL) return(-1); /* popen() has never been called */ fd = fileno(fp); if ( (pid = childpid[fd]) == 0) return(-1); /* fp wasn't opened by popen() */ childpid[fd] = 0; if (fclose(fp) == EOF) return(-1); while (waitpid(pid, &stat, 0) < 0) if (errno != EINTR) return(-1); /* error other than EINTR from waitpid() */ return(stat); /* return child's termination status */ } /* Determine maximum number of open files */ #ifdef OPEN_MAX static int openmax = OPEN_MAX; #else static int openmax = 0; #endif #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */ /* we're not guaranteed this is adequate */ int open_max(void) { if (openmax == 0) { /* first time through */ errno = 0; if ( (openmax = sysconf(_SC_OPEN_MAX)) < 0) { if (errno == 0) openmax = OPEN_MAX_GUESS; /* it's indeterminate */ else err_sys("sysconf error for _SC_OPEN_MAX"); } } return(openmax); } ipband-0.8.1/styles.css0000744000000000000000000000070411025771407013516 0ustar rootrootbody { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #fffbf0; background-color: #008080; } .text { font-family: Fixedsys, monospace; font-size: 9px; color: #fffbf0; } .subject { font-family: Arial, Helvetica, sans-serif; font-size: 21px; color: #ffff00; font-weight: bold; } .date { font-family: Arial, Helvetica, sans-serif; font-size: 12px; } .line { color: #eeeeee; height: 1px; } ipband-0.8.1/main.c0000744000000000000000000001550411025771407012555 0ustar rootroot/* main.c * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * Much of the code is based on ipaudit by Jon Rifkin * * Thanks to Nic Bellamy for promisc mode on/off and variable type correction * patch. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" /* Initialize here and not in set_defaults() in case the latter called _after_ the structures are created */ ll_srvc_t *ll_tcp_cache = NULL; /* Resolved tcp services cache */ ll_srvc_t *ll_udp_cache = NULL; /* Resolved udp services cache */ int main (int argc, char *argv[]) { struct pcap_pkthdr pkthdr; U_CHAR *raw_pkt_save = NULL; U_CHAR *raw_pkt = NULL; hlist_t **hconn = NULL; /* subnet aggreg connection table */ hlist_t **hconn_d = NULL; /* subnet detail connection table */ fd_set rdfs; int fd; int retval; pid_t pid; eth_struct_t *eth_pkt = NULL; ip_struct_t *ip_pkt = NULL; time_t t0, t1; char *config_name_def = CONFIG_DEF; /* Initialize global variables */ set_defaults(); /* Initialize aggregate and detail hash tables */ hconn = hash_init(); hconn_d = hash_init(); /* Read default config file */ config_m = strdup(config_name_def); read_config(config_m); /* Read command line options (override config file) and interface */ read_options(argc, argv); /* Check if option values are reasonable */ check_invalues(); /* Record application start time */ started_m = time(NULL); /* Print all options for debug */ if (debug_m) dump_options(); /* Check for interface */ if( 1 == (argc-optind) ) { pcapdev_m = strdup(argv[optind]); } if( !pcapdev_m) { print_usage(); return(1); } /* Try to fork */ if (fork_m) { switch (pid = fork()) { case 0: /* Child */ setsid(); /* Become session leader */ chdir("/"); /* Don't hold on to current dir */ { /* Close all file descriptors */ int fd = 0; int maxfd = open_max(); while (fd < maxfd) close(fd++); } /* New descriptors for stdin, stdout & stderr */ open("/dev/null",O_RDWR); dup(0); dup(0); break; case -1: printf("Couldn't run in background, exiting...\n"); exit(1); default: /* Parent */ /* printf("Running in background...%d\n",(int) pid); */ exit(0); } } /* Convert number of mask bits to mask in hex */ if (mask_m == 32) { /* Ugly */ mask_m = 0xffffffff; } else { mask_m = 0xffffffff >> mask_m; mask_m ^= 0xffffffff; } /* If subnet option was specified in config file we will now read config file one more time and add subnet data to the table. We couldn't do this before since there was no guarantee that subnet mask appeared before subnets list in the file */ if (preload_m) parse_subnets(config_m,hconn); /* Open pcap file */ open_interface(promisc_m); /* Print datalink type as returned by pcap */ if (debug_m) print_datalink(); /* Now we have MAC frame size and can check it against frame size * adjustment option value */ if( -lenadj_m > pcapoffset_m ) err_quit("ERROR: absolute value of frame length adjustment is greater then layer 2 frame size for the interface\n"); /* Allocate room for saved raw packet */ raw_pkt_save = (U_CHAR *) malloc (PLEN); /* Install interupt handler */ signal (SIGINT, ihandler); /* intercepts ^C */ signal (SIGTERM, ihandler); /* intercepts ^kill */ signal (SIGPIPE, ihandler); /* intercepts broken pipe */ /* Initialize info for select(). Using select here as we might add multiple interfaces later */ FD_ZERO (&rdfs); fd = pcap_fileno(pcapfile_m); FD_SET (fd, &rdfs); /* Record cycle start time */ t0 = time(NULL); /* Read packets until interupt signal */ while (isig_m == 0) { /* Wait for packet on one of the interfaces */ retval = select (fd+1, &rdfs, NULL, NULL, NULL); /* If user interupt caught during select() call, retval will be <0. By continuing we re-test isig_m which should now be set by the interupt handler */ if (retval<0) continue; /* Read packet */ raw_pkt = (U_CHAR *) pcap_next (pcapfile_m, &pkthdr); if (raw_pkt==NULL) continue; /* Skip this packet if ethernet and not ip */ if (pcapoffset_m==POFF_ETH) { eth_pkt = (eth_struct_t *) raw_pkt; if (! (eth_pkt->ptype[0]==8 && eth_pkt->ptype[1]==0) ) continue; } /* Find pointer to ip packet */ ip_pkt = (ip_struct_t *) (raw_pkt + pcapoffset_m); /* Dump packet contents if debugging */ if (3==debug_m) { unsigned int ibyte; int iwidth; printf ("Raw packet length %d ", pkthdr.len); if (lenadj_m) { printf ("(%d after adjustment)", pkthdr.len + lenadj_m); } printf ("\n"); printf ("Captured bytes (%d) ...\n", pkthdr.caplen); iwidth=0; for (ibyte=0;ibyteprot[0]!=0x11 && ip_pkt->prot[0]!=0x06 ) { if (ip_pkt->prot[0]==1) { memset (ip_pkt->dstpt, 0, 2); } else { memset (ip_pkt->srcpt, 0, 2); memset (ip_pkt->dstpt, 0, 2); } } /* Dump packet ip data if debugging */ if (3==debug_m) { printf ("*%03d.%03d.%03d.%03d -> %03d.%03d.%03d.%03d %3d %5d %5d\n\n", ip_pkt->srcip[0],ip_pkt->srcip[1],ip_pkt->srcip[2],ip_pkt->srcip[3], ip_pkt->dstip[0],ip_pkt->dstip[1],ip_pkt->dstip[2],ip_pkt->dstip[3], ip_pkt->prot[0], ip_pkt->srcpt[0]*256+ip_pkt->srcpt[1], ip_pkt->dstpt[0]*256+ip_pkt->dstpt[1]); } /* Store packets in the hash tables */ storepkt(&pkthdr, ip_pkt, hconn, hconn_d); /* In the end of the loop check if it's time to check aggregate table for bandwidth usage, reset the table and start logging individual subnets */ t1 = time(NULL); if ( (int) difftime(t1,t0) >= cycle_m) { t0 = t1; proc_aggr(hconn, hconn_d); /* Process aggregate table */ } } /* end of main loop (isig_m == 0) */ /* Close files */ pcap_close(pcapfile_m); /* Clear error if breaking during pcap call */ errno = 0; exit(0); } ipband-0.8.1/INSTALL0000744000000000000000000000054011025771407012510 0ustar rootrootIPBAND ====== Requirements ============ - Libpcap (http://www-nrg.ee.lbl.gov/nrg.html) IPBAND was developed and tested on i386 system running Red Hat 7.1. It was also successfully compiled and tested on FreeBSD (4.3-RELEASE) and OpenBSD 2.9. Basic Installation ================== Modify Makefile if needed. Do `make` followed by `make install`. ipband-0.8.1/Makefile0000744000000000000000000000331311025771407013120 0ustar rootroot# # ipband - IP bandwidth watchdog # Change this variables to match your installation # # Note: When the version changes, you also have to change # the RPM spec file V=0.8.1 MAKE=make CPPFLAGS=-I/usr/include/pcap LIBS=-lpcap CFLAGS := -Wall $(CFLAGS) CC=gcc ifndef PREFIX PREFIX=/usr endif ifndef BINDIR BINDIR=$(PREFIX)/sbin endif ifndef MANDIR MANDIR=$(PREFIX)/share/man endif ifndef MAN8DIR MAN8DIR=$(MANDIR)/man8 endif ifndef SYSCONFDIR #SYSCONFDIR=$(PREFIX)/etc SYSCONFDIR=/etc endif ifndef RCDIR RCDIR=$(SYSCONFDIR)/rc.d/init.d endif BIN = ipband SRC_C = main.c error.c init.c packets.c \ pcapfunc.c popen.c reports.c utils.c hash.c OBJ_C = $(SRC_C:.c=.o) all: $(BIN) $(BIN): $(OBJ_C) $(CC) -o $(BIN) $(OBJ_C) $(LIBS) $(CFLAGS) strip $(BIN) install-strip: install install: all mkdir -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(MAN8DIR) mkdir -p $(DESTDIR)$(SYSCONFDIR) mkdir -p $(DESTDIR)$(RCDIR) install -D ipband $(DESTDIR)$(BINDIR)/ipband install -D ipband.8 $(DESTDIR)$(MAN8DIR)/ipband.8 install -D ipband.sample.conf $(DESTDIR)$(SYSCONFDIR)/ipband.sample.conf install -D ipband.rc $(DESTDIR)$(RCDIR)/ipband clean: rm -f *.o rm -f ipband # # ------------------------------------------------------------------------- # # If we need rpm SRC_ROOT = Makefile CHANGELOG COPYING README INSTALL ipband.spec styles.css SRC_SRCS = Makefile *.c *.h ipband.8 SRC_CONF = ipband.sample.conf ipband.rc tgz: mkdir ipband-$(V) cp $(SRC_ROOT) ipband-$(V)/ cp $(SRC_SRCS) ipband-$(V)/ cp $(SRC_CONF) ipband-$(V)/ tar -czvf ipband-$(V).tgz ipband-$(V)/ rm -rf ipband-$(V) rpm: tgz mv ipband-$(V).tgz /usr/src/redhat/SOURCES cp ipband.spec /usr/src/redhat/SPECS rpmbuild -bb ipband.spec ipband-0.8.1/pcapfunc.c0000744000000000000000000000566511025771407013437 0ustar rootroot/* pcapfunc.c pcap related routines * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" void open_interface (int promisc) { struct bpf_program fcode; char ebuf[PCAP_ERRBUF_SIZE]; pcapfile_m = pcap_open_live(pcapdev_m, PLEN, promisc, 1000, ebuf); if (pcapfile_m==NULL) { printf("ipband: Trouble opening <%s>, msg=\"%s\"\n", pcapdev_m, ebuf); exit(1); } /* Find IP header offset */ pcapoffset_m = get_packetoffset(pcap_datalink(pcapfile_m)); /* Apply user requested packet filter code */ if (pcap_compile(pcapfile_m, &fcode, filtercmd_m, 0, 0) < 0) printf("compile: %s", pcap_geterr(pcapfile_m)); if (pcap_setfilter(pcapfile_m, &fcode) < 0) printf("setfilter: %s", pcap_geterr(pcapfile_m)); /* Problem with pcap_setfilter? Sets error, unset here */ errno = 0; } /* Return IP header offset depending on the interface type */ int get_packetoffset (int DataLinkType) { int PacketOffset; switch (DataLinkType) { case DLT_EN10MB: case DLT_IEEE802: PacketOffset = POFF_ETH; break; case DLT_PPP: PacketOffset = POFF_PPP; break; case DLT_RAW: PacketOffset = POFF_RAW; break; /* For others we guess */ default: PacketOffset = 0; } return PacketOffset; } /* Prints datalink type */ void print_datalink() { printf ("Interface (%s) ", pcapdev_m); switch (pcap_datalink(pcapfile_m)) { case DLT_EN10MB: printf ("DataLinkType = %s\n", "DLT_EN10MB"); break; case DLT_IEEE802: printf ("DataLinkType = %s\n", "DLT_IEEE802"); break; case DLT_SLIP: printf ("DataLinkType = %s\n", "DLT_SLIP"); break; case DLT_SLIP_BSDOS: printf ("DataLinkType = %s\n", "DLT_SLIP_BSDOS"); break; case DLT_PPP: printf ("DataLinkType = %s\n", "DLT_PPP"); break; case DLT_PPP_BSDOS: printf ("DataLinkType = %s\n", "DLT_PPP_BSDOS"); break; case DLT_FDDI: printf ("DataLinkType = %s\n", "DLT_FDDI"); break; case DLT_NULL: printf ("DataLinkType = %s\n", "DLT_NULL"); break; case DLT_RAW: printf ("DataLinkType = %s\n", "DLT_RAW"); break; case DLT_ATM_RFC1483: printf ("DataLinkType = %s\n", "DLT_ATM_RFC1483"); break; default: printf ("DataLinkType = %d\n", pcap_datalink(pcapfile_m)); } printf("\n"); } ipband-0.8.1/hash.h0000744000000000000000000000231411025771407012554 0ustar rootroot#ifndef HASH_H__ #define HASH_H__ /* ------------------------------------------------------------------------ Defines ------------------------------------------------------------------------ */ #define N_HASH_SLOTS 10000 /* ------------------------------------------------------------------------ Type Definitions ------------------------------------------------------------------------ */ /* Table node structure */ typedef struct hlist_s { struct hlist_s *next; u_char *key; int nkey; u_char *data; int ndata; } hlist_t; /* Table iterator structure */ typedef struct hiter_s { int index; hlist_t *ptr; } hiter_t; /* ------------------------------------------------------------------------ Function Prototypes ------------------------------------------------------------------------ */ hlist_t **hash_init () ; int hash_finddata (hlist_t **, u_char *, int, u_char **, int *); int hash_delnode (hlist_t **, u_char *, int); int hash_addnode (hlist_t **, u_char *, int, u_char *, int) ; int hash_getcount (hlist_t **); hlist_t **hash_getlist (hlist_t **, int *); hlist_t *hash_getnext (hlist_t **, hiter_t *); hlist_t *hash_getfirst (hlist_t **, hiter_t *); #endif /* HASH_H__ */ ipband-0.8.1/ipband.h0000744000000000000000000001641211025771407013072 0ustar rootroot/* ipband.h * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef IPBAND_H__ #define IPBAND_H__ /* ------------------------------------------------------------------------ Include Files ------------------------------------------------------------------------ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef AF_INET #include /* BSD AF_INET */ #endif #include #include "hash.h" /* ------------------------------------------------------------------------ Defines ------------------------------------------------------------------------ */ #define VERSION_STR "ipband 0.8.1" #define DUMP #undef DUMP /* Defaults */ #define CONFIG_DEF "/etc/ipband.conf" #define MTASTR_DEF "/usr/sbin/sendmail -t -oi" #define REPFILE_DEF "ipband.txt" #define HTMLFILE_DEF "ipband.html" #define HTMLTITLE_DEF "My bandwidth" #define TRUE 1 #define FALSE 0 #define MAXLINE 4096 /* Length of saved packets */ #define PLEN 68 /* Length of packet headers */ #define POFF_ETH 14 #define POFF_PPP 4 #define POFF_RAW 0 #define U_CHAR unsigned char /* Used for setting defaults */ #define FREE(P) if ((P)!=NULL) { free(P); (P)=NULL; } /* ------------------------------------------------------------------------ Type Definitions ------------------------------------------------------------------------ */ /* Packet structure used by pcap library */ typedef struct { U_CHAR src[6]; U_CHAR dst[6]; U_CHAR ptype[2]; /* ==0x800 if ip */ } eth_struct_t; typedef struct { U_CHAR version[1]; U_CHAR service[1]; U_CHAR length[2]; U_CHAR id[2]; U_CHAR flag[2]; U_CHAR ttl[1]; U_CHAR prot[1]; U_CHAR chksum[2]; U_CHAR srcip[4]; U_CHAR dstip[4]; U_CHAR srcpt[2]; U_CHAR dstpt[2]; } ip_struct_t; /* Subnet detail data */ typedef struct { double nbyte; /* These 2 are keys for deleting detail data for a given subnet */ int subnet_src; int subnet_dst; } data_t; /* Per subnet aggregate data */ typedef struct { double nbyte; /* * Non-zero value in logtime means: a) we started detailed * logging for this subnet; b) we keep logging on next cycle * and don't spin off another logging; c) we only zero byte * counters for this subnet and don't delete this subnet from * hash table; d) we check if bandwidth goes _below_ limit to * stop logging and create a report. */ time_t logtime; /* * Number of seconds threshold was exceeded since we started * detailed logging */ int exc_time; /* * For pre-loaded subnets we store their bandwidth * threshold value */ float band; /* * Accumulated threshold exceed time in seconds since * ipband started. Only makes sense for preloaded subnets * as otherwise subnet data is deleted when usage drops. */ unsigned int exc_accum; } aggr_data_t; /* Linked list for tcp and udp services cache */ typedef struct ll_srvc_s { struct ll_srvc_s *next; int port; char *sname; } ll_srvc_t; /* ------------------------------------------------------------------------ Global variables ------------------------------------------------------------------------ */ /* Externals */ extern char pcap_version[]; /* Internal use */ int isig_m; /* Interupt flag for capture loop */ int preload_m; /* Subnets are preloaded flag */ char *pcapdev_m; /* Device to listen to */ pcap_t *pcapfile_m; /* Pcap input file descriptor */ int pcapoffset_m; /* IP header offset */ time_t started_m; /* Time when we started */ ll_srvc_t *ll_tcp_cache; /* Resolved tcp services cache */ ll_srvc_t *ll_udp_cache; /* Resolved udp services cache */ /* Variables holding option values */ int debug_m; /* Debug option */ int do_html; /* Generate HTML output */ char *filtercmd_m; /* Pcap filter string */ char *repfname_m; /* Subnet report output file */ char *htmlfname_m; /* HTML report output file */ char *htmltitle_m; /* HTML Title */ int mask_m; /* Network aggregation mask bits */ int cycle_m; /* Number of sec to average data */ int rcycle_m; /* How long in sec bandwidth threshold may be exceeded */ float thresh_m; /* Bandwidth threshold in kBps */ int fork_m; /* Fork flag */ int top_m; /* No of top connections in report */ char *config_m; /* Config file name */ char *mailto_m; /* E-mail address for reporting */ char *mailfoot_m; /* Footer file for e-mail report */ char *mtastring_m; /* MTA command string */ int report_aggr_m; /* Flag to report aggr exceed time */ int promisc_m; /* Use promiscious mode? */ int *iplist_m; /* List of local networks */ int niplist_m; /* Number of local networks */ int lenadj_m; /* IP packet length adjustment in bytes */ /* ------------------------------------------------------------------------ Local Function Prototypes ------------------------------------------------------------------------ */ /* error.c */ void err_msg(const char *, ...); void err_quit(const char *, ...); void err_ret(const char *, ...); void err_sys(const char *, ...); /* init.c */ void print_usage (); void read_options (int argc, char *argv[]); void dump_options(); void ihandler (int); int read_config (char *); void check_invalues(); int parse_subnets (char *, hlist_t **); void preload_subnets(char *, hlist_t **); void set_defaults(); void parse_ip_range (char *, int **, int *); int in_iprange (int, int *, int); /* packets.c */ void storepkt (struct pcap_pkthdr *, ip_struct_t *, hlist_t **, hlist_t **); void proc_aggr (hlist_t **, hlist_t **); void detail_cleanup(hlist_t **, U_CHAR *); /* pcapfunc.c */ void open_interface (int); void print_datalink (); int get_packetoffset (int); /* popen.c */ FILE *sec_popen(const char *, const char *); int sec_pclose(FILE *); int open_max(void); /* reports.c */ void subnet_report (hlist_t **, U_CHAR *,float, int, unsigned int); void va_report(char *,...); void html_report(char *,...); char *get_service(int, int); /* utils.c */ int delete_next(hlist_t **, int, int); char *hex2dot (char *); void get_two_tok(char *, char **, char **); int is_space(char); char *find_nonspace (char *); char *find_space (char *); int strcmpi (char *, char *); int is_true_str (char *); int compare_bytes (const void *, const void *); void str2ip (char *, int *, int *); #ifdef strtok_r #undef strtok_r #endif char *strtok_r(char *, const char *, char **); #endif /* IPBAND_H__ */ ipband-0.8.1/ipband.spec0000744000000000000000000000150011025771407013565 0ustar rootrootSummary: IP bandwidth watchdog. Name: ipband Version: 0.8.1 Release: 1 License: GPL Group: Applications/Network Source: ipband-0.8.1.tgz Requires: libpcap %description ipband is pcap based IP traffic monitor. It listens to a network interface in promiscuous mode, tallies per-subnet traffic and bandwidth usage and starts detailed logging if specified threshold for the specific subnet is exceeded. This utility could be handy in a limited bandwidth WAN environment (frame relay, ISDN etc. circuits) to pinpoint offending traffic source if certain links become saturated to the point where legitimate packets start getting dropped. %prep %setup %build make %install make install %post chkconfig --add ipband %files /usr/share/man/man8/ipband.8 /usr/sbin/ipband /etc/ipband.sample.conf /etc/rc.d/init.d/ipband ipband-0.8.1/COPYING0000744000000000000000000004310211025771407012513 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1990, 1991, 1992 Free Software Foundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ipband-0.8.1/utils.c0000744000000000000000000001134611025771407012771 0ustar rootroot/* utils.c - various support functions * * ipband - network bandwidth watchdog * By Andrew Nevynniy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" /* Delete next node matching ip_key from given slot */ int delete_next(hlist_t **ha_d, int hash, int ip_key) { hlist_t *t_prev; hlist_t *t; data_t *data; int subnet_src, subnet_dst; for(t=ha_d[hash]; t; t_prev=t, t=t->next) { data = (data_t *) t->data; subnet_src = data->subnet_src; subnet_dst = data->subnet_dst; if((subnet_src == ip_key) || (subnet_dst == ip_key)) { free(t->data); free(t->key); if (t == ha_d[hash]) ha_d[hash] = t->next; else t_prev->next = t->next; free((void *) t); return 1; } } return 0; } /* Convert 8 byte hex string to dotted octet string */ char * hex2dot (char * str) { int i,ip; int p[4]; static char buf[20]; sscanf(str,"%08x",&ip); for (i=0;i<4;i++) { p[i] = ip & 0xff; ip >>= 8; } sprintf (buf, "%d.%d.%d.%d", p[3], p[2], p[1], p[0]); return buf; } /* Return pointers to first two space delimited tokens, null terminating first token if necessary. If no first,second token then pointers point to '\0' */ void get_two_tok(char *str, char **tok1, char **tok2) { /* Find start of first token */ str = find_nonspace(str); *tok1 = *tok2 = str; if (*str=='\0') return; /* Find end of first token */ *tok2 = str = find_space (str); if (*str=='\0') return; /* terminate first token */ *(str++) = '\0'; /* find second token */ *tok2 = find_nonspace(str); /* Remove trailing space */ str = str + strlen(str) - 1; while (is_space(*str)) { str--; } *(++str) = '\0'; } /* Test for space *OR* equals sign * (to allow shell scripts lines like TERM=vt1000 to be used as config * files * */ int is_space(char c) { return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='='; } /* Find first non-space char */ char *find_nonspace (char *str) { while (*str && is_space(*str)) str++; return str; } /* Find first space char */ char *find_space (char *str) { while (*str && !is_space(*str)) str++; return str; } /* Compare two strings ignoring case */ int strcmpi (char *a, char *b) { int equal = 1; char c,d; while (equal && *a) { c = *a++; d = *b++; if ('a'<=c && c<='z') c += 'A' - 'a'; if ('a'<=d && d<='z') d += 'A' - 'a'; equal = (c==d); } if (equal) return 0; if (cdata; datab = (data_t *) (*tb)->data; return (datab->nbyte) - (dataa->nbyte); } /* Convert strings like "138.99.201.5" or "137.99.26" to int ip address */ void str2ip (char *ipstr, int *ipout, int *mask) { int ip[4]; int n = sscanf (ipstr, "%d.%d.%d.%d", ip, ip+1, ip+2, ip+3); int i; *ipout = 0; for (i=0;i<4;i++) { *ipout = *ipout<<8; if (i> (8*n); /* for reasons unknown 0xffffffff >> 32 -> -1, so set to 0 */ if (*mask==-1) *mask=0; } /* Reentrant string tokenizer. Generic version. Slightly modified from: glibc 2.1.3 Copyright (C) 1991, 1996, 1997, 1998, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. */ char *strtok_r(char *s, const char *delim, char **save_ptr) { char *token; if (s == NULL) s = *save_ptr; /* Scan leading delimiters. */ s += strspn (s, delim); if (*s == '\0') return NULL; /* Find the end of the token. */ token = s; s = strpbrk (token, delim); if (s == NULL) /* This token finishes the string. */ *save_ptr = ""; else { /* Terminate the token and make *SAVE_PTR point past it. */ *s = '\0'; *save_ptr = s + 1; } return token; } ipband-0.8.1/ipband.80000744000000000000000000002347411025771407013020 0ustar rootroot.\" .TH "ipband" "8" "Jun 13, 2008" "Andrew Nevynniy" "" .SH "NAME" ipband \- IP bandwidth watchdog .SH "SYNOPSIS" .BI ipband \-aAbcCdfFhJlLmMowPrtTv \fIINTERFACE\fR .sp .SH "DESCRIPTION" .B ipband is a pcap based IP traffic monitor. It tallies per\-subnet traffic and bandwidth usage and starts detailed logging if specified threshold for the specific subnet is exceeded. If traffic has been high for a certain period of time, the report for that subnet is generated which can be appended to a file or e\-mailed. When bandwidth usage drops below the threshold, detailed logging for the subnet is stopped and memory is freed. This utility could be handy in a limited bandwidth WAN environment (frame relay, ISDN etc. circuits) to pinpoint offending traffic source if certain links become saturated to the point where legitimate packets start getting dropped. It also can be used to monitor internet connection when specifying the range of local ip addresses (to avoid firing reports about non\-local networks). Bandwidth is defined as total size in kBytes of the layer 2 frames with IP packets passing the specified interface during the avaraging period devided by the number of seconds in that period. .SH "COMMAND LINE OPTIONS" .TP .B interface Network interface to read data from. .TP .B \-a \fIsecs\fR Averaging period in seconds. How often total traffic and bandwidth should be calculated. Default is 60 secs. .TP .B \-A Include threshold exceeded accumulated time and percentage in the report. This option works only with preloaded subnets ("subnet" directive) because otherwise subnet data is deleted when bandwidth usage drops below threshold to clear memory and reduce processing time. .TP .B "\-b \fIkBps\fR" Bandwidth threshold in kBytes per sec. Default is 7 kBps i.e. 56 kbps. .TP .B "\-c \fIfilename\fR" Use \fIfilename\fR as configuration file. Default is /etc/ipband.conf. Specifying different bandwidth threshold per subnet is only available through the configuration file. See \fBsubnet\fR directive in the CONFIGURATION FILE section below. .TP .B "\-C" Ignore configuration file. .TP .B "\-d \fIlevel\fR" Debug level. 0 \- no debuging; 1 \- summary; 2 \- subnet statistics; 3 \- all packets captured. Default is 0. .TP .B "\-f \fIfilterstr\fR" Use \fIfilterstr\fR as pcap filter. See manual page for tcpdump. Also see EXAMPLES section below. .TP .B "\-F" Fork and run in background. Default is run in foreground. .TP .B "\-h" Print help and exit. .TP .B "\-J \fInumber\fR" Packet length adjustment in bytes. This option can be used when layer 2 frame sizes for the interface ipband is listening on and the interface we are measuring the bandwidth for are different. For example, if you are concerned about bandwidth usage on a router's frame relay interface with 6 bytes overhead (frame header + RFC1490 encapsulation) while ipband is running on an ethernet interface with 14 bytes MAC frame, then you could use value \-8 for this option to get more accurate bandwidth calculation. The \fInumber\fR can be a positive or a negative integer. Negative values should not exceed leyer 2 frame size for the ipband's interface (i.e. we can't use \-15 in the above example). The default is 0. .TP .B "\-l \fIfilename\fR" If \-M (or \fBmailto\fR directive in config file) option is set, specifies name of the file to be appended to the end of e\-mail reports. .TP .B "\-L \fIip\-range[:ip\-range[:ip\-range[..]]]\fR" This option specifies which network numbers should be considered local when collecting data and generating reports (actually non\-local networks are not logged at all). It can be used instead of config file's multiple "subnet" directives (unlike that directive, there would be a single bandwidth threshold specified by \-b option). This option can be used for monitoring internet connections when you don't want to get reports on someone else's networks. There can be many ip\-ranges separate by colons. No spaces may appear in the argument. Each ip\-range can be either a single ip address such as 192.168.1.1 which indicates a range of one, a partial ip address such as 192.168.1.0 which indicates a range from 192.168.1.0 to 192.168.1.255, a low and high ip address separated by a hypen (\-), and a single ip address, a slash (/) and an integer between 0 and 32 (a "net address") which indicates a network. If you run ipband with the debug option (\-d) the program will print the entire list of ip ranges, so you can check their values. Here is a list of arguments to \-L along with the corresponding range. COMMAND: \fBipband eth0 \-l 137.99.11\fR RANGE: 137.99.11.0\-137.99.11.255 COMMAND: \fBipband eth0 \-L 137.99.11:127.0.5/23\fR RANGE: 137.99.11.0\-137.99.11.255,127.0.4.0\-127.0.5.255 COMMAND: \fBipband eth0 \-L 127.1.5.17\-127.1.7.131\fR RANGE: 127.1.5.17\-127.1.7.131 .TP .B "\-m \fImaskbits\fR" Set number of subnet mask bits (1\-32) for subnet traffic aggregation. Default is 24 (255.255.255.0). .TP .B "\-M \fIemail address(es)\fR" Send detailed subnet report to specified e\-mail address(es). Multiple addresses must be separated by comma. .TP .B "\-o \fIfilename\fR" Filename to output detailed subnet report. Default is ipband.txt in current directory. .TP .B "\-w \fIfilename\fR" HTML report output file. Default is ipband.html in current directory. The styles.css file can be used in the same directory to customize its look and feel. .TP .B "\-P" Do not use promiscuous mode on the network interface we are listening on. .TP .B "\-r \fIsecs\fR" Reporting period \- number of seconds bandwidth threshold may be exceeded before it should be reported. Default is 300 seconds. .TP .B "\-t \fInumber\fR" Limit subnet report to a given number of per\-host connections with highest byte count (top connections). Default is no limit. .TP .B "\-T \fIstring\fR" MTA command string for mailing reports. Default is "/usr/sbin/sendmail \-t \-oi". The string is tokenized and passed directly to exec(), so that shell's metacharacters are not interpreted. .TP .B "\-v" Print version and exit. .SH "CONFIGURATION FILE" In addition to command line options you can use a configuration file. When \fBipband\fR starts it first looks for /etc/ipband.conf. You can also give the '\-c' (see OPTIONS above) to specify a configuration file. The options in the config file are specified by keyword/value pairs. Lines starting with # are ignored. Below is a list of config file options: .TP .B interface \fIinterface\fR Interface to read packets from. .TP .B promisc \fI{yes/no}\fR Like \-P option, specifies whether or not to use promiscious mode on the listening network interface. Promiscuous mode is the default. .TP .B debug \fI{0\-3}\fR Like \-d option, specifies debug level. .TP .B fork \fI{yes/no}\fR Like \-F option, specifies whether or not to run in background. Default is no. .TP .B filter \fIfilterstr\fR Like \-f option, specifies pcap filter. .TP .B outfile \fIfilename\fR Like \-o option, specifies report file name. efault is ipband.txt in current directory. .TP .B htmlfile \fIfilename\fR Like \-w option, HTML report output file. Default is ipband.html in current directory. The styles.css file can be used in the same directory to customize its look and feel. .TP .B htmltitle \fItitle\fR HTML title of the report output file. .TP .B bandwidth \fIkBps\fR Like \-b option, bandwidth threshold in kBytes per second. Default is 7.0 kBps. .TP .B average \fIsecs\fR Like \-a option, tells \fBipband\fR nomber of seconds to average per\-subnet traffic and calculate bandwidth usage. Default is 60 seconds. .TP .B lenadj \fInumber\fR Like \-J option, specifies packet length adjustment in bytes. .TP .B report \fIsecs\fR Like \-r option, number of seconds specified threshold(s) may be exceeded before report is fired off. Default is 300 secs. .TP .B top \fInumber\fR Like \-t option, limits subnet report to a given number of per\-host connections with highest byte count (top connections). Default is 0 \- no limit. .TP .B accumulate \fI{yes/no}\fR Like \-A option, whether or not to include threshold exceeded accumulated time and percentage in the report. Default is no. .TP .B mailto \fIemail address(es)\fR Like \-M option, e\-mail address(es) detailed subnet report should be sent to. Multiple addresses must be separated by comma. .TP .B mailfoot \fIfilename\fR Like \-l option, name of the file to be appended to the end of e\-mail reports. .TP .B mtastring \fIstring\fR Like \-T option, specifies MTA command string for mailing reports. Default is "/usr/sbin/sendmail \-t \-oi". .TP .B maskbits \fI{1\-32}\fR Like \-m option, sets the number of network mask bits. Default is 24 (corresponding to subnet mask 255.255.255.0). .TP .B localrange \fIip_range\fR Like \-L option, determines which range(s) of ip addresses are considered local. .TP .B subnet \fIsubnet\-ip\fR \fBbandwidth\fR \fIkBps\fR Specifies which subnets \fBipband\fR should work with and sets individual bandwidth thresholds for them \- one subnet option per line (subnet mask is set by \fImaskbits\fR option). This option is only available through a configuration file. Setting it limits data collection and reporting to the specified subnets. .SH "EXAMPLES" .TP .B ipband eth0 \-f "net 10.10.0.0/16" \-m 24 \-a 300 \-r 900 Will capture packets from/to ip addresses matching 10.10.0.0/255.255.0.0, tally traffic by the third octet,calculate bandwidth utilization every 5 minutes and report per host traffic every 15 minutes. .TP .B ipband \-c ipband.conf Read configuration from file ipband.conf. .SH "BUGS" .TP Report mailing blocks until pipe to sendmail returns. .TP Report any bugs to anevynni@russelmetals.com. .br Thanks. .SH "AUTHOR" Andrew Nevynniy \fIanevynni@russelmetals.com\fR .TP ipband is based on ipaudit\-0.95 by J Rifkin \fIjon.rifkin@uconn.edu\fR (http://www.sp.uconn.edu/~jrifkin). .SH "VERSION" 0.8.1 Jun 13, 2008 .SH "SEE ALSO" .BR tcpdump (1) .BR pcap (3) ipband-0.8.1/hash.c0000744000000000000000000002116511025771407012554 0ustar rootroot/* hash.c * * hash.c - generic basic hash table functions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------------------------------------------------ Include files ------------------------------------------------------------------------ */ #include #include #include #include /* BSD u_char */ #include "hash.h" /* ------------------------------------------------------------------------ Defines ------------------------------------------------------------------------ */ #define U_CHAR unsigned char #define UINT4 unsigned int #define NRSEQ 256 /* ------------------------------------------------------------------------ Module variables ------------------------------------------------------------------------ */ static int ntable_m=0; /* Random sequence table - source of random numbers. The hash routine 'amplifies' this 2**8 long sequence into a 2**32 long sequence. */ static U_CHAR rseq_m[NRSEQ+3] = { 79,181, 35,147, 68,177, 63,134,103, 0, 34, 88, 69,221,231, 13, 91, 49,220, 90, 58,112, 72,145, 7, 4, 93,176,129,192, 5,132, 86,142, 21,148, 37,139, 39,169,143,224,251, 64,223, 1, 9,152, 51, 66, 98,155,180,109,149,135,229,137,215, 42, 62,115,246,242, 118,160, 94,249,123,144,122,213,252,171, 60,167,253,198, 77, 2, 154,174,168, 52, 27, 92,226,233,205, 10,208,247,209,113,211,106, 163,116, 65,196, 73,201, 23, 15, 31,140,189, 53,207, 83, 87,202, 101,173, 28, 46, 6,255,237, 47,227, 36,218, 70,114, 22,100, 96, 182,117, 43,228,210, 19,191,108,128, 89, 97,153,212,203, 99,236, 238,141, 3, 95, 29,232, 8, 75, 57, 25,159, 24,131,162, 67,119, 74, 30,138,214,240, 12,187,127,133, 18, 81,222,188,239, 82,199, 186,166,197,230,126,161,200, 40, 59,165,136,234,250, 44,170,157, 190,150,105, 84, 55,204, 56,244,219,151,178,195,194,110,184, 14, 48,146,235,216,120,175,254, 50,102,107, 41,130, 54, 26,248,225, 111,124, 33,193, 76,121,125,158,185,245, 16,206, 71, 45, 20,179, 32, 38,241, 80, 85,243, 11,217, 61, 17, 78,172,156,183,104,164, 79,181, 35 }; /* ------------------------------------------------------------------------ Local Function Prototypes ------------------------------------------------------------------------ */ UINT4 foldkey (U_CHAR *key, int keylength); UINT4 makehash( UINT4 ); double mrand ( UINT4 ); /* ------------------------------------------------------------------------ Exported Functions ------------------------------------------------------------------------ */ hlist_t **hash_init () { int ntable = N_HASH_SLOTS; int nhashbit = 1; ntable--; while (ntable>>=1) nhashbit++; ntable_m = 1 << nhashbit; if (ntable_m<=0) return NULL; return calloc(ntable_m, sizeof(hlist_t *)); } int hash_finddata (hlist_t **ha, U_CHAR *key, int nkey, U_CHAR **data, int *ndata) { int hash; hlist_t *t; hash = (int) ( ntable_m * mrand ( foldkey(key, nkey) ) ); if (NULL==ha[hash]) { *data = NULL; *ndata = 0; return 0; } /* Search list */ t = ha[hash]; while (NULL!=t) { if (t->nkey==nkey && ! memcmp(t->key, key, nkey)) { *data = t->data; *ndata = t->ndata; return 1; } t = t->next; } *data = NULL; *ndata = 0; return 0; } /* Delete note from the table */ int hash_delnode (hlist_t **ha, U_CHAR *key, int nkey) { int hash; hlist_t *t; hlist_t *t_prev; /* Find hash */ hash = (int) ( ntable_m * mrand ( foldkey(key, nkey) ) ); /* If table entry is blank, nothing to delete */ if (NULL==ha[hash]) return 0; /* Search list */ for(t = ha[hash]; t; t_prev = t, t = t->next) { if (t->nkey==nkey && ! memcmp(t->key, key, nkey)) { if (t->data) free(t->data); free(t->key); if (t == ha[hash]) ha[hash] = t->next; /* Was first */ else t_prev->next = t->next; /* Wasn't */ free((void *) t); return 1; } } /* Not found even though slot wasn't empty ? */ return 0; } /* Add node to *front* of list */ int hash_addnode (hlist_t **ha, U_CHAR *key, int nkey, U_CHAR *data, int ndata) { int hash; hlist_t **pt; hlist_t *t; hlist_t *next; /* Find hash */ hash = (int) ( ntable_m * mrand ( foldkey(key, nkey) ) ); /* If table entry is blank, make new entry */ if (NULL==ha[hash]) { pt = &(ha[hash]); /* Search table for existing node */ } else { pt = &(ha[hash]); t = *pt; while (NULL!=t) { /* Existing node with same key, replace the data */ if ( t->nkey==nkey && ! memcmp(t->key,key,nkey) ) { if (t->data) free(t->data); if (NULL==t->data || 0==t->ndata) { t->data = NULL; t->ndata = 0; } else { t->data = calloc(1, ndata); t->ndata = ndata; memcpy(t->data, data, ndata); } return 0; } pt = &(t->next); t = *pt; } } /* If reached here then key not found */ /* Make a new node (unattached to list) */ t = calloc(1, sizeof(hlist_t)); t->key = calloc(1, nkey); t->data = calloc(1, ndata); t->nkey = nkey; t->ndata = ndata; t->next = NULL; memcpy(t->key, key, nkey); memcpy(t->data, data, ndata); /* Add node to list tail */ if (NULL==ha[hash]) { *pt = t; /* Add node to list head */ } else { next = ha[hash]; ha[hash] = t; t->next = next; } return 0; } /* Get count of nodes */ int hash_getcount (hlist_t **ha) { int count = 0; int hash; hlist_t *t; for (hash = 0; hash next; count++; } } } return count; } /* Get array of non-nodes and modify count of nodes */ hlist_t **hash_getlist (hlist_t **ha, int *cp) { int hash; hlist_t *t; hlist_t **list = NULL; *cp = 0; /* number of nodes */ for (hash = 0; hash next; (*cp)++; } } } return list; } /* Find first existing node */ hlist_t *hash_getfirst (hlist_t **ha, hiter_t *ti) { ti->index = (-1); ti->ptr = NULL; return hash_getnext(ha,ti); } /* Find next node */ hlist_t *hash_getnext (hlist_t **ha, hiter_t *ti) { hlist_t *result; while((result = ti->ptr) == NULL) { if( ++(ti->index) >= ntable_m ) return NULL; /* Nothing left */ ti->ptr = ha[ti->index]; } ti->ptr = result->next; return result; } /* ------------------------------------------------------------------------ Local Functions ------------------------------------------------------------------------ */ /* 'Folds' n-byte key into 4 byte key */ UINT4 foldkey(U_CHAR *key, int keylength) { int ikey; int tkey; UINT4 fkey = 0; int ishift = 0; /* "fold" original key into four byte key */ for (ikey=0; ikey=32) ishift = 0; } return fkey; } /* Hash function - performs a one to one mapping between input integer and output integers, in other words, two different input integers a_i, a_j will ALWAYS result in two different output makehash(a_i) and makehash(a_j). This hash function is designed so that a changing just one bit in input 'a' will potentially affect the every bit in makehash(a), and the correlation between succesive hashes is (hopefully) extremely small (if not zero). It can be used as a quick, dirty, portable and open source random number generator that generates randomness on all 32 bits. Use wrapper function mrand(n) to obtain floating point random number r 0.0 <= r < 1.0 */ UINT4 makehash(UINT4 a) { U_CHAR *c = (U_CHAR *) &a; U_CHAR d[4] = {0, 0, 0, 0}; int i; for (i=0;i<4;i++) { d[3] = rseq_m[c[0] ] + rseq_m[c[1]+1] + rseq_m[c[2]+2] + rseq_m[c[3]+3]; d[2] = rseq_m[c[1] ] + rseq_m[c[2]+1] + rseq_m[c[3]+2]; d[1] = rseq_m[c[2] ] + rseq_m[c[3]+1]; d[0] = rseq_m[c[3] ]; a = * (int *) &d[0]; } return a; } /* Map hash value into number 0.0<= n < 1.0 */ double mrand (UINT4 a) { static double f = 1.0/4294967296.0; return f * makehash(a); } ipband-0.8.1/ipband.rc0000755000000000000000000000154611025771407013253 0ustar rootroot#!/bin/sh # # ipband This shell script takes care of starting and stopping # ipband. # # chkconfig: - 85 15 # description: ip bandwidth watchdog # Source function library. . /etc/init.d/functions [ -f /etc/ipband.conf ] || exit 0 RETVAL=0 prog="ipband" start() { echo -n $"Starting $prog: " daemon /usr/local/bin/ipband RETVAL=$? echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/ipband return $RETVAL } stop() { echo -n $"Shutting down $prog: " killproc ipband RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/ipband return $RETVAL } # See how we were called. case "$1" in start) start ;; stop) stop ;; status) status ipband RETVAL=$? ;; restart|reload) stop start RETVAL=$? ;; *) echo $"Usage: $0 {start|stop|restart|status}" exit 1 esac ipband-0.8.1/README0000744000000000000000000000306111025771407012340 0ustar rootrootIPBAND (FEB 20, 2002) ========================== Contents ======== ipband is a pcap based IP traffic monitor. It listens to a network interface in promiscuous mode, tallies per-subnet traffic and bandwidth usage and starts detailed logging if specified threshold for the specific subnet is exceeded. Suggested Usage =============== The utility could be handy in a limited bandwidth WAN environment (frame relay, ISDN etc. circuits) to pinpoint offending traffic source if certain links become saturated to the point where legitimate packets start getting dropped. It also can be used to monitor internet connection when specifying the range of local ip addresses (to avoid firing reports about non-local networks). Installing ========== (1) You must first have pcap library installed (see Requirements below). (2) Type 'make' to produce executables. (3) Type 'make install' to install executable, man page and sample config file. (4) 'ipband' typically must be run as root to read the network interface. Documentation ============= See the man page ipband.1. Bugs/Todo ========= Report mailing blocks until pipe to sendmail returns. Might add threads later. Contact Info ============ Andrew Nevynniy . Requirements ============ IPBAND uses the pcap library which is available from the URL http://www-nrg.ee.lbl.gov/nrg.html. It is installed by default in some Unix environments, and it available as an rpm from Red Hat. License ======= IPBAND is covered by the GNU General Public Licensse. See the file COPYING for copying permission. ipband-0.8.1/reports.c0000744000000000000000000002170111025771407013323 0ustar rootroot/* reports.c reporting functions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ipband.h" /* Print detail report for given subnet */ void subnet_report (hlist_t **ha_d, U_CHAR *key, float thresh, int exc_time, unsigned int exc_aggr) { hlist_t **conn = NULL; int nconn, j, count; hlist_t *t; data_t *data; char ip1[16], ip2[16], uprots[4]; int pt1, pt2, prot; double kbytes; time_t now = time(NULL); int i; int ip_src = 0; int ip_dst = 0; int ip_key = 0; int max_conn; char *srvcs; /* Service name */ char *prots; /* Protocol name */ struct protoent *prot_s; /* IP protocol structure */ struct netent *net_s; /* Resolved network name sructure */ int ikey; /* key as integer */ /* Get array of pointers to data and number of connections */ nconn = 0; conn = hash_getlist(ha_d,&nconn); /* Sort array descending by byte count */ qsort(conn,nconn,sizeof(hlist_t *),compare_bytes); /* Get network name if available */ sscanf(key,"%08x",&ikey); net_s = getnetbyaddr(ikey,AF_INET); /* Print e-mail subject to include subnet info */ if(net_s) va_report("Subject: Bandwidth report for %s <%s>\n\n",hex2dot(key),net_s->n_name); else va_report("Subject: Bandwidth report for %s\n\n",hex2dot(key)); /* Print header */ va_report("\nDate: %s", ctime(&now)); if(top_m) va_report("Showing top %d connections\n",top_m); va_report("Network: %s", hex2dot(key)); if(net_s) va_report(" <%s>",net_s->n_name); va_report("\n"); va_report("Bandwidth threshold: %.2f kBps, exceeded for: %.2f min\n",thresh,(float) exc_time/60.0); /* Total accumulated time and percentage would not apply * if subnets are not pre-loaded as they would be deleted * once bandwidth usage dropped below threshold */ if(report_aggr_m && preload_m) { char *exc_str; size_t lastch; float elapsed; exc_str = ctime(&started_m); lastch = strlen(exc_str) - 1; if (exc_str[lastch] == '\n') exc_str[lastch] = '\0'; /* How many secs passed since we started? */ elapsed = (float) difftime(time(NULL),started_m); va_report("Threshold exceeded time since %s: %.2f min (%4.2f%%)\n",exc_str, (float) exc_aggr/60.0, exc_aggr*100.0/elapsed); } va_report("===============================================================================\n"); va_report("FROM < PORT> TO < PORT> PROT KBYTES SERVICE\n"); va_report("-------------------------------------------------------------------------------\n"); /* Walk hash table */ max_conn = (top_m && top_m < nconn) ? top_m : nconn; for(j=0, count=0; jdata; for(i=3; i>=0; i--) { ip_src += t->key[i] << (8*i); ip_dst += t->key[i+4] << (8*(i+4)); } /* Skiping subnets other than our */ ip_src = data->subnet_src; ip_dst = data->subnet_dst; sscanf(key,"%08x",&ip_key); if ( !(ip_src == ip_key || ip_dst == ip_key) ) continue; /* Inreasing loop counter only after other subnets are skipped */ count++; /* Get ip addresses and ports */ sprintf (ip1, "%u.%u.%u.%u", t->key[0], t->key[1], t->key[2], t->key[3]); sprintf (ip2, "%u.%u.%u.%u", t->key[4], t->key[5], t->key[6], t->key[7]); pt1 = (int) t->key[ 8]*256 + t->key[ 9]; pt2 = (int) t->key[10]*256 + t->key[11]; prot = t->key[12]; /* For tcp or udp we try to resolve service name */ if (6 == prot) { /* tcp */ srvcs = get_service(pt1,prot); if (!strlen(srvcs)) srvcs = get_service(pt2,prot); prots = "tcp"; } else if (17 == prot ) { /* udp */ srvcs = get_service(pt1,prot); if (!strlen(srvcs)) srvcs = get_service(pt2,prot); prots = "udp"; } else { /* not tcp or udp */ if ( (prot_s = getprotobynumber(prot)) ) { prots = prot_s->p_name; } else { snprintf(uprots, 4, "%u",prot); prots = uprots; } srvcs = ""; } /* Print key info */ va_report("%-15s <%5u> <-> %-15s <%5u> %4s", ip1, pt1, ip2, pt2, prots); /* Total bytes, time and service */ kbytes = (data->nbyte)/1024.0; va_report(" %12.2f",kbytes); if (srvcs) va_report(" %.11s",srvcs); va_report("\n"); } /* End looping through connections */ va_report("===============================================================================\n"); /* Close report file handles */ va_report(NULL); /* Free array of pointers */ if( NULL != conn ) free(conn); } /* Get service name by tcp or udp port number and store in cache */ char *get_service(int port, int prot) { ll_srvc_t *p; char *srvcs; char *prots; struct servent *srvc_s; struct protoent *prot_s; int found = 0; srvcs = ""; /* For tcp or udp we try to resolve service name */ if (6 == prot) { /* tcp */ /* Check service name in cache */ p = ll_tcp_cache; while (p) { if (port == p->port) { found = 1; srvcs = p->sname; } p = p->next; } /* Not in cache? Put there */ if( !found) { /* Resolve name */ if ((srvc_s = getservbyport(htons(port),"tcp"))) srvcs = srvc_s->s_name; /* Insert name in front of tcp cache linked list */ if( (p = (ll_srvc_t *) malloc(sizeof(*p))) ){ p->port = port; p->sname = strdup(srvcs); p->next = ll_tcp_cache; ll_tcp_cache = p; } } } else if (17 == prot ) { /* udp */ if ( (prot_s = getprotobynumber(prot)) ) { prots = prot_s->p_name; } /* Check service name in cache */ p = ll_udp_cache; while (p) { if (port == p->port) { found = 1; srvcs = p->sname; } p = p->next; } /* Not in cache? Put there */ if( !found) { /* Resolve name */ if ((srvc_s = getservbyport(htons(port),prots))) srvcs = srvc_s->s_name; /* Insert name in front of udp cache linked list */ if( (p = (ll_srvc_t *) malloc(sizeof(*p))) ){ p->port = port; p->sname = strdup(srvcs); p->next = ll_udp_cache; ll_udp_cache = p; } } } return srvcs; } /* Use variable length arguments to output reports to multiple facilities */ void va_report(char *cp,...) { va_list va; static FILE *sendmail; /* static to persist across calls */ static FILE *repfile; /* static to persist across calls */ FILE *ffoot = NULL; char buffer[512]; char *str; if (!cp){ /* Cleanup when called with NULL format string */ if (repfile) { if (repfile != stdout) fclose(repfile); repfile = NULL; } if (sendmail && mailto_m) { /* Append mail footer if needed */ if (mailfoot_m) { if ( (ffoot = fopen (mailfoot_m, "r")) ){ while ( (str=fgets(buffer, 512, ffoot)) ) fputs(str,sendmail); fclose (ffoot); } } /* Close handle */ sec_pclose(sendmail); sendmail = NULL; } } else { /* Get handles and print */ if (!repfile) { if (! repfname_m) repfname_m = strdup(REPFILE_DEF); if (strcmp("-",repfname_m)) repfile = fopen (repfname_m, "a"); else repfile = stdout; if (NULL==repfile) { err_quit("ERROR: Cannot open output file <%s>\n", repfname_m); } } if (mailto_m) { /* If e-mail option is set */ /* Open pipe to MTA */ if(!sendmail) { sendmail = sec_popen(mtastring_m,"w"); if (NULL==sendmail) { err_quit("ERROR: error opening %s\n",mtastring_m); } /* Sendmail headers */ fprintf(sendmail,"To: %s\n",mailto_m); fprintf(sendmail,"From: IP bandwdth watchdog <>\n"); } } if (strncmp(cp,"Subject:",8)) { /* Skip mail subject line */ va_start(va,cp); if( repfile) vfprintf(repfile,cp,va); va_end(va); } if (mailto_m) { va_start(va,cp); if( sendmail) vfprintf(sendmail,cp,va); va_end(va); } } } /* HTML reports */ void html_report(char *cp,...) { va_list va; static FILE *htmlfile; /* static to persist across calls */ if (!cp) { /* Cleanup when called with NULL format string */ if (htmlfile) { if (htmlfile != stdout) { fclose(htmlfile); } htmlfile = NULL; } } else { /* Get handles and print */ if (!htmlfile) { if (! htmlfname_m) { htmlfname_m = strdup(HTMLFILE_DEF); } if (strcmp("-",htmlfname_m)) { htmlfile = fopen (htmlfname_m, "w"); } else { htmlfile = stdout; } if (NULL==htmlfile) { err_quit("ERROR: Cannot open output file <%s>\n", htmlfname_m); } } va_start(va,cp); if (htmlfile) { vfprintf(htmlfile,cp,va); } va_end(va); } } ipband-0.8.1/ipband.sample.conf0000744000000000000000000000427511025771407015054 0ustar rootroot####################################******************** # # ipband sample configuration file v.0.8.1 # # Uncomment and modify options as needed # ######################################################## # Debug level. #debug 0 # Interface to listen on. #interface eth0 # Use promiscuous mode on the network interface? Default is yes. #promisc yes # # Running in background? Default is no. #fork no # Pcap filter (see man tcpdump). #filter net 10.10.0.0/16 # Report file. #outfile ipband.txt # HTML report file #htmlfile /var/www/html/ipbandwidth/index.html # HTML title #htmltitle My IP bandwidth # Default bandwidth in kBytes/sec. #bandwidth 7 # Averaging period in seconds. #average 60 # Reporting period. #report 300 # Limit report to a number of top per-host connections (by byte count). # Zero for all conections. #top 15 # Include accumulated threshold exceeded time in the report? # This option works only with preloaded subnets ("subnet" directive). #accumulate no # E-mail address we want to mail report to. Default is not to mail. #mailto root@localhost # Packet length adjustment in bytes. Can be a positive or a negative integer # with negative value not exceeding leyer 2 frame size for the interface. # Default is 0 (no adjustment). #lenadj -8 # ASCII file to use as e-mail report footer. #mailfoot /etc/ipband.foot # MTA string. Default is "/usr/sbin/sendmail -t -ba". Change it to # whatever runs MTA of your choice. Note that the stringis tokenized and # passed to exec(), so that shell's metacharacters are not interpreted. #mtastring "/usr/sbin/sendmail -t -ba" # Default number of subnet mask bits. #maskbits 24 # Range of ip address that are considered local for data collection and # reporting. May be used instead of multiple "subnet" directives. # See man page for format description. #localrange 10.10.82.0/24:10.10.61.0/24 # Limit data collection and reporting to the following subnets with # default subnet mask. # Format: subnet _ip_ bandwidth _number_. #subnet 10.10.82.0 bandwidth 7 #subnet 10.10.61.0 bandwidth 7 #subnet 10.10.14.0 bandwidth 7 #subnet 10.10.20.0 bandwidth 16 #subnet 10.10.85.0 bandwidth 16 ipband-0.8.1/CHANGELOG0000744000000000000000000000777111025771407012706 0ustar rootrootipband 0.8.1 13 Jun 2008 Debian Bug report - #363407. Changed integer type to hold cumulative byte count from long to double to avoid counter overflow in reports. Debian specific (Thanks to Giuseppe Iuculano): No /usr/local/, man 8, no printf when runs in background, don't fail to build if strtok_r is defined as a macro and change default MTA command string for mailing reports. ipband 0.8 02 Oct 2006 A seg fault issue is resolved when a non tcp/udp protocol is encountered during report generation. Thanks to Shane Denovan for providing the patch. Installation directories in Makefile can be specified using PREFIX, BINDIR, MANDIR, SYSCONFDIR and RCDIR environmental variables. Thanks to Enrico Weigelt. Added "-w" option (and corresponding htmlfile and htmltitle directives) to allow generation of HTML report. Thanks to SHOREWALL TimeLord for providing the patch. ipband 0.7.2 25 Mar 2002 Proper procedure is used to become daemon process. Fixed a bug where a footer file descriptor was not closed (sic). ipband 0.7.1 20 Feb 2002 Fixed a bug where getopt() return value was interpreted as char and not integer. This could have caused problems parsing command line options on systems where char is signed by default. ipband 0.7 10 Jan 2002 Added "-T" option and "mtastring" directive to specify MTA command string. The default is "/usr/sbin/sendmail -t -ba" and now can be overridden for systems that use other mail transport agents for mailing ipband reports. As a result, for security reasons call to popen() has been replaced with a safer routine that parses the MTA string and uses exec() to start specified program thus avoiding shell expansions. If ipband is running setuid/setgid, these privileges are dropped before exec() in the child process. Also added "-J" option and corresponding "lenadj" directive to specify packet length adjustment. This can be used when layer 2 frame sizes for the interface ipband is listening on and the interface we are measuring the bandwidth for are different. A bug in packet length calculation for non-ethernet interfaces has been fixed. The bug was in the code inherited from ipaudit and resulted in a hard coded value of 14 bytes (ethernet frame size) being added to each IP datagram regardless of the underlying interface. That caused higher bandwidth usage being repoted for ppp and raw interfaces. Source code is re-organized for easier future development. Some minor changes in error handling routines. ipband 0.6 03 Oct 2001 Support for PPP and WAN (e.g. Sangoma cards) interfaces is added. ipband 0.5 26 Sep 2001 Added "-P" option and "promisc" directive to enable/disable the use of promiscuous mode on the network interface. A tiny signed/unsigned issue is also fixed in the packed content debug dump code. Thanks to Nic Bellamy for providing the patch. Also added "-L" option and "localrange" directive to specify a range of network numbers that are considered local and therefore packets belonging only to these networks are processed. This can be used instead of multiple "subnet" directives in the config file. ipband 0.4.1 13 Sep 2001 Two bugs related to subnet mask calculation were fixed. One was preventing using zero as a number of mask bits and another one resulted in 32 bits being miscalculated as netmask 0.0.0.0. ipband 0.4 12 Sep 2001 Option to include threshold exceeded accumulated time and percentage in the report is added. This option works only with preloaded subnets because otherwise subnet data is deleted when bandwidth usage drops below threshold to clear memory and reduce processing time. ipband 0.31 31 Jul 2001 Added a couple of include's to compile on FreeBSD ipband 0.3 12 Jul 2001 'C' option added to ignore configuration file Memory freeing when resetting default settings is now complete ipband 0.2 11 Jul 2001 Report mailing option added ipband 0.1 04 Jun 2001 Initial Release