/////////////////////////////////////////////////////////////////////////////// // // nmapgrep v0.2 by blh@sr-71.nu 20040522 // // nmapgrep is a program that searches for patterns in nmap log files and // outputs the matching ip if the port is flagged as open. // // in example, searching for hosts that has port 80 open: // # nmapgrep ^80/tcp logfile.txt // // compile: // in win32 using visual studio (not tested for 0.2): // cl nmapgrep.c // // in any unix or with cygwin: // gcc -Wall -O2 -DHAVE_REGEX -o nmapgrep nmapgrep.c // // use -DHAVE_REGEX only if you know that you have regex.h // // feel free to use the code at your own disposal // // changes for version 0.2 // - altered regexp and keywork searching to work for all ports discovered // for the host instead of matching for each line in the log file. // // greetings to everyone attending ph-neutral 0x7d4! // /////////////////////////////////////////////////////////////////////////////// #include #include #include #ifdef HAVE_REGEX #include #include #endif #include void errdo(char *str) { char estr[255]; snprintf(estr, 255, "%s, line %d", str, __LINE__); perror(estr); return; } int main(int argc, char **argv) { FILE *fp = stdin; char buf[1024]; char hoststr[64]; char *ptr1 = NULL; char *ptr2 = NULL; char *ports = NULL; int i = 1; int bz = 1024; int ubz = 0; #ifdef HAVE_REGEX int nmatch = 0; regmatch_t pmatch; regex_t preg; #endif fprintf(stderr, "nmapgrep v0.2 by blh@sr-71.nu 20040522\n"); if(argc < 2) fprintf(stderr, "syntax: %s pattern [nmaplogfile]\n" #ifdef HAVE_REGEX "\t- regular expressions supported\n" #endif , argv[0]), exit(1); if(argc > 2) { if((fp = fopen(argv[2], "r")) == NULL) errdo("fopen"), exit(1); } fgets(buf, 1024, fp); if(strncmp(buf, "# nmap", 6)) fprintf(stderr, "%s: unknown log format.\n", argv[2]), exit(1); if((ports = (char *) malloc(bz)) == NULL) errdo("malloc"), exit(1); #ifdef HAVE_REGEX if((regcomp(&preg, argv[1], REG_EXTENDED)) != 0) errdo("expression"), exit(1); #endif while((fgets(buf, 1024, fp)) != NULL) { if(!strncmp(buf, "Interesting", 11)) { if(((ptr1 = strchr(buf, '(')) == NULL) || ((ptr2 = strchr(ptr1, ')')) == NULL)) fprintf(stderr, "error parsing line %d\n", i), exit(1); ptr1[0] = 0; ptr2[0] = 0; ptr1++; strncpy(hoststr, ptr1, 64); } else if(buf[0] == '\n' && ubz > 0) { #ifdef HAVE_REGEX if((regexec(&preg, ports, nmatch, &pmatch, REG_NOTEOL)) != REG_NOMATCH) #else if(strstr(ports, argv[1])) #endif fprintf(stdout, "%s\n", hoststr); ubz = 0; memset(ports, 0, bz); } else if(strstr(buf, "open")) { if((ubz + strlen(buf)) > bz) { bz += 1024; if((ports = (char *) realloc(ports, bz)) == NULL) errdo("realloc"), exit(1); } strncpy(ports + ubz, buf, bz - ubz); ubz += strlen(buf); } i++; } fclose(fp); exit(0); }