grepcidr-2.0/0000700000175000017500000000000012267022663013002 5ustar jberkesjberkesgrepcidr-2.0/COPYING0000600000175000017500000003544610013343202014031 0ustar jberkesjberkes GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 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 grepcidr-2.0/grepcidr.c0000600000175000017500000004470312327360777014767 0ustar jberkesjberkes/* grepcidr 2.0 - Filter IPv4 and IPv6 addresses matching CIDR patterns Copyright (C) 2004 - 2014 Jem E. Berkes www.berkes.ca 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 #include #include #include #include #include #include #include #include #define EXIT_OK 0 #define EXIT_NOMATCH 1 #define EXIT_ERROR 2 #define TXT_VERSION "grepcidr 2.0\nCopyright (C) 2004 - 2014 Jem E. Berkes \n" #define TXT_USAGE "Usage:\n" \ "\tgrepcidr [-V] [-cisvx] PATTERN [FILE...]\n" \ "\tgrepcidr [-V] [-cisvx] [-e PATTERN | -f PATFILE] [FILE...]\n" #define TXT_USAGE2 "grepcidr: Specify PATTERN or -f FILE to read patterns from\n" #define TXT_BADPAT "grepcidr: Not a valid pattern" #define TXT_FATAL "grepcidr: Fatal error: unexpected size of data type(s) on this system!\n" #define TXT_MEMORY "grepcidr: Fatal error: out of memory!\n" /* Use GREPERROR instead of perror */ #define GREPERROR(prefix) fprintf(stderr, "grepcidr: %s: %s\n", prefix, strerror(errno)); #define MAXFIELD 512 #define TOKEN_SEPS " \t,\r\n" /* so user can specify multiple patterns on command line */ #define INIT_NETWORKS 8192 /* Specifies a network. Whether originally in CIDR format (IP/mask) or a range of IPs (IP_start-IP_end), spec is converted to a range. The range is min to max (32-bit IPs) inclusive. */ struct netspec { unsigned int min; unsigned int max; }; /* IPv6 version of pattern */ struct netspec6 { unsigned char min[16]; unsigned char max[16]; }; /* Macro to test for valid IP address in four integers */ #define VALID_IP(IP) ((IP[0]<256) && (IP[1]<256) && (IP[2]<256) && (IP[3]<256)) /* Macro to build 32-bit IP from four integers */ #define BUILD_IP(IP) ((IP[0]<<24) | (IP[1]<<16) | (IP[2]<<8) | IP[3]) /* Parameters and macros for hints-based search */ #define HINT_LOOKAHEAD 4 /* e.g. if hints looks at P[4], then use 4 */ #define IPV4_FIELD "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz." #define IPV4_BUFSIZE 16 #define IPV4_HINT(P) (isdigit((int)P[0]) && ((P[1]=='.') || (P[2]=='.') || (P[3]=='.'))) #define IPV6_FIELD "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:." #define IPV6_BUFSIZE 46 #define IPV6_HINT1(P) ((P[0]==':') && (P[1]==':') && isxdigit((int)P[2])) #define IPV6_HINT2(P) (isxdigit((int)P[0]) && (P[1]==':')) #define IPV6_HINT3(P) (isxdigit((int)P[0]) && isxdigit((int)P[1]) && (P[2]==':')) #define IPV6_HINT4(P) (isxdigit((int)P[0]) && isxdigit((int)P[1]) && isxdigit((int)P[2]) && (P[3]==':')) #define IPV6_HINT5(P) (isxdigit((int)P[0]) && isxdigit((int)P[1]) && isxdigit((int)P[2]) && isxdigit((int)P[3]) && (P[4]==':')) /* Global variables */ int anymatch = 0; /* did anything match? for exit code */ int invert = 0; /* flag for inverted mode */ unsigned int counting = 0; /* when non-zero, counts matches */ int include_noip = 0; /* flag to include lines without IPs when inverting */ int strict_align = 0; /* flag to enforce strict base alignment */ int strict_nosearch = 0; /* flag for original style, single IP match */ int match_one = 0; /* for -v, have matched one IP on this line */ int seen_ip = 0; /* for -v, have seen an IP on this line */ int shownames = 0; /* show file names with output lines */ unsigned int patterns = 0; /* total patterns in IPv4 array */ unsigned int capacity = 0; /* current capacity of IPv4 array */ struct netspec* array = NULL; /* IPv4 array of patterns */ unsigned int patterns6 = 0; /* total patterns in IPv6 array */ unsigned int capacity6 = 0; /* current capacity of IPv6 array */ struct netspec6* array6 = NULL; /* IPv6 array of patterns */ /* Insert new spec inside array of network spec Dynamically grow array buffer as needed The array must have already been initially allocated, with valid capacity */ void array_insert(struct netspec* newspec) { if (patterns == capacity) { capacity *= 2; array = realloc(array, capacity*sizeof(struct netspec)); } array[patterns++] = *newspec; } void array_insert6(struct netspec6* newspec) { if (patterns6 == capacity6) { capacity6 *= 2; array6 = realloc(array6, capacity6*sizeof(struct netspec6)); } array6[patterns6++] = *newspec; } /* Convert IPv4 address string at location p, string length len, into result which must point to an unsigned int. Returns 1 on success, 0 on failure */ int ipv4_to_uint(const char* p, unsigned long len, unsigned int* result) { unsigned char parsed[4] = { 0 }; char buf[IPV4_BUFSIZE]; if (len > IPV4_BUFSIZE-1) return 0; /* too long to be a valid IPv4 */ memset(buf, 0, sizeof(buf)); memcpy(buf, p, len); if (inet_pton(AF_INET, buf, &parsed) == 1) { *result = BUILD_IP(parsed); return 1; } else return 0; } /* Convert IPv6 address string at location p, string length len, into result which must point to 16 byte unsigned char array. This uses system's inet_pton() which is quite fast on Linux. Returns 1 on success, 0 on failure */ int ipv6_to_uchar(const char* p, unsigned long len, unsigned char* result) { char buf[IPV6_BUFSIZE]; if (len > IPV6_BUFSIZE-1) return 0; /* too long to be a valid IPv6 */ memset(buf, 0, sizeof(buf)); memcpy(buf, p, len); if (inet_pton(AF_INET6, buf, result) == 1) return 1; else return 0; } /* Increment IPv6 address (array at input) and store result. Both input and result must point to 16 byte unsigned char array. */ void ipv6_increment(unsigned char* input, unsigned char* result) { int i, carry=1; for (i=15; i>=0; i--) /* network byte order is big endian */ { int sum = input[i] + carry; result[i] = (unsigned char)(sum & 0xFF); carry = sum >> 8; } } /* Given string, fills in the struct netspec (must be allocated) Accept CIDR IP/mask format or IP_start-IP_end range. Returns true (nonzero) on success, false (zero) on failure. */ int net_parse(const char* line, struct netspec* spec) { unsigned int IP1[4], IP2[4]; int maskbits = 32; /* if using CIDR IP/mask format */ /* Try parsing IP/mask, CIDR format */ if (strchr(line, '/') && (sscanf(line, "%u.%u.%u.%u/%d", &IP1[0], &IP1[1], &IP1[2], &IP1[3], &maskbits) == 5) && VALID_IP(IP1)) { unsigned int ipaddress = BUILD_IP(IP1); if (maskbits == 0) { if (strict_align && (ipaddress != 0)) return 0; /* invalid */ spec->min = 0; spec->max = 0xFFFFFFFF; return 1; } else if ((maskbits < 0) || (maskbits > 32)) return 0; /* invalid */ if (strict_align && (ipaddress & (((1 << (32-maskbits))-1) & 0xFFFFFFFF))) return 0; /* invalid, there are non-zero host bits */ spec->min = ipaddress & (~((1 << (32-maskbits))-1) & 0xFFFFFFFF); spec->max = spec->min | (((1 << (32-maskbits))-1) & 0xFFFFFFFF); return 1; } /* Try parsing a range. Spaces around hyphen are optional. */ else if (strchr(line, '-') && (sscanf(line, "%u.%u.%u.%u - %u.%u.%u.%u", &IP1[0], &IP1[1], &IP1[2], &IP1[3], &IP2[0], &IP2[1], &IP2[2], &IP2[3]) == 8) && VALID_IP(IP1) && VALID_IP(IP2)) { spec->min = BUILD_IP(IP1); spec->max = BUILD_IP(IP2); if (spec->max >= spec->min) return 1; else return 0; } /* Try simple IP address */ else if ((sscanf(line, "%u.%u.%u.%u", &IP1[0], &IP1[1], &IP1[2], &IP1[3]) == 4) && VALID_IP(IP1)) { spec->min = BUILD_IP(IP1); spec->max = spec->min; return 1; } return 0; /* could not parse */ } /* Parse an IPv6 pattern (struct netspec6) Accepts IP or IP/x format Returns true (nonzero) on success, false (zero) on failure. */ int net_parse6(const char* line, struct netspec6* v6spec) { size_t field_len = strspn(line, IPV6_FIELD); unsigned char address[16] = { 0 }; int maskbits = 128; if (!ipv6_to_uchar(line, field_len, address)) return 0; /* no IPv6 found here */ /* Simple IPv6 address is in address */ memcpy(v6spec->min, address, 16); memcpy(v6spec->max, address, 16); if (sscanf(line+field_len, "/%d", &maskbits) == 1) { unsigned char mask; int bytenum; if ((maskbits < 0) || (maskbits > 128)) return 0; /* invalid */ if (maskbits == 0) bytenum = -1; else { bytenum = (maskbits-1)/8; mask = (unsigned char)0xFF << (7 - ((maskbits-1)%8)); v6spec->min[bytenum] &= mask; v6spec->max[bytenum] |= (unsigned char)~mask; } for (++bytenum; bytenum<16; bytenum++) { v6spec->min[bytenum] = 0; v6spec->max[bytenum] = 0xFF; } if (strict_align && (memcmp(v6spec->min, address, 16) != 0)) return 0; /* bad CIDR alignment */ } return 1; } /* Compare two netspecs, for sorting. Comparison is done on minimum of range */ int netsort(const void* a, const void* b) { unsigned int c1 = ((struct netspec*)a)->min; unsigned int c2 = ((struct netspec*)b)->min; if (c1 < c2) return -1; if (c1 > c2) return +1; return 0; } int netsort6(const void* a, const void* b) { unsigned char* c1 = ((struct netspec6*)a)->min; unsigned char* c2 = ((struct netspec6*)b)->min; int n = memcmp(c1, c2, 16); if (n < 0) return -1; if (n > 0) return +1; return 0; } /* Compare two netspecs, for searching. Test if key (only min) is inside range */ int netsearch(const void* a, const void* b) { unsigned int key = ((struct netspec*)a)->min; unsigned int min = ((struct netspec*)b)->min; unsigned int max = ((struct netspec*)b)->max; if (key < min) return -1; if (key > max) return +1; return 0; } int netsearch6(const void* a, const void* b) { unsigned char* key = ((struct netspec6*)a)->min; unsigned char* min = ((struct netspec6*)b)->min; unsigned char* max = ((struct netspec6*)b)->max; if (memcmp(key, min, 16) < 0) return -1; if (memcmp(key, max, 16) > 0) return +1; return 0; } /* Action to take upon a matching line, print the line or count it */ void print_or_count(char* line, const char* filename) { anymatch = 1; if (counting) counting++; else { if (filename && shownames) printf("%s:", filename); printf("%s", line); } } /* Search for this IP (passed in key) among loaded network patterns and determine if it's a "match" Provide either an IPv4 or IPv6 key, but not both. Returns true or false, whether IP matched patterns. */ int match_ip(struct netspec* v4key, struct netspec6* v6key, char* line, const char* filename) { int match = 0; seen_ip = 1; if (v4key && bsearch(v4key, array, patterns, sizeof(struct netspec), netsearch)) match = 1; else if (v6key && bsearch(v6key, array6, patterns6, sizeof(struct netspec6), netsearch6)) match = 1; if (match) { match_one = 1; if (!invert) print_or_count(line, filename); /* take action if not using -v */ } return match; } /* Load patterns defining networks */ void load_patterns(const char* pat_filename, char* pat_strings) { if (pat_filename) { FILE* data = fopen(pat_filename, "r"); if (data) { char line[MAXFIELD]; while (fgets(line, sizeof(line), data)) { struct netspec ipv4_pat; struct netspec6 ipv6_pat; if ((*line=='#')||(*line=='\n')||(*line=='\r')) continue; /* skip blank lines and comments */ if (net_parse(line, &ipv4_pat)) array_insert(&ipv4_pat); else if (net_parse6(line, &ipv6_pat)) array_insert6(&ipv6_pat); else fprintf(stderr, TXT_BADPAT ": %s", line); } fclose(data); } else { GREPERROR(pat_filename); exit(EXIT_ERROR); } } if (pat_strings) { char* token = strtok(pat_strings, TOKEN_SEPS); while (token) { struct netspec ipv4_pat; struct netspec6 ipv6_pat; if (net_parse(token, &ipv4_pat)) array_insert(&ipv4_pat); else if (net_parse6(token, &ipv6_pat)) array_insert6(&ipv6_pat); else fprintf(stderr, TXT_BADPAT ": %s\n", token); token = strtok(NULL, TOKEN_SEPS); } } /* Prepare array for rapid searching */ if (patterns) { unsigned int item; qsort(array, patterns, sizeof(struct netspec), netsort); /* cure overlaps so that ranges are disjoint and consistent */ for (item=1; item= argc) inp_stream = stdin; else { /* One or more file names are specified on the command line */ if (optind+1 < argc) shownames = 1; /* more than one file */ curfilename = argv[optind++]; inp_stream = fopen(curfilename, "r"); if (!inp_stream) { GREPERROR(curfilename); return EXIT_ERROR; } } /* Ready to search this stream or file */ search_stream(inp_stream, curfilename); if (inp_stream != stdin) fclose(inp_stream); } while (optind < argc); if (counting) printf("%u\n", counting-1); /* Cleanup */ if (array) free(array); if (array6) free(array6); if (anymatch) return EXIT_OK; else return EXIT_NOMATCH; } grepcidr-2.0/grepcidr.sgml0000600000175000017500000001744012266566672015511 0ustar jberkesjberkes Jem Berkes
jem@berkes.ca
2013 Jem Berkes Jan 4, 2014
GREPCIDR 1 grepcidr Filter IPv4 and IPv6 addresses matching CIDR patterns grepcidr PATTERN grepcidr | DESCRIPTION grepcidr can be used to filter a list of IP addresses against one or more Classless Inter-Domain Routing (CIDR) specifications. As with grep, there are options to invert matching and load patterns from a file. grepcidr is capable of efficiently processing large numbers of IPs and networks. OPTIONS Show software version Display count of the matching lines, instead of showing the lines Inverse match, include lines without an IP, implies -v Enforce strict alignment of CIDR mask; host portion must be all zero Invert the sense of matching, output lines with IPs that don't match Strict matching, only look at start of line Specify individual IP or CIDR pattern(s) on command-line Load individual IP or CIDR pattern(s) from file USAGE NOTES PATTERN specified on the command line may contain multiple patterns separated by whitespace or commas. For long lists of network patterns, use to load a file where each line contains one pattern (can be IPv4 or IPv6). Blank lines and comments starting with # are ignored. Each IPv4 pattern, whether on command line or loaded from a file, may be: a.b.c.d/xy (CIDR format) a.b.c.d-e.f.g.h (IP range) a.b.c.d (Single IP) And similarly for IPv6: a:b:c::/xyz (CIDR format) a:b:c:: (Single IP) Dotted-decimal IPv4 format, or any legal IPv6 format is supported (see: man inet_pton). IP addresses that appear anywhere on the input line will be compared and matched against the patterns. To be recognized, an IP (field) must end with terminating text. An IPv4 field terminates upon anything other than alphanumeric or dot. An IPv6 field terminates upon anything other than alphanumeric, dot, or colon. This is to prevent accidental matching of ambiguous text such as host names containing reverse DNS. Use the option to do a strict parse without searching the whole line, and grepcidr will only look for the single IP at the start of the line. EXAMPLES grepcidr -f ournetworks blacklist > abuse.log Find customers (CIDR ranges in file) that appear in blacklist grepcidr 2001:db8::/32 log.1 log.2 Search for this IPv6 network inside two files grepcidr 127.0.0.0/8 iplog Searches for any localnet IP addresses inside the iplog file grepcidr "192.168.0.1-192.168.10.13" iplog Searches for IPs matching indicated range in the iplog file script | grepcidr -vf whitelist > blacklist Create a blacklist, with whitelisted networks removed (inverse) grepcidr -f list1 list2 Cross-reference two lists, outputs IPs common to both lists EXIT STATUS As with grep: the exit status is 0 if matching IPs are found, and 1 if not found. If an error occurred the exit status is 2. AUTHOR This software and manual page was written by Jem Berkes <jem@berkes.ca> based on the first man page and DocBook format contributed by Ryan Finnie. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2 or any later version published by the Free Software Foundation. WEB SITE http://www.pc-tools.net/unix/grepcidr/ THANKS Sponsored in part by the Spamhaus Project, http://www.spamhaus.org/ Thanks to John Levine <johnl@taugh.com> for sharing his alternative implementation. I used a couple ideas from his code, such as portable 128-bit numbers and support for multiple input files. However, John's version is quite different and represents a significant fork in the project. Thanks to Ryan Finnie <ryan@finnie.org> for his work on the Debian package. I've adopted several of his changes including the Makefile, and the DocBook format which now is the source of the man page. Thanks to Ryan for writing the first manual in DocBook format. Many thanks to Dick Wesseling <ftu@fi.uu.nl> who suggested an improved data structure format as well as binary search, to improve grepcidr performance.
grepcidr-2.0/README0000600000175000017500000001040612266421240013656 0ustar jberkesjberkesgrepcidr 2.0 - Filter IPv4 and IPv6 addresses matching CIDR patterns Copyright (C) 2004 - 2014 Jem E. Berkes http://www.pc-tools.net/unix/grepcidr/ http://www.berkes.ca/ Sponsored in part by the Spamhaus Project, http://www.spamhaus.org/ DESCRIPTION ----------- grepcidr can be used to filter a list of IP addresses against one or more Classless Inter-Domain Routing (CIDR) specifications. As with grep, there are options to invert matching and load patterns from a file. grepcidr is capable of efficiently processing large numbers of IPs and networks. grepcidr has endless uses in network software, including: mail filtering and processing, network security, log analysis, and many custom applications. COMPILING & INSTALLING ---------------------- make make doc make install COMMAND USAGE ------------- grepcidr [-V] [-cisvx] PATTERN [FILE...] grepcidr [-V] [-cisvx] [-e PATTERN | -f PATFILE] [FILE...] -V Show software version -c Display count of the matching lines, instead of showing the lines -i Inverse match, include lines without an IP, implies -v -s Enforce strict alignment of CIDR mask; host portion must be all zero -v Invert the sense of matching, output lines with IPs that don't match -x Strict matching, only look at start of line -e Specify individual IP or CIDR pattern(s) on command-line -f Load individual IP or CIDR pattern(s) from file MAJOR 2.0 CHANGES ----------------- Version 2.0 adds support for IPv6 addresses. As with 1.4, version 2.0 finds IP addresses anywhere on the line. Use -x to search only from the start of line, like versions 1.3 and earlier. USAGE NOTES ----------- PATTERN specified on the command line may contain multiple patterns separated by whitespace or commas. For long lists of network patterns, use -f to load a file where each line contains one pattern (can be IPv4 or IPv6). Blank lines and comments starting with # are ignored. Each IPv4 pattern, whether on command line or loaded from a file, may be: a.b.c.d/xy (CIDR format) a.b.c.d-e.f.g.h (IP range) a.b.c.d (Single IP) And similarly for IPv6: a:b:c::/xyz (CIDR format) a:b:c:: (Single IP) Dotted-decimal IPv4 format, or any legal IPv6 format is supported (see: man inet_pton). IP addresses that appear anywhere on the input line will be compared and matched against the patterns. To be recognized, an IP (field) must end with terminating text. An IPv4 field terminates upon anything other than alphanumeric or dot. An IPv6 field terminates upon anything other than alphanumeric, dot, or colon. This is to prevent accidental matching of ambiguous text such as host names containing reverse DNS. Use the -x option to do a strict parse without searching the whole line, and grepcidr will only look for the single IP at the start of the line. EXAMPLES -------- grepcidr -f ournetworks blacklist > abuse.log Find customers (CIDR ranges in file) that appear in blacklist grepcidr 2001:db8::/32 log.1 log.2 Search for this IPv6 network inside two files grepcidr 127.0.0.0/8 iplog Searches for any localnet IP addresses inside the iplog file grepcidr "192.168.0.1-192.168.10.13" iplog Searches for IPs matching indicated range in the iplog file script | grepcidr -vf whitelist > blacklist Create a blacklist, with whitelisted networks removed (inverse) grepcidr -f list1 list2 Cross-reference two lists, outputs IPs common to both lists EXIT STATUS ----------- As with grep: the exit status is 0 if matching IPs are found, and 1 if not found. If an error occurred the exit status is 2. THANKS ------ Sponsored in part by the Spamhaus Project, http://www.spamhaus.org/ Thanks to John Levine for sharing his alternative implementation. I used a couple ideas from his code, such as portable 128-bit numbers and support for multiple input files. However, John's version is quite different and represents a significant fork in the project. Thanks to Ryan Finnie for his work on the Debian package. I've adopted several of his changes including the Makefile, and the DocBook format which now is the source of the man page. Thanks to Ryan for writing the first manual in DocBook format. Many thanks to Dick Wesseling who suggested an improved data structure format as well as binary search, to improve grepcidr performance. grepcidr-2.0/Makefile0000600000175000017500000000124612256223406014443 0ustar jberkesjberkesDESTDIR= PREFIX=/usr/local DATAROOTDIR=$(PREFIX)/share DATADIR=$(DATAROOTDIR) EXEC_PREFIX=$(PREFIX) BINDIR=$(EXEC_PREFIX)/bin SBINDIR=$(EXEC_PREFIX)/sbin MANDIR=$(DATAROOTDIR)/man INFODIR=$(DATAROOTDIR)/info CPPFLAGS= CFLAGS=-O3 -Wall -Werror LDFLAGS= all: grepcidr grepcidr: grepcidr.o $(CC) $(CFLAGS) grepcidr.o -o grepcidr doc: grepcidr.1 grepcidr.1: grepcidr.sgml docbook-to-man $< >$@ install: grepcidr install -m 0755 -d $(DESTDIR)$(BINDIR) install -m 0755 grepcidr $(DESTDIR)$(BINDIR)/grepcidr install -m 0755 -d $(DESTDIR)$(MANDIR)/man1 install -m 0644 grepcidr.1 $(DESTDIR)$(MANDIR)/man1/grepcidr.1 clean: rm -f grepcidr *.o doc-clean: rm -f grepcidr.1 grepcidr-2.0/ChangeLog0000600000175000017500000000376212327361112014556 0ustar jberkesjberkesVersion 2.0, 2014-04-27 ======================= * Added IPv6 support * Replaced regex with 'hints' scanner (2x to 10x faster on some platforms) * IP text now require strict termination, avoids matching reverse DNS * Now complains about bad pattern formats instead of silently ignoring * Supports multiple file names on command line, like regular grep * Updated Makefile to be FreeBSD-friendly; also now includes -O3 * Fixed invert (-v) logic and added -i to include lines without an IP * Now supports unlimited line length within input stream/file * Added -s option to enforce strict alignment of CIDR mask * Fixed bug, now recognizes /0 and 0.0.0.0 Version 1.4, 2013-11-20 ======================= * Default behaviour in 1.4 has changed to search anywhere on line * Includes regex to search anywhere on line (based on Jeff Makey's patch) * Added -x option to search without regex, old-style strict (faster) * Makefile and packaging update rollup, courtesy Ryan Finnie * Adopted DocBook man format, contributed by Ryan Finnie * Enhanced documentation and manual page * Increased maximum line length to 1024 bytes Version 1.3, 2005-04-23 ======================= * Much faster than past versions due to binary search of patterns * Decreased memory usage * Applied search improvements suggested by Dick Wesseling * Now supports IP ranges as well as CIDR format * Improved usage to be more grep-like (e.g. filename on command line) * Now uses grep-like exit code (0=ok, 1=no match, 2=error) Version 1.2, 2004-04-23 ======================= * Improved algorithm for faster processing with large number of patterns (approx. 50 times as fast on test set, with specs from diverse regions) version 1.1, 2004-02-16 ======================= * New algorithm has increased speed by about 2.4 times! * Added -c (count) option, like grep * Reduced memory usage in case loading large files (-f) * Added simple Makefile version 1.0, 2004-02-14 ======================= * First public release grepcidr-2.0/grepcidr.10000600000175000017500000001126212266666270014676 0ustar jberkesjberkes.TH "GREPCIDR" "1" .SH "NAME" grepcidr \(em Filter IPv4 and IPv6 addresses matching CIDR patterns .SH "SYNOPSIS" .PP \fBgrepcidr\fR [\fB\fIOPTIONS\fR\fP] PATTERN [\fB\fIFILE...\fR\fP] .PP \fBgrepcidr\fR [\fB\fIOPTIONS\fR\fP] [\fB-e \fIPATTERN\fR\fP | \fB-f \fIPATFILE\fR\fP] [\fB\fIFILE...\fR\fP] .SH "DESCRIPTION" .PP \fBgrepcidr\fR can be used to filter a list of IP addresses against one or more Classless Inter-Domain Routing (CIDR) specifications. As with grep, there are options to invert matching and load patterns from a file. \fBgrepcidr\fR is capable of efficiently processing large numbers of IPs and networks. .SH "OPTIONS" .IP "\fB-V\fP" 10 Show software version .IP "\fB-c\fP" 10 Display count of the matching lines, instead of showing the lines .IP "\fB-i\fP" 10 Inverse match, include lines without an IP, implies \-v .IP "\fB-s\fP" 10 Enforce strict alignment of CIDR mask; host portion must be all zero .IP "\fB-v\fP" 10 Invert the sense of matching, output lines with IPs that don't match .IP "\fB-x\fP" 10 Strict matching, only look at start of line .IP "\fB-e\fP" 10 Specify individual IP or CIDR pattern(s) on command-line .IP "\fB-f\fP" 10 Load individual IP or CIDR pattern(s) from file .SH "USAGE NOTES" .PP PATTERN specified on the command line may contain multiple patterns separated by whitespace or commas. For long lists of network patterns, use \fB-f\fP to load a file where each line contains one pattern (can be IPv4 or IPv6). Blank lines and comments starting with # are ignored. .PP Each IPv4 pattern, whether on command line or loaded from a file, may be: .PP .nf a.b.c.d/xy (CIDR format) a.b.c.d-e.f.g.h (IP range) a.b.c.d (Single IP) .fi .PP .PP And similarly for IPv6: .PP .nf a:b:c::/xyz (CIDR format) a:b:c:: (Single IP) .fi .PP .PP Dotted-decimal IPv4 format, or any legal IPv6 format is supported (see: man inet_pton). .PP IP addresses that appear anywhere on the input line will be compared and matched against the patterns. To be recognized, an IP (field) must end with terminating text. An IPv4 field terminates upon anything other than alphanumeric or dot. An IPv6 field terminates upon anything other than alphanumeric, dot, or colon. This is to prevent accidental matching of ambiguous text such as host names containing reverse DNS. .PP Use the \fB-x\fP option to do a strict parse without searching the whole line, and \fBgrepcidr\fR will only look for the single IP at the start of the line. .SH "EXAMPLES" .PP \fI\fBgrepcidr\fR \-f ournetworks blacklist > abuse.log\fP .PP Find customers (CIDR ranges in file) that appear in blacklist .PP \fI\fBgrepcidr\fR 2001:db8::/32 log.1 log.2\fP .PP Search for this IPv6 network inside two files .PP \fI\fBgrepcidr\fR 127.0.0.0/8 iplog\fP .PP Searches for any localnet IP addresses inside the iplog file .PP \fI\fBgrepcidr\fR "192.168.0.1-192.168.10.13" iplog\fP .PP Searches for IPs matching indicated range in the iplog file .PP \fI\fBscript\fR | \fBgrepcidr\fR \-vf whitelist > blacklist\fP .PP Create a blacklist, with whitelisted networks removed (inverse) .PP \fI\fBgrepcidr\fR \-f list1 list2\fP .PP Cross-reference two lists, outputs IPs common to both lists .SH "EXIT STATUS" .PP As with grep: the exit status is 0 if matching IPs are found, and 1 if not found. If an error occurred the exit status is 2. .SH "AUTHOR" .PP This software and manual page was written by Jem Berkes based on the first man page and DocBook format contributed by Ryan Finnie. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 2 or any later version published by the Free Software Foundation. .SH "WEB SITE" .PP http://www.pc-tools.net/unix/grepcidr/ .SH "THANKS" .PP Sponsored in part by the Spamhaus Project, http://www.spamhaus.org/ .PP Thanks to John Levine for sharing his alternative implementation. I used a couple ideas from his code, such as portable 128-bit numbers and support for multiple input files. However, John's version is quite different and represents a significant fork in the project. .PP Thanks to Ryan Finnie for his work on the Debian package. I've adopted several of his changes including the Makefile, and the DocBook format which now is the source of the man page. Thanks to Ryan for writing the first manual in DocBook format. .PP Many thanks to Dick Wesseling who suggested an improved data structure format as well as binary search, to improve grepcidr performance. .\" created by instant / docbook-to-man, Sun 19 Jan 2014, 01:12