home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / nmap254b.zip / nmap.c < prev    next >
C/C++ Source or Header  |  2002-02-25  |  83KB  |  2,368 lines

  1. /***********************************************************************/
  2. /* nmap.c -- Currently handles the bulk of Nmap's port scanning        */
  3. /* features as well as the command line user interface.  At some point */
  4. /* I hope to move the port scanning & related support functions to     */
  5. /* another file.                                                       */
  6. /*                                                                     */
  7. /***********************************************************************/
  8. /*  The Nmap Security Scanner is (C) 1995-2001 Insecure.Com LLC. This  */
  9. /*  program is free software; you can redistribute it and/or modify    */
  10. /*  it under the terms of the GNU General Public License as published  */
  11. /*  by the Free Software Foundation; Version 2.  This guarantees your  */
  12. /*  right to use, modify, and redistribute this software under certain */
  13. /*  conditions.  If this license is unacceptable to you, we may be     */
  14. /*  willing to sell alternative licenses (contact sales@insecure.com). */
  15. /*                                                                     */
  16. /*  If you received these files with a written license agreement       */
  17. /*  stating terms other than the (GPL) terms above, then that          */
  18. /*  alternative license agreement takes precendence over this comment. */
  19. /*                                                                     */
  20. /*  Source is provided to this software because we believe users have  */
  21. /*  a right to know exactly what a program is going to do before they  */
  22. /*  run it.  This also allows you to audit the software for security   */
  23. /*  holes (none have been found so far).                               */
  24. /*                                                                     */
  25. /*  Source code also allows you to port Nmap to new platforms, fix     */
  26. /*  bugs, and add new features.  You are highly encouraged to send     */
  27. /*  your changes to fyodor@insecure.org for possible incorporation     */
  28. /*  into the main distribution.  By sending these changes to Fyodor or */
  29. /*  one the insecure.org development mailing lists, it is assumed that */
  30. /*  you are offering Fyodor the unlimited, non-exclusive right to      */
  31. /*  reuse, modify, and relicense the code.  This is important because  */
  32. /*  the inability to relicense code has caused devastating problems    */
  33. /*  for other Free Software projects (such as KDE and NASM).  Nmap     */
  34. /*  will always be available Open Source.  If you wish to specify      */
  35. /*  special license conditions of your contributions, just say so      */
  36. /*  when you send them.                                                */
  37. /*                                                                     */
  38. /*  This program is distributed in the hope that it will be useful,    */
  39. /*  but WITHOUT ANY WARRANTY; without even the implied warranty of     */
  40. /*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  */
  41. /*  General Public License for more details (                          */
  42. /*  http://www.gnu.org/copyleft/gpl.html ).                            */
  43. /*                                                                     */
  44. /***********************************************************************/
  45.  
  46. /* $Id: nmap.c,v 1.211 2001/10/14 21:28:41 fyodor Exp $ */
  47.  
  48. #include "nmap.h"
  49. #include "osscan.h"
  50. #include "scan_engine.h"
  51. #include "idle_scan.h"
  52. #include "timing.h"
  53.  
  54. /* global options */
  55. extern char *optarg;
  56. extern int optind;
  57. struct ops o;  /* option structure */
  58. extern char **environ;
  59.  
  60. #ifdef __EMX__
  61. /*
  62.  * Copyright (c) 1983, 1990, 1993
  63.  *    The Regents of the University of California.  All rights reserved.
  64.  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
  65.  * See above for the neccesary list of conditions on use.
  66.  */
  67.  
  68. /* 
  69.  * Check whether "cp" is a valid ascii representation
  70.  * of an Internet address and convert to a binary address.
  71.  * Returns 1 if the address is valid, 0 if not.
  72.  * This replaces inet_addr, the return value from which
  73.  * cannot distinguish between failure and a local broadcast address.
  74.  */
  75. int inet_aton(const char *cp, struct in_addr *addr)
  76. {
  77.     unsigned long    val;
  78.     int        base, n;
  79.     char        c;
  80.     unsigned    parts[4];
  81.     unsigned    *pp = parts;
  82.  
  83.     c = *cp;
  84.     for (;;) {
  85.         /*
  86.          * Collect number up to ``.''.
  87.          * Values are specified as for C:
  88.          * 0x=hex, 0=octal, isdigit=decimal.
  89.          */
  90.         if (!isdigit(c))
  91.             return (0);
  92.         val = 0; base = 10;
  93.         if (c == '0') {
  94.             c = *++cp;
  95.             if (c == 'x' || c == 'X')
  96.                 base = 16, c = *++cp;
  97.             else
  98.                 base = 8;
  99.         }
  100.         for (;;) {
  101.             if (isascii(c) && isdigit(c)) {
  102.                 val = (val * base) + (c - '0');
  103.                 c = *++cp;
  104.             } else if (base == 16 && isascii(c) && isxdigit(c)) {
  105.                 val = (val << 4) |
  106.                     (c + 10 - (islower(c) ? 'a' : 'A'));
  107.                 c = *++cp;
  108.             } else
  109.                 break;
  110.         }
  111.         if (c == '.') {
  112.             /*
  113.              * Internet format:
  114.              *    a.b.c.d
  115.              *    a.b.c    (with c treated as 16 bits)
  116.              *    a.b    (with b treated as 24 bits)
  117.              */
  118.             if (pp >= parts + 3)
  119.                 return (0);
  120.             *pp++ = val;
  121.             c = *++cp;
  122.         } else
  123.             break;
  124.     }
  125.     /*
  126.      * Check for trailing characters.
  127.      */
  128.     if (c != '\0' && (!isascii(c) || !isspace(c)))
  129.         return (0);
  130.     /*
  131.      * Concoct the address according to
  132.      * the number of parts specified.
  133.      */
  134.     n = pp - parts + 1;
  135.     switch (n) {
  136.  
  137.     case 0:
  138.         return (0);        /* initial nondigit */
  139.  
  140.     case 1:                /* a -- 32 bits */
  141.         break;
  142.  
  143.     case 2:                /* a.b -- 8.24 bits */
  144.         if (val > 0xffffff)
  145.             return (0);
  146.         val |= parts[0] << 24;
  147.         break;
  148.  
  149.     case 3:                /* a.b.c -- 8.8.16 bits */
  150.         if (val > 0xffff)
  151.             return (0);
  152.         val |= (parts[0] << 24) | (parts[1] << 16);
  153.         break;
  154.  
  155.     case 4:                /* a.b.c.d -- 8.8.8.8 bits */
  156.         if (val > 0xff)
  157.             return (0);
  158.         val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
  159.         break;
  160.     }
  161.     if (addr)
  162.         addr->s_addr = htonl(val);
  163.     return (1);
  164. }
  165. #endif
  166. /* --- end of inet_aton.c --- */
  167.  
  168. int main(int argc, char *argv[], char *envp[]) {
  169.   /* The "real" main is nmap_main().  This function hijacks control at the
  170.      beginning to do the following:
  171.      1) Check if Nmap called under name listed in INTERACTIVE_NAMES or with
  172.      interactive.
  173.      2) Start interactive mode or just call nmap_main
  174.   */
  175.   char *interactive_names[] = INTERACTIVE_NAMES;
  176.   int numinames = sizeof(interactive_names) / sizeof(char *);
  177.   int nameidx;
  178.   char *nmapcalledas;
  179.   char command[2048];
  180.   int myargc, fakeargc;
  181.   char **myargv = NULL, **fakeargv = NULL;
  182.   char *cptr;
  183.   int ret;
  184.   int i;
  185.   char nmapargs[1024];
  186.   char fakeargs[1024];
  187.   char nmappath[MAXPATHLEN];
  188.   char *pptr;
  189.   char path[4096];
  190.   struct stat st;
  191.   char *endptr;
  192.   int interactivemode = 0;
  193.   int fd;
  194.   struct timeval tv;
  195.  
  196.   /* You never know when "random" numbers will come in handy ... */
  197.   gettimeofday(&tv, NULL);
  198.   srand((tv.tv_sec ^ tv.tv_usec) ^ getpid());
  199.  
  200.   /* initialize our options */
  201.   options_init();
  202.  
  203.   /* Trap these sigs for cleanup */
  204. #if HAVE_SIGNAL
  205.   signal(SIGINT, sigdie);
  206.   signal(SIGTERM, sigdie);
  207.   signal(SIGHUP, sigdie); 
  208.  
  209.   signal(SIGCHLD, reaper);
  210. #endif
  211.  
  212.   /* First we figure out whether the name nmap is called as qualifies it 
  213.      for interactive mode treatment */
  214.   nmapcalledas = strrchr(argv[0], '/');
  215.   if (!nmapcalledas) {
  216.     nmapcalledas = argv[0];
  217.   } else nmapcalledas++;
  218.  
  219.   if ((cptr = getenv("NMAP_ARGS"))) {
  220.     snprintf(command, sizeof(command), "nmap %s", cptr);
  221.     myargc = arg_parse(command, &myargv);
  222.     if (myargc < 1) {
  223.       fatal("NMAP_ARG variable could not be parsed");
  224.     }
  225.     options_init();
  226.     ret = nmap_main(myargc, myargv);
  227.     arg_parse_free(myargv);
  228.     return ret;
  229.   }
  230.  
  231.   for(nameidx = 0; nameidx < numinames; nameidx++) {
  232.     if (strcasecmp(nmapcalledas, interactive_names[nameidx]) == 0) {
  233.       printf("Entering Interactive Mode because argv[0] == %s\n", nmapcalledas);
  234.       interactivemode = 1;
  235.       break;
  236.     }
  237.   }
  238.  
  239.   if (interactivemode == 0 &&
  240.       argc == 2 && strcmp("--interactive", argv[1]) == 0) {
  241.     interactivemode = 1;
  242.   }
  243.  
  244.   if (!interactivemode) {
  245.     options_init();
  246.     if (argc == 3 && strcmp("--resume", argv[1]) == 0) {
  247.       /* OK, they want to resume an aborted scan given the log file specified.
  248.      Lets gather our state from the log file */
  249.       if (gather_logfile_resumption_state(argv[2], &myargc, &myargv) == -1) {
  250.     fatal("Cannot resume from (supposed) log file %s", argv[2]);
  251.       }
  252.       return nmap_main(myargc, myargv);
  253.     }
  254.     return nmap_main(argc, argv);
  255.   }
  256.   /*  printf("\nStarting nmap V. %s by fyodor@insecure.org ( www.insecure.org/nmap/ )\n", VERSION);*/
  257.   printf("\nStarting %s V. %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
  258.  
  259.   printf("Welcome to Interactive Mode -- press h <enter> for help\n");
  260.  
  261.   while(1) {
  262.     printf("nmap> ");
  263.     fflush(stdout);
  264.     fgets(command, sizeof(command), stdin);
  265.     myargc = arg_parse(command, &myargv);
  266.     if (myargc < 1) {
  267.       printf("Bogus command -- press h <enter> for help\n");
  268.       continue;
  269.     }
  270.     if (strcasecmp(myargv[0], "h") == 0 ||
  271.     strcasecmp(myargv[0], "help") == 0) {
  272.       printinteractiveusage();
  273.       continue;
  274.     } else if (strcasecmp(myargv[0], "x") == 0 ||
  275.            strcasecmp(myargv[0], "q") == 0 ||
  276.            strcasecmp(myargv[0], "e") == 0 ||
  277.            strcasecmp(myargv[0], ".") == 0 ||
  278.            strcasecmp(myargv[0], "exit") == 0 ||
  279.            strcasecmp(myargv[0], "quit") == 0) {
  280.       printf("Quitting by request.\n");
  281.       exit(0);
  282.     } else if (strcasecmp(myargv[0], "n") == 0 ||
  283.            strcasecmp(myargv[0], "nmap") == 0) {
  284.       options_init();
  285.       o.interactivemode = 1;
  286.       nmap_main(myargc, myargv);
  287.     } else if (*myargv[0] == '!') {
  288.       cptr = strchr(command, '!');
  289.       system(cptr + 1);
  290.     } else if (*myargv[0] == 'd') {
  291.       o.debugging++;
  292.     } else if (strcasecmp(myargv[0], "f") == 0) {
  293.       switch((ret = fork())) {
  294.       case 0: /* Child */
  295.     /* My job is as follows:
  296.        1) Go through arguments for the following 3 purposes:
  297.        A.  Build env variable nmap execution will read args from
  298.        B.  Find spoof and realpath variables
  299.        C.  If realpath var was not set, find an Nmap to use
  300.        2) Exec the sucka!@#$! 
  301.     */
  302.     fakeargs[0] = nmappath[0] = '\0';
  303.     strcpy(nmapargs, "NMAP_ARGS=");
  304.     for(i=1; i < myargc; i++) {
  305.       if (strcasecmp(myargv[i], "--spoof") == 0) {
  306.         if (++i > myargc -1) {
  307.           fatal("Bad arguments to f!");
  308.         }        
  309.         strncpy(fakeargs, myargv[i], sizeof(fakeargs));
  310.       } else if (strcasecmp(myargv[i], "--nmap_path") == 0) {
  311.         if (++i > myargc -1) {
  312.           fatal("Bad arguments to f!");
  313.         }        
  314.         strncpy(nmappath, myargv[i], sizeof(nmappath));
  315.       } else {
  316.         if (strlen(nmapargs) + strlen(myargv[i]) + 1 < sizeof(nmapargs)) {
  317.           strcat(nmapargs, " ");
  318.           strcat(nmapargs, myargv[i]);
  319.         } else fatal("Arguments too long.");
  320.       }     
  321.     }
  322.     /* First we stick our arguments into envp */
  323.     if (o.debugging) {
  324.       error("Adding to environment: %s", nmapargs);
  325.     }
  326.     if (putenv(nmapargs) == -1) {
  327.       pfatal("Failed to add NMAP_ARGS to environment");
  328.     }
  329.     /* Now we figure out where the #@$#@ Nmap is located */
  330.     if (!*nmappath) {
  331.       if (stat(argv[0], &st) != -1 && !S_ISDIR(st.st_mode)) {
  332.         strncpy(nmappath, argv[0], sizeof(nmappath));
  333.       } else {
  334.         nmappath[0] = '\0';
  335.         /* Doh!  We must find it in path */
  336.         if ((pptr = getenv("PATH"))) {
  337.           strncpy(path, pptr, sizeof(path));
  338.           pptr = path;
  339.           while(pptr && *pptr) {
  340.         endptr = strchr(pptr, ':');
  341.         if (endptr) { 
  342.           *endptr = '\0';
  343.         }
  344.         snprintf(nmappath, sizeof(nmappath), "%s/%s", pptr, nmapcalledas);
  345.         if (stat(nmappath, &st) != -1)
  346.           break;
  347.         nmappath[0] = '\0';
  348.         if (endptr) pptr = endptr + 1;
  349.         else pptr = NULL;
  350.           }
  351.         }
  352.       }
  353.     }
  354.     if (!*nmappath) {
  355.       fatal("Could not find Nmap -- you must add --nmap_path argument");
  356.     }       
  357.  
  358.     /* We should be courteous and give Nmap reasonable signal defaults */
  359. #if HAVE_SIGNAL
  360.     signal(SIGINT, SIG_DFL);
  361.     signal(SIGTERM, SIG_DFL);
  362.     signal(SIGHUP, SIG_DFL);
  363.     signal(SIGSEGV, SIG_DFL);
  364. #endif
  365.  
  366.     /* Now I must handle spoofery */
  367.     if (*fakeargs) {
  368.       fakeargc = arg_parse(fakeargs, &fakeargv);
  369.       if (fakeargc < 1) {
  370.         fatal("Bogus --spoof parameter");
  371.       }
  372.     } else {
  373.       fakeargc = 1;
  374.       fakeargv = (char **) malloc(sizeof(char *) * 2);
  375.       fakeargv[0] = nmappath;
  376.       fakeargv[1] = NULL;
  377.     }
  378.  
  379.     if (o.debugging) error("About to exec %s", nmappath);
  380.     /* Kill stdout & stderr */
  381.     if (!o.debugging) {
  382.       fd = open(DEVNULL, O_WRONLY);
  383.       if (fd != -1) {
  384.         dup2(fd, STDOUT_FILENO);
  385.         dup2(fd, STDERR_FILENO);
  386.       }
  387.     }
  388.  
  389.     /* OK, I think we are finally ready for the big exec() */
  390.     ret = execve(nmappath, fakeargv, environ);
  391.     if (ret == -1) {
  392.       pfatal("Could not exec %s", nmappath);
  393.     }
  394.     break;
  395.       case -1:
  396.     gh_perror("fork() failed");
  397.     break;
  398.       default: /* Parent */
  399.     printf("[PID: %d]\n", ret);
  400.     break;
  401.       }
  402.     } else {
  403.       printf("Unknown command (%s) -- press h <enter> for help\n", myargv[0]);
  404.       continue;
  405.     }
  406.     arg_parse_free(myargv);
  407.   }
  408.   return 0;
  409.  
  410. }
  411.  
  412.  
  413. /* parse a URL stype ftp string of the form user:pass@server:portno */
  414. static int parse_bounce_argument(struct ftpinfo *ftp, char *url) {
  415.   char *p = url,*q, *s;
  416.  
  417.   if ((q = strrchr(url, '@'))) /*we have username and/or pass */ {
  418.     *(q++) = '\0';
  419.     if ((s = strchr(q, ':')))
  420.       { /* has portno */
  421.     *(s++) = '\0';
  422.     strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
  423.     ftp->port = atoi(s);
  424.       }
  425.     else  strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
  426.  
  427.     if ((s = strchr(p, ':'))) { /* User AND pass given */
  428.       *(s++) = '\0';
  429.       strncpy(ftp->user, p, 63);
  430.       strncpy(ftp->pass, s, 255);
  431.     }
  432.     else { /* Username ONLY given */
  433.       log_write(LOG_STDOUT, "Assuming %s is a username, and using the default password: %s\n",
  434.           p, ftp->pass);
  435.       strncpy(ftp->user, p, 63);
  436.     }
  437.   }
  438.   else /* no username or password given */ 
  439.     if ((s = strchr(url, ':'))) { /* portno is given */
  440.       *(s++) = '\0';
  441.       strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
  442.       ftp->port = atoi(s);
  443.     }
  444.     else  /* default case, no username, password, or portnumber */
  445.       strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
  446.  
  447.   ftp->user[63] = ftp->pass[255] = ftp->server_name[MAXHOSTNAMELEN] = 0;
  448.  
  449.   return 1;
  450. }
  451.  
  452. int nmap_main(int argc, char *argv[]) {
  453.   char *p, *q;
  454.   int i, arg;
  455.   size_t j, argvlen;
  456.   FILE *inputfd = NULL;
  457.   char *host_spec;
  458.   short fastscan=0, randomize=1, resolve_all=0;
  459.   short quashargv = 0;
  460.   int numhosts_scanned = 0;
  461.   char **host_exp_group;
  462.   char *idleProxy = NULL; /* The idle host used to "Proxy" an Idlescan */
  463.   int num_host_exp_groups = 0;
  464.   char *machinefilename = NULL, *kiddiefilename = NULL, 
  465.        *normalfilename = NULL, *xmlfilename = NULL;
  466.   struct hostgroup_state hstate;
  467.   int numhosts_up = 0;
  468.   int starttime;
  469.   struct scan_lists *ports = NULL;
  470.   char myname[MAXHOSTNAMELEN + 1];
  471. #if (defined(IN_ADDR_DEEPSTRUCT) || defined( SOLARIS))
  472.   /* Note that struct in_addr in solaris is 3 levels deep just to store an
  473.    * unsigned int! */
  474.   struct ftpinfo ftp = { FTPUSER, FTPPASS, "",  { { { 0 } } } , 21, 0};
  475. #else
  476.   struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { 0 }, 21, 0};
  477. #endif
  478.   struct hostent *target = NULL;
  479.   char **fakeargv;
  480.   struct hoststruct *currenths;
  481.   char emptystring[1];
  482.   int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
  483.                 source addresses? */
  484.   time_t timep;
  485.   char mytime[128];
  486.   int option_index;
  487.   struct option long_options[] =
  488.   {
  489.     {"version", no_argument, 0, 'V'},
  490.     {"verbose", no_argument, 0, 'v'},
  491.     {"debug", optional_argument, 0, 'd'},
  492.     {"help", no_argument, 0, 'h'},
  493.     {"max_parallelism", required_argument, 0, 'M'},
  494.     {"timing", required_argument, 0, 'T'},
  495.     {"max_rtt_timeout", required_argument, 0, 0},
  496.     {"min_rtt_timeout", required_argument, 0, 0},
  497.     {"host_timeout", required_argument, 0, 0},
  498.     {"scan_delay", required_argument, 0, 0},
  499.     {"initial_rtt_timeout", required_argument, 0, 0},
  500.     {"oA", required_argument, 0, 0},  
  501.     {"oN", required_argument, 0, 0},
  502.     {"oM", required_argument, 0, 0},  
  503.     {"oG", required_argument, 0, 0},  
  504.     {"oS", required_argument, 0, 0},
  505.     {"oH", required_argument, 0, 0},  
  506.     {"oX", required_argument, 0, 0},  
  507.     {"iL", required_argument, 0, 0},  
  508.     {"iR", no_argument, 0, 0},
  509.     {"sI", required_argument, 0, 0},  
  510.     {"initial_rtt_timeout", required_argument, 0, 0},
  511.     {"randomize_hosts", no_argument, 0, 0},
  512.     {"osscan_limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
  513.     {"osscan_guess", no_argument, 0, 0}, /* More guessing flexability */
  514.     {"data_length", required_argument, 0, 0},
  515.     {"rH", no_argument, 0, 0},
  516.     {"vv", no_argument, 0, 0},
  517.     {"append_output", no_argument, 0, 0},
  518.     {"noninteractive", no_argument, 0, 0},
  519. #ifdef WIN32
  520.     {"win_list_interfaces", no_argument, 0, 0},
  521.     {"win_norawsock", no_argument, 0, 0}, 
  522.     {"win_forcerawsock", no_argument, 0, 0}, 
  523.     {"win_nopcap", no_argument, 0, 0}, 
  524.     {"win_nt4route", no_argument, 0, 0}, 
  525.     {"win_noiphlpapi", no_argument, 0, 0}, 
  526.     {"win_help", no_argument, 0, 0},
  527.     {"win_trace", no_argument, 0, 0},
  528. #endif
  529.     {0, 0, 0, 0}
  530.   };
  531.  
  532. #ifdef ROUTETHROUGHTEST
  533.   /* Routethrough stuff -- kill later */
  534.   {
  535.     char *dev;
  536.     struct in_addr dest;
  537.     struct in_addr source;
  538.     if (!resolve(argv[1], &dest))
  539.       fatal("Failed to resolve %s\n", argv[1]);
  540.     dev = routethrough(&dest, &source);
  541.     if (dev)
  542.       log_write(LOG_STDOUT, "%s routes through device %s using IP address %s\n", argv[1], dev, inet_ntoa(source));
  543.     else log_write(LOG_STDOUT, "Could not determine which device to route through for %s!!!\n", argv[1]);
  544.  
  545.     exit(0);
  546.   }
  547. #endif
  548.  
  549.   /* argv faking silliness */
  550.   fakeargv = (char **) safe_malloc(sizeof(char *) * (argc + 1));
  551.   for(i=0; i < argc; i++) {
  552.     fakeargv[i] = strdup(argv[i]);
  553.   }
  554.   fakeargv[argc] = NULL;
  555.  
  556.   emptystring[0] = '\0'; /* It wouldn't be an emptystring w/o this ;) */
  557.  
  558.   if (argc < 2 ) printusage(argv[0], -1);
  559.  
  560.   /* OK, lets parse these args! */
  561.   optind = 1; /* so it can be called multiple times */
  562.   while((arg = getopt_long_only(argc,fakeargv,"b:D:d::e:Ffg:hIi:M:m:NnOo:P:p:qRrS:s:T:Vv", long_options, &option_index)) != EOF) {
  563.     switch(arg) {
  564.     case 0:
  565.       if (strcmp(long_options[option_index].name, "max_rtt_timeout") == 0) {
  566.     o.max_rtt_timeout = atoi(optarg);
  567.     if (o.max_rtt_timeout <= 5) {
  568.       fatal("max_rtt_timeout is given in milliseconds and must be at least 5");
  569.     }       
  570.         if (o.max_rtt_timeout < 20) {
  571.       error("WARNING: You specified a round-trip time timeout (%d ms) that is EXTRAORDINARILY SMALL.  Accuracy may suffer.", o.max_rtt_timeout);
  572.     }
  573.     if ( o.initial_rtt_timeout > o.max_rtt_timeout)
  574.       o.initial_rtt_timeout = o.max_rtt_timeout;
  575.       } else if (strcmp(long_options[option_index].name, "min_rtt_timeout") == 0) {
  576.     o.min_rtt_timeout = atoi(optarg);
  577.     if (o.min_rtt_timeout > 50000) {
  578.       fatal("Warning:  o.min_rtt_timeout is given in milliseconds, your value seems pretty large.");
  579.     }
  580.       } else if (strcmp(long_options[option_index].name, "host_timeout") == 0) {
  581.     o.host_timeout = strtoul(optarg, NULL, 10);
  582.     if (o.host_timeout <= 200) {
  583.       fatal("host_timeout is given in milliseconds and must be greater than 200");
  584.     }
  585. #ifdef WIN32
  586.       } else if (strcmp(long_options[option_index].name, "win_list_interfaces") == 0 ) { 
  587.     wo.listinterfaces = 1; 
  588.       } else if (strcmp(long_options[option_index].name, "win_norawsock") == 0 ) { 
  589.     wo.norawsock = 1; 
  590.       } else if (strcmp(long_options[option_index].name, "win_forcerawsock") == 0 ) { 
  591.     wo.forcerawsock = 1; 
  592.       } else if (strcmp(long_options[option_index].name, "win_nopcap") == 0 ) { 
  593.     wo.nopcap = 1; 
  594.       } else if (strcmp(long_options[option_index].name, "win_nt4route") == 0 ) { 
  595.     wo.nt4route = 1; 
  596.       } else if (strcmp(long_options[option_index].name, "win_noiphlpapi") == 0 ) { 
  597.     wo.noiphlpapi = 1; 
  598.       } else if (strcmp(long_options[option_index].name, "win_trace") == 0 ) { 
  599.     wo.trace++; 
  600.       } else if (strcmp(long_options[option_index].name, "win_help") == 0 ) { 
  601.     printf("Windows-specific options:\n\n"); 
  602.     printf(" --win_list_interfaces : list all network interfaces\n"); 
  603.     printf(" --win_norawsock       : disable raw socket support\n"); 
  604.     printf(" --win_forcerawsock    : try raw sockets even on non-W2K systems\n"); 
  605.     printf(" --win_nopcap          : disable winpcap support\n"); 
  606.     printf(" --win_nt4route        : test nt4 route code\n"); 
  607.     printf(" --win_noiphlpapi      : test response to lack of iphlpapi.dll\n"); 
  608.     printf(" --win_trace           : trace through raw IP initialization\n");
  609.     exit(0);
  610. #endif
  611.       } else if (strcmp(long_options[option_index].name, "append_output") == 0) {
  612.     o.append_output = 1;
  613.       } else if (strcmp(long_options[option_index].name, "noninteractive") == 0) {
  614.     /* Do nothing */
  615.       } else if (strcmp(long_options[option_index].name, "scan_delay") == 0) {
  616.     o.scan_delay = atoi(optarg);
  617.     if (o.scan_delay <= 0) {
  618.       fatal("scan_delay must be greater than 0");
  619.     }   
  620.     o.max_parallelism = 1;
  621.       } else if (strcmp(long_options[option_index].name, "randomize_hosts") == 0
  622.          || strcmp(long_options[option_index].name, "rH") == 0) {
  623.     o.randomize_hosts = 1;
  624.     o.host_group_sz = 2048;
  625.       } else if (strcmp(long_options[option_index].name, "osscan_limit")  == 0) {
  626.     o.osscan_limit = 1;
  627.       } else if (strcmp(long_options[option_index].name, "osscan_guess")  == 0) {
  628.     o.osscan_guess = 1;
  629.       } else if (strcmp(long_options[option_index].name, "initial_rtt_timeout") == 0) {
  630.     o.initial_rtt_timeout = atoi(optarg);
  631.     if (o.initial_rtt_timeout <= 0) {
  632.       fatal("initial_rtt_timeout must be greater than 0");
  633.     }
  634.       } else if (strcmp(long_options[option_index].name, "data_length") == 0) {
  635.     o.extra_payload_length = atoi(optarg);
  636.     if (o.extra_payload_length < 0) {
  637.       fatal("data_length must be greater than 0");
  638.     } else if (o.extra_payload_length > 0) {
  639.       o.extra_payload = (char *) safe_malloc(o.extra_payload_length);
  640.       get_random_bytes(o.extra_payload, o.extra_payload_length);
  641.     }
  642.       } else if (strcmp(long_options[option_index].name, "oN") == 0) {
  643.     normalfilename = optarg;
  644.       } else if (strcmp(long_options[option_index].name, "oG") == 0 ||
  645.          strcmp(long_options[option_index].name, "oM") == 0) {
  646.     machinefilename = optarg;
  647.       } else if (strcmp(long_options[option_index].name, "oS") == 0) {
  648.     kiddiefilename = optarg;
  649.       } else if (strcmp(long_options[option_index].name, "oH") == 0) {
  650.     fatal("HTML output is not yet supported");
  651.       } else if (strcmp(long_options[option_index].name, "oX") == 0) {
  652.     xmlfilename = optarg;
  653.       } else if (strcmp(long_options[option_index].name, "oA") == 0) {
  654.     char buf[MAXPATHLEN];
  655.     snprintf(buf, sizeof(buf), "%s.nmap", optarg);
  656.     normalfilename = strdup(buf);
  657.     snprintf(buf, sizeof(buf), "%s.gnmap", optarg);
  658.     machinefilename = strdup(buf);
  659.     snprintf(buf, sizeof(buf), "%s.xml", optarg);
  660.     xmlfilename = strdup(buf);
  661.       }
  662.       else if (strcmp(long_options[option_index].name, "iL") == 0) {
  663.     if (inputfd) {
  664.       fatal("Only one input filename allowed");
  665.     }
  666.     if (!strcmp(optarg, "-")) {
  667.       inputfd = stdin;
  668.       log_write(LOG_STDOUT, "Reading target specifications from stdin\n");
  669.     } else {    
  670.       inputfd = fopen(optarg, "r");
  671.       if (!inputfd) {
  672.         fatal("Failed to open input file %s for reading", optarg);
  673.       }  
  674.       log_write(LOG_STDOUT, "Reading target specifications from FILE: %s\n", optarg);
  675.     }
  676.       } else if (strcmp(long_options[option_index].name, "iR") == 0) {
  677.     o.generate_random_ips = 1;
  678.       } else if (strcmp(long_options[option_index].name, "sI") == 0) {
  679.     o.idlescan = 1;
  680.     idleProxy = optarg;
  681.       } else if (strcmp(long_options[option_index].name, "vv") == 0) {
  682.     /* Compatability hack ... ugly */
  683.     o.verbose += 2;
  684.       } else {
  685.     fatal("Unknown long option (%s) given@#!$#$", long_options[option_index].name);
  686.       }
  687.       break;
  688.     case 'b': 
  689.       o.bouncescan++;
  690.       if (parse_bounce_argument(&ftp, optarg) < 0 ) {
  691.     fprintf(stderr, "Your argument to -b is fucked up. Use the normal url style:  user:pass@server:port or just use server and use default anon login\n  Use -h for help\n");
  692.       }
  693.       break;
  694.     case 'D':
  695.       p = optarg;
  696.       do {    
  697.     q = strchr(p, ',');
  698.     if (q) *q = '\0';
  699.     if (!strcasecmp(p, "me")) {
  700.       if (o.decoyturn != -1) 
  701.         fatal("Can only use 'ME' as a decoy once.\n");
  702.       o.decoyturn = o.numdecoys++;
  703.     } else {      
  704.       if (o.numdecoys >= MAX_DECOYS -1)
  705.         fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)");
  706.       if (resolve(p, &o.decoys[o.numdecoys])) {
  707.         o.numdecoys++;
  708.       } else {
  709.         fatal("Failed to resolve decoy host: %s (must be hostname or IP address", optarg);
  710.       }
  711.     }
  712.     if (q) {
  713.       *q = ',';
  714.       p = q+1;
  715.     }
  716.       } while(q);
  717.       break;
  718.     case 'd': 
  719.       if (optarg)
  720.     o.debugging = o.verbose = atoi(optarg);
  721.       else {
  722.     o.debugging++; o.verbose++;
  723.       }
  724.       break;
  725.     case 'e': 
  726.       strncpy(o.device, optarg,63); o.device[63] = '\0'; break;
  727.     case 'F': fastscan++; break;
  728.     case 'f': o.fragscan++; break;
  729.     case 'g': 
  730.       o.magic_port = atoi(optarg);
  731.       o.magic_port_set = 1;
  732.       if (!o.magic_port) fatal("-g needs nonzero argument");
  733.       break;    
  734.     case 'h': printusage(argv[0], 0); break;
  735.     case '?': printusage(argv[0], -1); break;
  736.     case 'I': o.identscan++; break;
  737.     case 'i': 
  738.       if (inputfd) {
  739.     fatal("Only one input filename allowed");
  740.       }
  741.       if (!strcmp(optarg, "-")) {
  742.     inputfd = stdin;
  743.     log_write(LOG_STDOUT, "Reading target specifications from stdin\n");
  744.       } else {    
  745.     inputfd = fopen(optarg, "r");
  746.     if (!inputfd) {
  747.       fatal("Failed to open input file %s for reading", optarg);
  748.     }  
  749.     log_write(LOG_STDOUT, "Reading target specifications from FILE: %s\n", optarg);
  750.       }
  751.       break;  
  752.     case 'M': 
  753.       o.max_parallelism = atoi(optarg); 
  754.       if (o.max_parallelism < 1) fatal("Argument to -M must be at least 1!");
  755.       if (o.max_parallelism > MAX_SOCKETS_ALLOWED) {
  756.     fprintf(stderr, "Warning: You are limited to MAX_SOCKETS_ALLOWED (%d) parallel sockets.  If you really need more, change the #define and recompile.\n", MAX_SOCKETS_ALLOWED);
  757.     o.max_parallelism = MAX_SOCKETS_ALLOWED;
  758.       }
  759.       break;
  760.     case 'm': 
  761.       machinefilename = optarg;
  762.       break;
  763.     case 'N': o.force++; break;
  764.     case 'n': o.noresolve++; break;
  765.     case 'O': 
  766.       o.osscan++; 
  767.       o.reference_FPs = parse_fingerprint_reference_file();
  768.       break;
  769.     case 'o':
  770.       normalfilename = optarg;
  771.       break;
  772.     case 'P': 
  773.       if (*optarg == '\0' || *optarg == 'I')
  774.     o.pingtype |= PINGTYPE_ICMP;
  775.       else if (*optarg == '0' || *optarg == 'N' || *optarg == 'D')      
  776.     o.pingtype = PINGTYPE_NONE;
  777.       else if (*optarg == 'S') {
  778.     o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_SYN);
  779.     if (isdigit((int) *(optarg+1))) {      
  780.       o.tcp_probe_port = atoi(optarg+1);
  781.       log_write(LOG_STDOUT, "TCP probe port is %hu\n", o.tcp_probe_port);
  782.     } else if (o.verbose)
  783.       log_write(LOG_STDOUT, "TCP probe port is %hu\n", o.tcp_probe_port);
  784.       }
  785.       else if (*optarg == 'T' || *optarg == 'A') {
  786.     o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK);
  787.     if (isdigit((int) *(optarg+1))) {      
  788.       o.tcp_probe_port = atoi(optarg+1);
  789.       log_write(LOG_STDOUT, "TCP probe port is %hu\n", o.tcp_probe_port);
  790.     } else if (o.verbose)
  791.       log_write(LOG_STDOUT, "TCP probe port is %hu\n", o.tcp_probe_port);
  792.       }
  793.       else if (*optarg == 'B') {
  794.     o.pingtype = (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK|PINGTYPE_ICMP);
  795.     if (isdigit((int) *(optarg+1)))
  796.       o.tcp_probe_port = atoi(optarg+1);
  797.     log_write(LOG_STDOUT, "TCP probe port is %hu\n", o.tcp_probe_port);
  798.       }
  799.       else {fatal("Illegal Argument to -P, use -P0, -PI, -PT, or -PT80 (or whatever number you want for the TCP probe destination port)"); }
  800.       break;
  801.     case 'p': 
  802.       if (ports)
  803.     fatal("Only 1 -p option allowed, separate multiple ranges with commas.");
  804.       ports = getpts(optarg);
  805.       if (!ports)
  806.     fatal("Your port specification string is not parseable");
  807.       break;
  808.     case 'q': quashargv++; break;
  809.     case 'R': resolve_all++; break;
  810.     case 'r': 
  811.       randomize = 0;
  812.       break;
  813.     case 'S': 
  814.       if (o.spoofsource)
  815.     fatal("You can only use the source option once!  Use -D <decoy1> -D <decoy2> etc. for decoys\n");
  816.       o.source = (struct in_addr *) safe_malloc(sizeof(struct in_addr));
  817.       o.spoofsource = 1;
  818.       if (!resolve(optarg, o.source))
  819.     fatal("Failed to resolve source address, try dotted decimal IP address\n");
  820.       break;
  821.     case 's': 
  822.       if (!*optarg) {
  823.     fprintf(stderr, "An option is required for -s, most common are -sT (tcp scan), -sS (SYN scan), -sF (FIN scan), -sU (UDP scan) and -sP (Ping scan)");
  824.     printusage(argv[0], -1);
  825.       }
  826.       p = optarg;
  827.       while(*p) {
  828.     switch(*p) {
  829.     case 'A': o.ackscan = 1; break;
  830.     case 'B':  fatal("No scan type 'B', did you mean bounce scan (-b)?");
  831.       break;
  832.     case 'F':  o.finscan = 1; break;
  833.     case 'L':  o.listscan = 1; o.pingtype = PINGTYPE_NONE; break;
  834.     case 'M':  o.maimonscan = 1; break;
  835.     case 'N':  o.nullscan = 1; break;
  836.     case 'O':  o.ipprotscan = 1; break;
  837.     case 'P':  o.pingscan = 1; break;
  838.     case 'R':  o.rpcscan = 1; break;
  839.     case 'S':  o.synscan = 1; break;      
  840.     case 'W':  o.windowscan = 1; break;
  841.     case 'T':  o.connectscan = 1; break;
  842.     case 'U':  
  843.       o.udpscan++;
  844.       break;
  845.     case 'X':  o.xmasscan++;break;
  846.     default:  error("Scantype %c not supported\n",*p); printusage(argv[0], -1); break;
  847.     }
  848.     p++;
  849.       }
  850.       break;
  851.     case 'T':
  852.       if (*optarg == '0' || (strcasecmp(optarg, "Paranoid") == 0)) {
  853.     o.max_parallelism = 1;
  854.     o.scan_delay = 300000;
  855.     o.initial_rtt_timeout = 300000;
  856.       } else if (*optarg == '1' || (strcasecmp(optarg, "Sneaky") == 0)) {
  857.     o.max_parallelism = 1;
  858.     o.scan_delay = 15000;
  859.     o.initial_rtt_timeout = 15000;
  860.       } else if (*optarg == '2' || (strcasecmp(optarg, "Polite") == 0)) {
  861.     o.max_parallelism = 1;
  862.     o.scan_delay = 400;
  863.       } else if (*optarg == '3' || (strcasecmp(optarg, "Normal") == 0)) {
  864.       } else if (*optarg == '4' || (strcasecmp(optarg, "Aggressive") == 0)) {
  865.     o.max_rtt_timeout = 1250;
  866.     o.host_timeout = 300000;
  867.     o.initial_rtt_timeout = 1000;
  868.       } else if (*optarg == '5' || (strcasecmp(optarg, "Insane") == 0)) {
  869.     o.max_rtt_timeout = 300;
  870.     o.initial_rtt_timeout = 300;
  871.     o.host_timeout = 75000;
  872.       } else {
  873.     fatal("Unknown timing mode (-T argment).  Use either \"Paranoid\", \"Sneaky\", \"Polite\", \"Normal\", \"Aggressive\", \"Insane\" or a number from 0 (Paranoid) to 5 (Insane)");
  874.       }
  875.       break;
  876.     case 'V': 
  877.       printf("\nnmap V. %s\n", NMAP_VERSION); 
  878.       exit(0);
  879.       break;
  880.     case 'v': o.verbose++; break;
  881.     }
  882.   }
  883.  
  884. #ifdef WIN32
  885.   winip_postopt_init();
  886. #endif
  887.  
  888. #if HAVE_SIGNAL
  889.   if (!o.debugging)
  890.     signal(SIGSEGV, sigdie); 
  891. #endif
  892.  
  893.   if (o.pingtype == PINGTYPE_UNKNOWN) {
  894.     if (o.isr00t) o.pingtype = PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK|PINGTYPE_ICMP;
  895.     else o.pingtype = PINGTYPE_TCP;
  896.   }
  897.  
  898.   /* Open the log files, now that we know whether the user wants them appended
  899.      or overwritten */
  900.   if (normalfilename)
  901.     log_open(LOG_NORMAL, o.append_output, normalfilename);
  902.   if (machinefilename)
  903.     log_open(LOG_MACHINE, o.append_output, machinefilename);
  904.   if (kiddiefilename)
  905.     log_open(LOG_SKID, o.append_output, kiddiefilename);
  906.   if (xmlfilename)
  907.     log_open(LOG_XML, o.append_output, xmlfilename);
  908.  
  909.   if (!o.interactivemode)
  910.     log_write(LOG_STDOUT|LOG_SKID, "\nStarting %s V. %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
  911.  
  912.   /* Now we check the option sanity */
  913.   /* Insure that at least one scantype is selected */
  914.   if (!o.connectscan && !o.udpscan && !o.synscan && !o.windowscan && !o.idlescan && !o.finscan && !o.maimonscan &&  !o.nullscan && !o.xmasscan && !o.ackscan && !o.bouncescan && !o.pingscan && !o.ipprotscan && !o.listscan) {
  915.     o.connectscan++;
  916.     if (o.verbose) error("No tcp,udp, or ICMP scantype specified, assuming vanilla tcp connect() scan. Use -sP if you really don't want to portscan (and just want to see what hosts are up).");
  917.   }
  918.  
  919.   if (o.pingtype != PINGTYPE_NONE && o.spoofsource) {
  920.     error("WARNING:  If -S is being used to fake your source address, you may also have to use -e <iface> and -P0 .  If you are using it to specify your real source address, you can ignore this warning.");
  921.   }
  922.  
  923.   if (o.pingtype != PINGTYPE_NONE && o.idlescan) {
  924.     error("WARNING: Many people use -P0 w/Idlescan to prevent pings from your true IP");
  925.     sleep(1); /* Give ppl a chance for ^C :) */
  926.   }
  927.  
  928.   if (o.numdecoys > 1 && o.idlescan) {
  929.     error("WARNING: Your decoys won't be used in the Idlescan portion of your scanning (although all packets sent to the target are spoofed anyway");
  930.   }
  931.  
  932.   if (o.connectscan && o.spoofsource) {
  933.     error("WARNING:  -S will not affect the source address used in a connect() scan.  Use -sS or another raw scan if you want to use the specified source address for the port scanning stage of nmap");
  934.   }
  935.  
  936.  
  937.   if (o.ipprotscan && (o.connectscan | o.windowscan | o.synscan | o.finscan | o.maimonscan | o.xmasscan | o.nullscan | o.ackscan | o.udpscan | o.idlescan )) {
  938.   /* It's no longer the case that the reason this doesn't work is due to port
  939.    * list conflicts. Port ranges and protocol ranges could be specified on
  940.    * the command line. Right now though, the main issue is with conflicting
  941.    * port vs protocol scan output (in particular, -oG output format would have
  942.    * to be updated). 
  943.    *
  944.    * if (!ports)
  945.    *   fatal("Sorry, IP protocol scan can only be used with other scan types if port ranges and protocol ranges are specified on command line with -p\n");
  946.    */
  947.      fatal("Sorry, IP protocol scan can not be used with other scan types for now");
  948.    }
  949.  
  950.   if (fastscan && ports) {
  951.     fatal("You can specify fast scan (-F) or explicitly select individual ports (-p), but not both");
  952.   } else if (fastscan && o.ipprotscan) {
  953.     ports = getfastprots();
  954.   } else if (fastscan) {
  955.     ports = getfastports(o.windowscan|o.synscan|o.connectscan|o.fragscan|o.idlescan|o.finscan|o.maimonscan|o.bouncescan|o.nullscan|o.xmasscan|o.ackscan,o.udpscan);
  956.   }
  957.  
  958.  
  959.   if ((o.pingscan || o.listscan) && ports) {
  960.     fatal("You cannot use -F (fast scan) or -p (explicit port selection) with PING scan or LIST scan");
  961.   }
  962.  
  963.   if ((o.pingscan || o.listscan) && fastscan) {
  964.     fatal("The fast scan (-F) is incompatible with ping scan");
  965.   }
  966.  
  967.   if ((o.pingscan && o.pingtype == PINGTYPE_NONE)) {
  968.     fatal("-P0 (skip ping) is incompatable with -sP (ping scan).  If you only want to enumerate hosts, try list scan (-sL)");
  969.   }
  970.  
  971.   if (!ports) {
  972.     if (o.ipprotscan) {
  973.       ports = getdefaultprots();
  974.     } else {
  975.       ports = getdefaultports(o.windowscan|o.synscan|o.connectscan|o.fragscan|o.idlescan|o.finscan|
  976.                   o.maimonscan|o.bouncescan|o.nullscan|o.xmasscan|o.ackscan,
  977.                   o.udpscan);
  978.     }
  979.   }
  980.  
  981.   /* By now, we've got our port lists.  Give the user a warning if no 
  982.    * ports are specified for the type of scan being requested.  Other things
  983.    * (such as OS ident scan) might break cause no ports were specified,  but
  984.    * we've given our warning...
  985.    */
  986.   if ((o.windowscan|o.synscan|o.connectscan|o.fragscan|o.finscan|o.maimonscan|o.bouncescan|o.nullscan|o.xmasscan|o.ackscan|o.idlescan) && ! ports->tcp_count)
  987.     error("WARNING: a TCP scan type was requested, but no tcp ports were specified.  Skipping this scan type.");
  988.   if (o.udpscan && ! ports->udp_count)
  989.     error("WARNING: UDP scan was requested, but no udp ports were specified.  Skipping this scan type.");
  990.   if (o.ipprotscan && ! ports->prot_count)
  991.     error("WARNING: protocol scan was requested, but no protocols were specified to be scanned.  Skipping this scan type.");
  992.  
  993.   /* Default dest port for tcp probe */
  994.   if (!o.tcp_probe_port) o.tcp_probe_port = DEFAULT_TCP_PROBE_PORT;
  995.  
  996.  
  997.   if (o.pingscan && (o.connectscan || o.udpscan || o.windowscan || o.synscan || o.idlescan || o.finscan || o.maimonscan ||  o.nullscan || o.xmasscan || o.ackscan || o.bouncescan || o.ipprotscan || o.listscan)) {
  998.     fatal("Ping scan is not valid with any other scan types (the other ones all include a ping scan");
  999.   }
  1000.  
  1001.   if (o.listscan && (o.connectscan || o.udpscan || o.windowscan || o.synscan || o.idlescan || o.finscan || o.maimonscan ||  o.nullscan || o.xmasscan || o.ackscan || o.bouncescan || o.pingscan)) {
  1002.     fatal("List scan is not valid with any other scan types (it just lists the hosts that WOULD be scanned)");
  1003.   }
  1004.  
  1005.  
  1006.   /* We start with stuff users should not do if they are not root */
  1007.   if (!o.isr00t) {
  1008.  
  1009. #ifndef WIN32    /*    Win32 has perfectly fine ICMP socket support */
  1010.     if (o.pingtype & PINGTYPE_ICMP) {
  1011.       error("Warning:  You are not root -- using TCP pingscan rather than ICMP");
  1012.       o.pingtype = PINGTYPE_TCP;
  1013.     }
  1014. #endif
  1015.  
  1016.     if (o.idlescan || o.finscan || o.windowscan || o.synscan || o.maimonscan || o.nullscan || o.xmasscan || o.ackscan
  1017.     || o.udpscan || o.ipprotscan) {
  1018. #ifndef WIN32
  1019.       fatal("You requested a scan type which requires r00t privileges, and you do not have them.\n");
  1020. #else
  1021.       winip_barf(0);
  1022. #endif
  1023.     }
  1024.   
  1025.     if (o.numdecoys > 0) {
  1026. #ifndef WIN32
  1027.       fatal("Sorry, but you've got to be r00t to use decoys, boy!");
  1028. #else
  1029.       winip_barf(0);
  1030. #endif
  1031.     }
  1032.   
  1033.     if (o.fragscan) {
  1034. #ifndef WIN32
  1035.       fatal("Sorry, but fragscan requires r00t privileges\n");
  1036. #else
  1037.       winip_barf(0);
  1038. #endif
  1039.     }
  1040.  
  1041.     if (o.osscan) {
  1042. #ifndef WIN32
  1043.       fatal("TCP/IP fingerprinting (for OS scan) requires root privileges which you do not appear to possess.  Sorry, dude.\n");
  1044. #else
  1045.       winip_barf(0);
  1046. #endif
  1047.     }
  1048.   }
  1049.  
  1050.   if (o.numdecoys > 0 && o.rpcscan) {
  1051.     error("WARNING:  RPC scan currently does not make use of decoys so don't count on that protection");
  1052.   }
  1053.  
  1054.   if (o.bouncescan && o.pingtype != PINGTYPE_NONE) 
  1055.     log_write(LOG_STDOUT, "Hint: if your bounce scan target hosts aren't reachable from here, remember to use -P0 so we don't try and ping them prior to the scan\n");
  1056.  
  1057.   if (o.connectscan + o.windowscan + o.synscan + o.finscan + o.idlescan + o.maimonscan + o.xmasscan + o.nullscan + o.ackscan  > 1) {
  1058.     fatal("You specified more than one type of TCP scan.  Please choose only one of -sT, -sS, -sF, -sM, -sX, -sA, -sW, and -sN");
  1059.   }
  1060.  
  1061.   if (o.numdecoys > 0 && (o.bouncescan || o.connectscan)) {
  1062.     fatal("Decoys are irrelevant to the bounce or connect scans");
  1063.   }
  1064.  
  1065.   if (o.fragscan && (o.connectscan || 
  1066.              ((o.udpscan || o.ipprotscan) &&
  1067.               (o.windowscan + o.synscan + o.finscan + o.maimonscan + 
  1068.                o.xmasscan + o.ackscan + o.nullscan == 0))))
  1069.     fatal("Fragmentation scan can only be used with SYN, FIN, Maimon, XMAS, ACK, or NULL scan types");
  1070.  
  1071.   if (o.identscan && !o.connectscan) {
  1072.     error("Identscan only works with connect scan (-sT) ... ignoring option");
  1073.     o.identscan = 0;
  1074.   }
  1075.  
  1076.   if (o.osscan && o.bouncescan)
  1077.     error("Combining bounce scan with OS scan seems silly, but I will let you do whatever you want!");
  1078.  
  1079. #if !defined(LINUX) && !defined(OPENBSD) && !defined(FREEBSD) && !defined(NETBSD)
  1080.   if (o.fragscan) {
  1081.     fprintf(stderr, "Warning: Packet fragmentation selected on a host other than Linux, OpenBSD, FreeBSD, or NetBSD.  This may or may not work.\n");
  1082.   }
  1083. #endif
  1084.  
  1085.   if (o.max_parallelism > MAX_SOCKETS_ALLOWED) {
  1086.     error("Warning: You are limited to MAX_SOCKETS_ALLOWED (%d) parallel sockets.  If you really need more, change the #define and recompile.\n", MAX_SOCKETS_ALLOWED);
  1087.     o.max_parallelism = MAX_SOCKETS_ALLOWED;
  1088.   }
  1089.  
  1090.   if (o.osscan && o.pingscan) {
  1091.     fatal("WARNING:  OS Scan is unreliable with a ping scan.  You need to use a scan type along with it, such as -sS, -sT, -sF, etc instead of -sP");
  1092.   }
  1093.  
  1094.   if (o.magic_port_set && o.connectscan) {
  1095.     error("WARNING:  -g is incompatible with the default connect() scan (-sT).  Use a raw scan such as -sS if you want to set the source port.");
  1096.   }
  1097.  
  1098.   /* Set up our array of decoys! */
  1099.   if (o.decoyturn == -1) {
  1100.     o.decoyturn = (o.numdecoys == 0)?  0 : get_random_uint() % o.numdecoys; 
  1101.     o.numdecoys++;
  1102.     for(i=o.numdecoys-1; i > o.decoyturn; i--)
  1103.       o.decoys[i] = o.decoys[i-1];
  1104.   }
  1105.  
  1106.   /* We need to find what interface to route through if:
  1107.    * --None have been specified AND
  1108.    * --We are root and doing tcp ping OR
  1109.    * --We are doing a raw sock scan and NOT pinging anyone */
  1110.   if (o.source && !*o.device) {
  1111.     if (ipaddr2devname(o.device, o.source) != 0) {
  1112.       fatal("Could not figure out what device to send the packet out on with the source address you gave me!  If you are trying to sp00f your scan, this is normal, just give the -e eth0 or -e ppp0 or whatever.  Otherwise you can still use -e, but I find it kindof fishy.");
  1113.     }
  1114.   }
  1115.  
  1116.   if (*o.device && !o.source) {
  1117.     o.source = (struct in_addr *) safe_malloc(sizeof(struct in_addr)); 
  1118.     if (devname2ipaddr(o.device, o.source) == -1) {
  1119.       fatal("I cannot figure out what source address to use for device %s, does it even exist?", o.device);
  1120.     }
  1121.   }
  1122.  
  1123.  
  1124.   /* If he wants to bounce off of an ftp site, that site better damn well be reachable! */
  1125.   if (o.bouncescan) {
  1126.     if (!inet_aton(ftp.server_name, &ftp.server)) {
  1127.       if ((target = gethostbyname(ftp.server_name)))
  1128.     memcpy(&ftp.server, target->h_addr_list[0], 4);
  1129.       else {
  1130.     fprintf(stderr, "Failed to resolve ftp bounce proxy hostname/IP: %s\n",
  1131.         ftp.server_name);
  1132.     exit(1);
  1133.       } 
  1134.     }  else if (o.verbose)
  1135.       log_write(LOG_STDOUT, "Resolved ftp bounce attack proxy to %s (%s).\n", 
  1136.         ftp.server_name, inet_ntoa(ftp.server)); 
  1137.   }
  1138.   fflush(stdout);
  1139.  
  1140.   timep = time(NULL);
  1141.   
  1142.   /* Brief info incase they forget what was scanned */
  1143.   Strncpy(mytime, ctime(&timep), sizeof(mytime));
  1144.   chomp(mytime);
  1145.   log_write(LOG_XML, "<?xml version=\"1.0\" ?>\n<!-- ");
  1146.   log_write(LOG_NORMAL|LOG_MACHINE, "# ");
  1147.   log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML, "%s (V. %s) scan initiated %s as: ", NMAP_NAME, NMAP_VERSION, mytime);
  1148.   
  1149.  
  1150.   for(i=0; i < argc; i++) {
  1151.     char *p = xml_convert(fakeargv[i]);
  1152.     log_write(LOG_XML,"%s ", p);
  1153.     free(p);
  1154.     log_write(LOG_NORMAL|LOG_MACHINE,"%s ", fakeargv[i]);
  1155.   }
  1156.   log_write(LOG_XML, "-->");
  1157.   log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML,"\n");  
  1158.  
  1159.   log_write(LOG_XML, "<nmaprun scanner=\"nmap\" args=\"");
  1160.   for(i=0; i < argc; i++) 
  1161.     log_write(LOG_XML, (i == argc-1)? "%s\" " : "%s ", fakeargv[i]);
  1162.  
  1163.   log_write(LOG_XML, "start=\"%d\" version=\"%s\" xmloutputversion=\"1.0\">\n",
  1164.         timep, NMAP_VERSION);
  1165.  
  1166.   output_xml_scaninfo_records(ports);
  1167.  
  1168.   log_write(LOG_XML, "<verbose level=\"%d\" />\n<debugging level=\"%d\" />\n",
  1169.         o.verbose, o.debugging);
  1170.  
  1171.   /* Before we randomize the ports scanned, lets output them to machine 
  1172.      parseable output */
  1173.   if (o.verbose)
  1174.      output_ports_to_machine_parseable_output(ports, o.windowscan|o.synscan|o.connectscan|o.fragscan|o.finscan|o.maimonscan|o.bouncescan|o.nullscan|o.xmasscan|o.ackscan|o.idlescan,o.udpscan,o.ipprotscan);
  1175.  
  1176.   /* more fakeargv junk, BTW malloc'ing extra space in argv[0] doesn't work */
  1177.   if (quashargv) {
  1178.     argvlen = strlen(argv[0]);
  1179.     if (argvlen < strlen(FAKE_ARGV))
  1180.       fatal("If you want me to fake your argv, you need to call the program with a longer name.  Try the full pathname, or rename it fyodorssuperdedouperportscanner");
  1181.     strncpy(argv[0], FAKE_ARGV, strlen(FAKE_ARGV));
  1182.     for(j = strlen(FAKE_ARGV); j < argvlen; j++) argv[0][j] = '\0';
  1183.     for(i=1; i < argc; i++) {
  1184.       argvlen = strlen(argv[i]);
  1185.       for(j=0; j <= argvlen; j++)
  1186.     argv[i][j] = '\0';
  1187.     }
  1188.   }
  1189.  
  1190. #if HAVE_SIGNAL
  1191.   signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
  1192.                    of it, but we really shouldn't get an unsuspected
  1193.                    SIGPIPE */
  1194. #endif
  1195.  
  1196.   if (o.max_parallelism && (i = max_sd()) && i < o.max_parallelism) {
  1197.     fprintf(stderr, "WARNING:  Your specified max_parallel_sockets of %d, but your system says it might only give us %d.  Trying anyway\n", o.max_parallelism, i);
  1198.   }
  1199.  
  1200.   if (o.debugging > 1) log_write(LOG_STDOUT, "The max # of sockets we are using is: %d\n", o.max_parallelism);
  1201.  
  1202.  
  1203.   if  (randomize) {
  1204.     if (ports->tcp_count) 
  1205.         shortfry(ports->tcp_ports, ports->tcp_count); 
  1206.     if (ports->udp_count) 
  1207.         shortfry(ports->udp_ports, ports->udp_count); 
  1208.     if (ports->prot_count) 
  1209.         shortfry(ports->prots, ports->prot_count); 
  1210.   }
  1211.  
  1212.   starttime = time(NULL);
  1213.  
  1214.   /* Time to create a hostgroup state object filled with all the requested
  1215.      machines */
  1216.   host_exp_group = (char **) safe_malloc(o.host_group_sz * sizeof(char *));
  1217.  
  1218.   while(1) {
  1219.     while(num_host_exp_groups < o.host_group_sz &&
  1220.       (host_spec = grab_next_host_spec(inputfd, argc, fakeargv))) {
  1221.       host_exp_group[num_host_exp_groups++] = strdup(host_spec);
  1222.     }
  1223.     if (num_host_exp_groups == 0)
  1224.       break;
  1225.  
  1226.     hostgroup_state_init(&hstate, o.host_group_sz, o.randomize_hosts, 
  1227.              host_exp_group, num_host_exp_groups);
  1228.   
  1229.     while((currenths = nexthost(&hstate, ports))) {
  1230.       numhosts_scanned++;
  1231.       if (currenths->flags & HOST_UP && !o.listscan) 
  1232.     numhosts_up++;
  1233.       
  1234.       /* Set timeout info */
  1235.       currenths->timedout = 0;
  1236.       if (o.host_timeout) {
  1237.     gettimeofday(¤ths->host_timeout, NULL);
  1238.     
  1239.     /* Must go through all this to avoid int overflow */
  1240.     currenths->host_timeout.tv_sec += o.host_timeout / 1000;
  1241.     currenths->host_timeout.tv_usec += (o.host_timeout % 1000) * 1000;
  1242.     currenths->host_timeout.tv_sec += currenths->host_timeout.tv_usec / 1000000;
  1243.     currenths->host_timeout.tv_usec %= 1000000;
  1244.       }
  1245.       
  1246.       /*    printf("Nexthost() returned: %s\n", inet_ntoa(currenths->host));*/
  1247.       target = NULL;
  1248.       if (((currenths->flags & HOST_UP) || resolve_all) && !o.noresolve)
  1249.     target = gethostbyaddr((char *) ¤ths->host, 4, AF_INET);
  1250.       if (target && *target->h_name) {
  1251.     currenths->name = strdup(target->h_name);
  1252.       }
  1253.       else {
  1254.     currenths->name = emptystring;
  1255.       }
  1256.       
  1257.       if (o.source) memcpy(¤ths->source_ip, o.source, sizeof(struct in_addr));
  1258.       log_write(LOG_XML, "<host>");
  1259.       write_host_status(currenths, resolve_all);
  1260.       
  1261.       /* The !currenths->wierd_responses was commented out after I found
  1262.      a smurf address which DID allow port scanninng and you could even
  1263.      telnetthere.  wierd :0 
  1264.      IGNORE THAT COMMENT!  The check is back again ... for now 
  1265.      NOPE -- gone again */
  1266.       
  1267.       if (currenths->flags & HOST_UP /*&& !currenths->wierd_responses*/ &&
  1268.       !o.pingscan && !o.listscan) {
  1269.     
  1270.     if (currenths->flags & HOST_UP && !currenths->source_ip.s_addr && ( o.windowscan || o.synscan || o.idlescan || o.finscan || o.maimonscan || o.udpscan || o.nullscan || o.xmasscan || o.ackscan || o.ipprotscan )) {
  1271.       if (gethostname(myname, MAXHOSTNAMELEN) || 
  1272.           !(target = gethostbyname(myname)))
  1273.         fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n"); 
  1274.       memcpy(¤ths->source_ip, target->h_addr_list[0], sizeof(struct in_addr));
  1275.       if (! sourceaddrwarning) {
  1276.         fprintf(stderr, "WARNING:  We could not determine for sure which interface to use, so we are guessing %s .  If this is wrong, use -S <my_IP_address>.\n", inet_ntoa(currenths->source_ip));
  1277.         sourceaddrwarning = 1;
  1278.       }
  1279.     }
  1280.     
  1281.     /* Figure out what link-layer device (interface) to use (ie eth0, ppp0, etc) */
  1282.     if (!*currenths->device && currenths->flags & HOST_UP && (o.nullscan || o.xmasscan || o.ackscan || o.udpscan || o.idlescan || o.finscan || o.maimonscan ||  o.synscan || o.osscan || o.windowscan || o.ipprotscan) && (ipaddr2devname( currenths->device, ¤ths->source_ip) != 0))
  1283.       fatal("Could not figure out what device to send the packet out on!  You might possibly want to try -S (but this is probably a bigger problem).  If you are trying to sp00f the source of a SYN/FIN scan with -S <fakeip>, then you must use -e eth0 (or other devicename) to tell us what interface to use.\n");
  1284.     /* Set up the decoy */
  1285.     o.decoys[o.decoyturn] = currenths->source_ip;
  1286.     
  1287.     /* Time for some actual scanning! */    
  1288.             /* Time for some actual scanning! */    
  1289.     if (o.synscan) pos_scan(currenths, ports->tcp_ports, ports->tcp_count, SYN_SCAN);
  1290.     if (o.windowscan) pos_scan(currenths, ports->tcp_ports, ports->tcp_count, WINDOW_SCAN);
  1291.     if (o.connectscan) pos_scan(currenths, ports->tcp_ports, ports->tcp_count, CONNECT_SCAN);
  1292.     if (o.ackscan) pos_scan(currenths, ports->tcp_ports, ports->tcp_count, ACK_SCAN); 
  1293.     if (o.finscan) super_scan(currenths, ports->tcp_ports, ports->tcp_count, FIN_SCAN);
  1294.     if (o.xmasscan) super_scan(currenths, ports->tcp_ports, ports->tcp_count, XMAS_SCAN);
  1295.     if (o.nullscan) super_scan(currenths, ports->tcp_ports, ports->tcp_count, NULL_SCAN);
  1296.     if (o.maimonscan) super_scan(currenths, ports->tcp_ports, 
  1297.                      ports->tcp_count, MAIMON_SCAN);
  1298.     if (o.udpscan) super_scan(currenths, ports->udp_ports, 
  1299.                   ports->udp_count, UDP_SCAN);
  1300.     if (o.ipprotscan) super_scan(currenths, ports->prots, 
  1301.                      ports->prot_count, IPPROT_SCAN);
  1302.  
  1303.     if (o.idlescan) idle_scan(currenths, ports->tcp_ports, 
  1304.                   ports->tcp_count, idleProxy);
  1305.  
  1306.     if (o.bouncescan) {
  1307.       if (ftp.sd <= 0) ftp_anon_connect(&ftp);
  1308.       if (ftp.sd > 0) bounce_scan(currenths, ports->tcp_ports, 
  1309.                       ports->tcp_count, &ftp);
  1310.     }
  1311.     
  1312.     /* This scantype must be after any TCP or UDP scans since it
  1313.      * get's it's port scan list from the open port list of the current
  1314.      * host rather than port list the user specified.
  1315.      */
  1316.     if (o.rpcscan)  pos_scan(currenths, NULL, 0, RPC_SCAN);
  1317.     
  1318.     
  1319.     if (o.osscan) {
  1320.       os_scan(currenths);
  1321.     }
  1322.     
  1323.     if (currenths->timedout) {
  1324.       log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT,"Skipping host  %s (%s) due to host timeout\n", currenths->name,
  1325.             inet_ntoa(currenths->host));
  1326.       log_write(LOG_MACHINE,"Host: %s (%s)\tStatus: Timeout", 
  1327.             inet_ntoa(currenths->host), currenths->name);
  1328.     } else {
  1329.       assignignoredportstate(¤ths->ports);
  1330.       printportoutput(currenths, ¤ths->ports);
  1331.       printosscanoutput(currenths);
  1332.      }      
  1333.  
  1334.     if (o.debugging) log_write(LOG_STDOUT, "Final times for host: srtt: %d rttvar: %d  to: %d\n", currenths->to.srtt, currenths->to.rttvar, currenths->to.timeout);
  1335.     log_write(LOG_MACHINE,"\n");
  1336.       }
  1337.       log_write(LOG_XML, "</host>\n");
  1338.   
  1339.       log_flush_all();
  1340.       hoststruct_free(currenths);
  1341.     }
  1342.  
  1343.     hostgroup_state_destroy(&hstate);
  1344.  
  1345.     /* Free my host expressions */
  1346.     for(i=0; i < num_host_exp_groups; i++)
  1347.       free(host_exp_group[i]);
  1348.     num_host_exp_groups = 0;
  1349.   }
  1350.  
  1351.   free(host_exp_group);
  1352.  
  1353.   printfinaloutput(numhosts_scanned, numhosts_up, starttime);
  1354.  
  1355.   /* Free fake argv */
  1356.   for(i=0; i < argc; i++)
  1357.     free(fakeargv[i]);
  1358.   free(fakeargv);
  1359.  
  1360.   return 0;
  1361. }
  1362.  
  1363.  
  1364. /* Reads in a (normal or machine format) Nmap log file and gathers enough
  1365.    state to allow Nmap to continue where it left off.  The important things
  1366.    it must gather are:
  1367.    1) The last host completed
  1368.    2) The command arguments
  1369. */
  1370.    
  1371. int gather_logfile_resumption_state(char *fname, int *myargc, char ***myargv) {
  1372. #ifndef __EMX__
  1373.   char *filestr;
  1374.   int filelen;
  1375.   char nmap_arg_buffer[1024];
  1376.   struct in_addr lastip;
  1377.   char *p, *q, *found; /* I love C! */
  1378.   /* We mmap it read/write since we will change the last char to a newline if it is not already */
  1379.   filestr = mmapfile(fname, &filelen, O_RDWR);
  1380.   if (!filestr) {
  1381.     fatal("Could not mmap() %s read/write", fname);
  1382.   }
  1383.  
  1384.   if (filelen < 20) {
  1385.     fatal("Output file %s is too short -- no use resuming", fname);
  1386.   }
  1387.  
  1388.   /* For now we terminate it with a NUL, but we will terminate the file with
  1389.      a '\n' later */
  1390.   filestr[filelen - 1] = '\0';
  1391.  
  1392.   /* First goal is to find the nmap args */
  1393.   p = strstr(filestr, " as: ");
  1394.   p += 5;
  1395.   while(*p && !isspace((int) *p))
  1396.     p++;
  1397.   if (!*p) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1398.   p++; /* Skip the space between program name and first arg */
  1399.   if (*p == '\n' || !*p) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1400.  
  1401.   q = strchr(p, '\n');
  1402.   if (!q || ((unsigned int) (q - p) >= sizeof(nmap_arg_buffer) - 32))
  1403.     fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1404.  
  1405.   strcpy(nmap_arg_buffer, "nmap --append_output ");
  1406.   memcpy(nmap_arg_buffer + 21, p, q-p);
  1407.   nmap_arg_buffer[21 + q-p] = '\0';
  1408.  
  1409.   *myargc = arg_parse(nmap_arg_buffer, myargv);
  1410.   if (*myargc == -1) {  
  1411.     fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1412.   }
  1413.      
  1414.   /* Now it is time to figure out the last IP that was scanned */
  1415.   q = p;
  1416.   found = NULL;
  1417.   /* Lets see if its a machine log first */
  1418.   while((q = strstr(q, "\nHost: ")))
  1419.     found = q = q + 7;
  1420.  
  1421.   if (found) {
  1422.     q = strchr(found, ' ');
  1423.     if (!q) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1424.     *q = '\0';
  1425.     if (inet_aton(found, &lastip) == 0)
  1426.       fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1427.     *q = ' ';
  1428.   } else {
  1429.     /* OK, I guess (hope) it is a normal log then */
  1430.     q = p;
  1431.     found = NULL;
  1432.     while((q = strstr(q, "\nInteresting ports on ")))
  1433.       found = q++;
  1434.  
  1435.     if (found) {    
  1436.       found = strchr(found, '(');
  1437.       if (!found) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1438.       found++;
  1439.       q = strchr(found, ')');
  1440.       if (!q) fatal("Unable to parse supposed log file %s.  Sorry", fname);
  1441.       *q = '\0';
  1442.       if (inet_aton(found, &lastip) == 0)
  1443.     fatal("Unable to parse ip (%s) supposed log file %s.  Sorry", found, fname);
  1444.       *q = ')';
  1445.     } else {
  1446.       error("Warning: You asked for --resume but it doesn't look like any hosts in the log file were successfully scanned.  Starting from the beginning.");
  1447.       lastip.s_addr = 0;
  1448.     }
  1449.   }
  1450.   o.resume_ip = lastip;
  1451.  
  1452.   /* Ensure the log file ends with a newline */
  1453.   filestr[filelen - 1] = '\n';
  1454.   munmap(filestr, filelen);
  1455. #endif
  1456.   return 0;
  1457. }
  1458.  
  1459. void options_init() {
  1460.  
  1461.   bzero( (char *) &o, sizeof(struct ops));
  1462. #ifndef WIN32
  1463.   o.isr00t = !(geteuid());
  1464. #else
  1465.   winip_init();    //    wrapper for all win32 initialization
  1466. #endif
  1467.   o.debugging = DEBUGGING;
  1468.   o.verbose = DEBUGGING;
  1469.   /*o.max_parallelism = MAX_SOCKETS;*/
  1470.   o.magic_port = 33000 + (get_random_uint() % 31000);
  1471.   o.pingtype = PINGTYPE_UNKNOWN;
  1472.   o.decoyturn = -1;
  1473.   o.nmap_stdout = stdout;
  1474.   o.host_group_sz = HOST_GROUP_SZ;
  1475.   o.min_rtt_timeout = MIN_RTT_TIMEOUT;
  1476.   o.max_rtt_timeout = MAX_RTT_TIMEOUT;
  1477.   o.initial_rtt_timeout = INITIAL_RTT_TIMEOUT;
  1478.   o.host_timeout = HOST_TIMEOUT;
  1479.   o.scan_delay = 0;
  1480.   o.extra_payload_length = 0;
  1481.   o.extra_payload = NULL;
  1482. }
  1483.  
  1484. /* We set the socket lingering so we will RST connection instead of wasting
  1485.    bandwidth with the four step close  */
  1486. void init_socket(int sd) {
  1487.   struct linger l;
  1488.   int res;
  1489.   static int bind_failed=0;
  1490.   struct sockaddr_in sin;
  1491.  
  1492.   l.l_onoff = 1;
  1493.   l.l_linger = 0;
  1494.  
  1495.   if (setsockopt(sd, SOL_SOCKET, SO_LINGER,  (const char *) &l, sizeof(struct linger)))
  1496.     {
  1497.       fprintf(stderr, "Problem setting socket SO_LINGER, errno: %d\n", errno);
  1498.       perror("setsockopt");
  1499.     }
  1500.   if (o.spoofsource && !bind_failed)
  1501.     {
  1502.       bzero(&sin,sizeof(sin));
  1503.       sin.sin_family=AF_INET;
  1504.       memcpy(&sin.sin_addr,o.source,sizeof(sin.sin_addr));
  1505.       res=bind(sd,(struct sockaddr*)&sin,sizeof(sin));
  1506.       if (res<0)
  1507.     {
  1508.       fprintf(stderr, "init_socket: Problem binding source address (%s), errno :%d\n", inet_ntoa(sin.sin_addr), errno);
  1509.       perror("bind");
  1510.       bind_failed=1;
  1511.     }
  1512.     }
  1513. }
  1514.  
  1515. /* Convert a string like "-100,200-1024,3000-4000,60000-" into an array 
  1516.    of port numbers. Note that one trailing comma is OK -- this is actually
  1517.    useful for machine generated lists */
  1518. struct scan_lists *getpts(char *origexpr) {
  1519.   u8 porttbl[65536];
  1520.   int portwarning = 0; /* have we warned idiot about dup ports yet? */
  1521.   long rangestart = -2343242, rangeend = -9324423;
  1522.   char *current_range;
  1523.   char *endptr;
  1524.   int i;
  1525.   int tcpportcount = 0, udpportcount = 0, protcount = 0;
  1526.   struct scan_lists *ports;
  1527.   int range_type = SCAN_TCP_PORT|SCAN_UDP_PORT|SCAN_PROTOCOLS;
  1528.  
  1529.   bzero(porttbl, sizeof(porttbl));
  1530.  
  1531.   current_range = origexpr;
  1532.   do {
  1533.     while(isspace((int) *current_range))
  1534.       current_range++; /* I don't know why I should allow spaces here, but I will */
  1535.     if (*current_range == 'T' && *++current_range == ':') {
  1536.     current_range++;
  1537.     range_type = SCAN_TCP_PORT;
  1538.     continue;
  1539.     }
  1540.     if (*current_range == 'U' && *++current_range == ':') {
  1541.     current_range++;
  1542.     range_type = SCAN_UDP_PORT;
  1543.     continue;
  1544.     }
  1545.     if (*current_range == 'P' && *++current_range == ':') {
  1546.     current_range++;
  1547.     range_type = SCAN_PROTOCOLS;
  1548.     continue;
  1549.     }
  1550.     if (*current_range == '-') {
  1551.       rangestart = 1;
  1552.     }
  1553.     else if (isdigit((int) *current_range)) {
  1554.       rangestart = strtol(current_range, &endptr, 10);
  1555.       if (rangestart <= 0 || rangestart > 65535) {
  1556.     fatal("Ports to be scanned must be between 1 and 65535 inclusive");
  1557.       }
  1558.       current_range = endptr;
  1559.       while(isspace((int) *current_range)) current_range++;
  1560.     } else {
  1561.       fatal("Error #485: Your port specifications are illegal.  Example of proper form: \"-100,200-1024,T:3000-4000,U:60000-\"");
  1562.     }
  1563.     /* Now I have a rangestart, time to go after rangeend */
  1564.     if (!*current_range || *current_range == ',') {
  1565.       /* Single port specification */
  1566.       rangeend = rangestart;
  1567.     } else if (*current_range == '-') {
  1568.       current_range++;
  1569.       if (!*current_range || *current_range == ',') {
  1570.     /* Ended with a -, meaning up until the last possible port */
  1571.     rangeend = 65535;
  1572.       } else if (isdigit((int) *current_range)) {
  1573.     rangeend = strtol(current_range, &endptr, 10);
  1574.     if (rangeend <= 0 || rangeend > 65535) {
  1575.       fatal("Ports to be scanned must be between 1 and 65535 inclusive");
  1576.     }
  1577.     current_range = endptr;
  1578.       } else {
  1579.     fatal("Error #486: Your port specifications are illegal.  Example of proper form: \"-100,200-1024,3000-4000,60000-\"");
  1580.       }
  1581.     } else {
  1582.     fatal("Error #487: Your port specifications are illegal.  Example of proper form: \"-100,200-1024,3000-4000,60000-\"");
  1583.     }
  1584.  
  1585.     /* Now I have a rangestart and a rangeend, so I can add these ports */
  1586.     while(rangestart <= rangeend) {
  1587.       if (porttbl[rangestart] & range_type) {
  1588.     if (!portwarning) {
  1589.       error("WARNING:  Duplicate port number(s) specified.  Are you alert enough to be using Nmap?  Have some coffee or Jolt(tm).");
  1590.       portwarning++;
  1591.     } 
  1592.       }
  1593.       if (range_type & SCAN_TCP_PORT)
  1594.     tcpportcount++;
  1595.       if (range_type & SCAN_UDP_PORT)
  1596.     udpportcount++;
  1597.       if (range_type & SCAN_PROTOCOLS)
  1598.     protcount++;
  1599.       porttbl[rangestart] |= range_type;
  1600.       rangestart++;
  1601.     }
  1602.     
  1603.     /* Find the next range */
  1604.     while(isspace((int) *current_range)) current_range++;
  1605.     if (*current_range && *current_range != ',') {
  1606.       fatal("Error #488: Your port specifications are illegal.  Example of proper form: \"-100,200-1024,3000-4000,60000-\"");
  1607.     }
  1608.     if (*current_range == ',')
  1609.       current_range++;
  1610.   } while(current_range && *current_range);
  1611.  
  1612.   if ( 0 == (tcpportcount + udpportcount + protcount))
  1613.     fatal("No ports specified -- If you really don't want to scan any ports use ping scan...");
  1614.  
  1615.   ports = (struct scan_lists *) safe_malloc(sizeof(struct scan_lists));
  1616.   bzero(ports, sizeof(ports));
  1617.   if (tcpportcount) {
  1618.     ports->tcp_ports = (unsigned short *)safe_malloc((tcpportcount + 1) * sizeof(unsigned short));
  1619.     bzero(ports->tcp_ports, (tcpportcount + 1) * sizeof(unsigned short));
  1620.   }
  1621.   if (udpportcount) {
  1622.     ports->udp_ports = (unsigned short *)safe_malloc((udpportcount + 1) * sizeof(unsigned short));
  1623.     bzero(ports->udp_ports, (udpportcount + 1) * sizeof(unsigned short));
  1624.   }
  1625.   if (protcount) {
  1626.     ports->prots = (unsigned short *)safe_malloc((protcount + 1) * sizeof(unsigned short));
  1627.     bzero(ports->prots, (protcount + 1) * sizeof(unsigned short));
  1628.   }
  1629.   ports->tcp_count = tcpportcount;
  1630.   ports->udp_count = udpportcount;
  1631.   ports->prot_count = protcount;
  1632.  
  1633.   tcpportcount=0;
  1634.   udpportcount=0;
  1635.   protcount=0;
  1636.   for(i=0; i <= 65535; i++) {
  1637.     if (porttbl[i] & SCAN_TCP_PORT)
  1638.       ports->tcp_ports[tcpportcount++] = i;
  1639.     if (porttbl[i] & SCAN_UDP_PORT)
  1640.       ports->udp_ports[udpportcount++] = i;
  1641.     if (porttbl[i] & SCAN_PROTOCOLS)
  1642.       ports->prots[protcount++] = i;
  1643.   }
  1644.  
  1645.   /* Someday I am going to make sure this isn't neccessary and then I
  1646.      will start allowing (invalid) port 0 scans */
  1647.   if (tcpportcount)
  1648.     ports->tcp_ports[ports->tcp_count] = 0; 
  1649.   if (udpportcount)
  1650.     ports->udp_ports[ports->udp_count] = 0; 
  1651.   if (protcount)
  1652.     ports->prots[ports->prot_count] = 0; 
  1653.   return ports;
  1654. }
  1655.  
  1656. void printusage(char *name, int rc) {
  1657. #ifdef WIN32
  1658. #define WIN32_PRINTF "  --win_help Windows-specific features\n"
  1659. #else
  1660. #define WIN32_PRINTF
  1661. #endif
  1662.   printf(
  1663.      "Nmap V. %s Usage: nmap [Scan Type(s)] [Options] <host or net list>\n"
  1664.      "Some Common Scan Types ('*' options require root privileges)\n"
  1665.      "  -sT TCP connect() port scan (default)\n"
  1666.      "* -sS TCP SYN stealth port scan (best all-around TCP scan)\n"
  1667.      "* -sU UDP port scan\n"
  1668.      "  -sP ping scan (Find any reachable machines)\n"
  1669.      "* -sF,-sX,-sN Stealth FIN, Xmas, or Null scan (experts only)\n"
  1670.      "  -sR/-I RPC/Identd scan (use with other scan types)\n"
  1671.      "Some Common Options (none are required, most can be combined):\n"
  1672.      "* -O Use TCP/IP fingerprinting to guess remote operating system\n"
  1673.      "  -p <range> ports to scan.  Example range: '1-1024,1080,6666,31337'\n"
  1674.      "  -F Only scans ports listed in nmap-services\n"
  1675.      "  -v Verbose. Its use is recommended.  Use twice for greater effect.\n"
  1676.      "  -P0 Don't ping hosts (needed to scan www.microsoft.com and others)\n"
  1677.      "* -Ddecoy_host1,decoy2[,...] Hide scan using many decoys\n"
  1678.      "  -T <Paranoid|Sneaky|Polite|Normal|Aggressive|Insane> General timing policy\n"
  1679.      "  -n/-R Never do DNS resolution/Always resolve [default: sometimes resolve]\n"
  1680.      "  -oN/-oX/-oG <logfile> Output normal/XML/grepable scan logs to <logfile>\n"
  1681.      "  -iL <inputfile> Get targets from file; Use '-' for stdin\n"
  1682.      "* -S <your_IP>/-e <devicename> Specify source address or network interface\n"
  1683.      "  --interactive Go into interactive mode (then press h for help)\n"
  1684.          WIN32_PRINTF
  1685.      "Example: nmap -v -sS -O www.my.com 192.168.0.0/16 '192.88-90.*.*'\n"
  1686.      "SEE THE MAN PAGE FOR MANY MORE OPTIONS, DESCRIPTIONS, AND EXAMPLES \n", NMAP_VERSION);
  1687.   exit(rc);
  1688. }
  1689.  
  1690. void printinteractiveusage() {
  1691.   printf(
  1692.      "Nmap Interactive Commands:\n\
  1693. n <nmap args> -- executes an nmap scan using the arguments given and\n\
  1694. waits for nmap to finish.  Results are printed to the\n\
  1695. screen (of course you can still use file output commands).\n\
  1696. ! <command>   -- runs shell command given in the foreground\n\
  1697. x             -- Exit Nmap\n\
  1698. f [--spoof <fakeargs>] [--nmap_path <path>] <nmap args>\n\
  1699. -- Executes nmap in the background (results are NOT\n\
  1700. printed to the screen).  You should generally specify a\n\
  1701. file for results (with -oX, -oG, or -oN).  If you specify\n\
  1702. fakeargs with --spoof, Nmap will try to make those\n\
  1703. appear in ps listings.  If you wish to execute a special\n\
  1704. version of Nmap, specify --nmap_path.\n\
  1705. n -h          -- Obtain help with Nmap syntax\n\
  1706. h             -- Prints this help screen.\n\
  1707. Examples:\n\
  1708. n -sS -O -v example.com/24\n\
  1709. f --spoof \"/usr/local/bin/pico -z hello.c\" -sS -oN /tmp/e.log example.com/24\n\n");
  1710. }
  1711.  
  1712. char *seqreport(struct seq_info *seq) {
  1713.   static char report[512];
  1714.   char tmp[256];
  1715.   char *p;
  1716.   int i;
  1717.  
  1718.   snprintf(report, sizeof(report), "TCP Sequence Prediction: Class=%s\n                         Difficulty=%d (%s)\n", seqclass2ascii(seq->seqclass), seq->index, seqidx2difficultystr(seq->index));
  1719.   if (o.verbose > 1 || o.debugging ) {
  1720.     p = tmp;
  1721.     strcpy(p, "TCP ISN Seq. Numbers: ");
  1722.     p += 22;
  1723.     for(i=0; i < seq->responses; i++) {
  1724.       if (p - tmp + 20 > (sizeof(tmp)))
  1725.     fatal("0verfl0w Error #234112");
  1726.       p += snprintf(p, 16, "%X ", seq->seqs[i]);
  1727.     }
  1728.     *--p = '\n';
  1729.     strcat(report, tmp);
  1730.   }
  1731.   return report;
  1732. }
  1733.  
  1734. /* Convert a TCP sequence prediction difficulty index like 1264386
  1735.    into a difficulty string like "Worthy Challenge */
  1736. const char *seqidx2difficultystr(unsigned long idx) {
  1737.   return  (idx < 10)? "Trivial joke" : (idx < 80)? "Easy" : (idx < 3000)? "Medium" : (idx < 5000)? "Formidable" : (idx < 100000)? "Worthy challenge" : "Good luck!";
  1738. }
  1739.  
  1740. char *seqclass2ascii(int seqclass) {
  1741.   switch(seqclass) {
  1742.   case SEQ_CONSTANT:
  1743.     return "constant sequence number (!)";
  1744.   case SEQ_64K:
  1745.     return "64K rule";
  1746.   case SEQ_TD:
  1747.     return "trivial time dependency";
  1748.   case SEQ_i800:
  1749.     return "increments by 800";
  1750.   case SEQ_RI:
  1751.     return "random positive increments";
  1752.   case SEQ_TR:
  1753.     return "truly random";
  1754.   case SEQ_UNKNOWN:
  1755.     return "unknown class";
  1756.   default:
  1757.     return "ERROR, WTF?";
  1758.   }
  1759. }
  1760.  
  1761. char *ipidclass2ascii(int seqclass) {
  1762.   switch(seqclass) {
  1763.   case IPID_SEQ_CONSTANT:
  1764.     return "Duplicated ipid (!)";
  1765.   case IPID_SEQ_INCR:
  1766.     return "Incremental";
  1767.   case IPID_SEQ_BROKEN_INCR:
  1768.     return "Broken little-endian incremental";
  1769.   case IPID_SEQ_RD:
  1770.     return "Randomized";
  1771.   case IPID_SEQ_RPI:
  1772.     return "Random positive increments";
  1773.   case IPID_SEQ_ZERO:
  1774.     return "All zeros";
  1775.   case IPID_SEQ_UNKNOWN:
  1776.     return "Busy server or unknown class";
  1777.   default:
  1778.     return "ERROR, WTF?";
  1779.   }
  1780. }
  1781.  
  1782. char *tsseqclass2ascii(int seqclass) {
  1783.   switch(seqclass) {
  1784.   case TS_SEQ_ZERO:
  1785.     return "zero timestamp";
  1786.   case TS_SEQ_2HZ:
  1787.     return "2HZ";
  1788.   case TS_SEQ_100HZ:
  1789.     return "100HZ";
  1790.   case TS_SEQ_1000HZ:
  1791.     return "1000HZ";
  1792.   case TS_SEQ_UNSUPPORTED:
  1793.     return "none returned (unsupported)";
  1794.   case TS_SEQ_UNKNOWN:
  1795.     return "unknown class";
  1796.   default:
  1797.     return "ERROR, WTF?";
  1798.   }
  1799. }
  1800.  
  1801.  
  1802. /**
  1803.  * Returns 1 if this is a reserved IP address, where "reserved" means
  1804.  * either a private address, non-routable address, or even a non-reserved
  1805.  * but unassigned address which has an extremely high probability of being
  1806.  * black-holed.
  1807.  *
  1808.  * We try to optimize speed when ordering the tests. This optimization
  1809.  * assumes that all byte values are equally likely in the input.
  1810.  *
  1811.  * Warning: This function could easily become outdated if the IANA
  1812.  * starts to assign some more IPv4 ranges to RIPE, etc. as they have
  1813.  * started doing this year (2001), for example 80.0.0.0/4 used to be
  1814.  * completely unassigned until they gave 80.0.0.0/7 to RIPE in April
  1815.  * 2001 (www.junk.org is an example of a new address in this range).
  1816.  *
  1817.  * Check <http://www.iana.org/assignments/ipv4-address-space> for
  1818.  * the most recent assigments.
  1819.  */
  1820.  
  1821. int ip_is_reserved(struct in_addr *ip)
  1822. {
  1823.   char *ipc = (char *) &(ip->s_addr);
  1824.   unsigned char i1 = ipc[0], i2 = ipc[1], i3 = ipc[2], i4 = ipc[3];
  1825.  
  1826.   /* 219-223/8 is IANA reserved */
  1827.   /* 224-239/8 is all multicast stuff */
  1828.   /* 240-255/8 is IANA reserved */
  1829.   if (i1 >= 219)
  1830.     return 1;
  1831.  
  1832.   /* 096-126/8 is IANA reserved */
  1833.   /* 127/8 is reserved for loopback */
  1834.   if (i1 >= 96 && i1 <= 127)
  1835.     return 1;
  1836.  
  1837.   /* 069-079/8 is IANA reserved */
  1838.   if (i1 >= 69 && i1 <= 79)
  1839.     return 1;
  1840.  
  1841.   /* 082-095/8 is IANA reserved */
  1842.   if (i1 >= 82 && i1 <= 95)
  1843.     return 1;
  1844.  
  1845.   /* do all the /7's and /8's with a big switch statement, hopefully the
  1846.    * compiler will be able to optimize this a little better using a jump table
  1847.    * or what have you
  1848.    */
  1849.   switch (i1)
  1850.     {
  1851.     case 0:         /* 000/8 is IANA reserved       */
  1852.     case 1:         /* 001/8 is IANA reserved       */
  1853.     case 2:         /* 002/8 is IANA reserved       */
  1854.     case 5:         /* 005/8 is IANA reserved       */
  1855.     case 6:         /* USA Army ISC                 */
  1856.     case 7:         /* used for BGP protocol        */
  1857.     case 10:        /* the infamous 10.0.0.0/8      */
  1858.     case 23:        /* 023/8 is IANA reserved       */
  1859.     case 27:        /* 027/8 is IANA reserved       */
  1860.     case 31:        /* 031/8 is IANA reserved       */
  1861.     case 36:        /* 036/8 is IANA reserved       */
  1862.     case 37:        /* 037/8 is IANA reserved       */
  1863.     case 39:        /* 039/8 is IANA reserved       */
  1864.     case 41:        /* 041/8 is IANA reserved       */
  1865.     case 42:        /* 042/8 is IANA reserved       */
  1866.     case 55:        /* misc. U.S.A. Armed forces    */
  1867.     case 58:        /* 058/8 is IANA reserved       */
  1868.     case 59:        /* 059/8 is IANA reserved       */
  1869.     case 60:        /* 060/8 is IANA reserved       */
  1870.     case 197:
  1871.       return 1;
  1872.     default:
  1873.       break;
  1874.     }
  1875.  
  1876.   /* 172.16.0.0/12 is reserved for private nets by RFC1819 */
  1877.   if (i1 == 172 && i2 >= 16 && i2 <= 31)
  1878.     return 1;
  1879.  
  1880.   /* 192.168.0.0/16 is reserved for private nets by RFC1819 */
  1881.   /* 192.0.2.0/24 is reserved for documentation and examples */
  1882.   if (i1 == 192) {
  1883.     if (i2 == 168)
  1884.       return 1;
  1885.     else if (i2 == 0 && i3 == 2)
  1886.       return 1;
  1887.   }
  1888.  
  1889.   /* reserved for DHCP clients seeking addresses, not routable outside LAN */
  1890.   if (i1 == 169 && i2 == 254)
  1891.     return 1;
  1892.  
  1893.   /* believe it or not, 204.152.64.0/23 is some bizarre Sun proprietary
  1894.    * clustering thing */
  1895.   if (i1 == 204 && i2 == 152 && (i3 == 64 || i3 == 65))
  1896.     return 1;
  1897.  
  1898.   /* 255.255.255.255, note we already tested for i1 in this range */
  1899.   if (i2 == 255 && i3 == 255 && i4 == 255)
  1900.     return 1;
  1901.  
  1902.   return 0;
  1903.  
  1904. }
  1905.  
  1906. char *grab_next_host_spec(FILE *inputfd, int argc, char **fakeargv) {
  1907.   static char host_spec[512];
  1908.   int host_spec_index;
  1909.   int ch;
  1910.   struct in_addr ip;
  1911.  
  1912.   if (o.generate_random_ips) {
  1913.     do {
  1914.       ip.s_addr = get_random_u32();
  1915.     } while (ip_is_reserved(&ip));
  1916.     strcpy(host_spec, inet_ntoa(ip));
  1917.   } else if (!inputfd) {
  1918.     return( (optind < argc)?  fakeargv[optind++] : NULL);
  1919.   } else { 
  1920.     host_spec_index = 0;
  1921.     while((ch = getc(inputfd)) != EOF) {
  1922.       if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\0') {
  1923.     if (host_spec_index == 0) continue;
  1924.     host_spec[host_spec_index] = '\0';
  1925.     return host_spec;
  1926.       } else if (host_spec_index < 511) {
  1927.     host_spec[host_spec_index++] = (char) ch;
  1928.       } else fatal("One of the host_specifications from your input file is too long (> %d chars)", sizeof(host_spec));
  1929.     }
  1930.     host_spec[host_spec_index] = '\0';
  1931.   }
  1932.   if (!*host_spec) return NULL;
  1933.   return host_spec;
  1934. }
  1935.  
  1936. /* Just a routine for obtaining a string for printing based on the scantype */
  1937. char *scantype2str(stype scantype) {
  1938.  
  1939.   switch(scantype) {
  1940.   case ACK_SCAN: return "ACK Scan"; break;
  1941.   case SYN_SCAN: return "SYN Stealth Scan"; break;
  1942.   case FIN_SCAN: return "FIN Scan"; break;
  1943.   case XMAS_SCAN: return "XMAS Scan"; break;
  1944.   case UDP_SCAN: return "UDP Scan"; break;
  1945.   case CONNECT_SCAN: return "Connect() Scan"; break;
  1946.   case NULL_SCAN: return "NULL Scan"; break;
  1947.   case WINDOW_SCAN: return "Window Scan"; break;
  1948.   case RPC_SCAN: return "RPCGrind Scan"; break;
  1949.   case MAIMON_SCAN: return "Maimon Scan"; break;
  1950.   case IPPROT_SCAN: return "IPProto Scan"; break;
  1951.   default: assert(0); break;
  1952.   }
  1953.  
  1954.   return NULL; /* Unreached */
  1955.  
  1956. }
  1957.  
  1958. char *statenum2str(int state) {
  1959.   switch(state) {
  1960.   case PORT_OPEN: return "open"; break;
  1961.   case PORT_FIREWALLED: return "filtered"; break;
  1962.   case PORT_UNFIREWALLED: return "UNfiltered"; break;
  1963.   case PORT_CLOSED: return "closed"; break;
  1964.   default: return "unknown"; break;
  1965.   }
  1966.   return "unknown";
  1967. }
  1968.  
  1969.  
  1970. /* Checks whether the identd port (113) is open on the target machine.  No
  1971.    sense wasting time trying it for each good port if it is down! */
  1972.  
  1973. int check_ident_port(struct in_addr target) {
  1974.   int sd;
  1975.   char buf[4096];
  1976.   struct sockaddr_in sock;
  1977.   int res;
  1978.   struct sockaddr_in stranger;
  1979.   NET_SIZE_T sockaddr_in_len = sizeof(struct sockaddr_in);
  1980.   fd_set fds_read, fds_write;
  1981.   struct timeval tv;
  1982.   tv.tv_sec = o.initial_rtt_timeout / 1000;
  1983.   tv.tv_usec = (o.initial_rtt_timeout % 1000) * 1000;
  1984.   if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  1985.     {perror("Socket troubles"); exit(1);}
  1986.   unblock_socket(sd);
  1987.   sock.sin_family = AF_INET;
  1988.   sock.sin_addr.s_addr = target.s_addr;
  1989.   sock.sin_port = htons(113); /*should use getservbyname(3), yeah, yeah */
  1990.   FD_ZERO(&fds_read);
  1991.   FD_ZERO(&fds_write);
  1992.   FD_SET(sd, &fds_read);
  1993.   FD_SET(sd, &fds_write);
  1994.   res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  1995.   if (res != -1) /* must be scanning localhost, this socket is non-blocking */ 
  1996.     goto success;
  1997.   if (errno == ECONNREFUSED) /* Unlikely in non-blocking, but could happen  */ 
  1998.     goto failure;
  1999.   if ((res = select(sd+1, &fds_read, &fds_write, NULL, &tv)) > 0) {
  2000.     /* Yay, it may be up ... */
  2001.     if (FD_ISSET(sd, &fds_read) && FD_ISSET(sd, &fds_write)) {
  2002.       res = recvfrom(sd, buf,4096, 0, (struct sockaddr *) & stranger, &sockaddr_in_len);
  2003.       if (res >= 0) goto success;
  2004.       goto failure;
  2005.     }
  2006.     else if (FD_ISSET(sd, &fds_write)) {
  2007.       res = send(sd, buf, 0, 0);
  2008.       if (res < 0) goto failure;
  2009.       goto success;
  2010.     } else if (FD_ISSET(sd, &fds_read)) {
  2011.       fprintf(stderr, "I have never seen this type of socket selectable for read only.  Please let me know how you did it and what OS you are running (fyodor@insecure.org).\n");
  2012.       goto success;
  2013.     }
  2014.     else {
  2015.       fprintf(stderr, "Wow, select blatantly lied to us!  Please let fyodor know what OS you are running (fyodor@insecure.org).\n");
  2016.       goto failure;
  2017.     } 
  2018.   }
  2019.  
  2020.  failure:
  2021.   close(sd);
  2022.   if (o.debugging || o.verbose) log_write(LOG_STDOUT, "identd port not active\n");
  2023.   return 0;
  2024.  
  2025.  success:
  2026.   close(sd);
  2027.   if (o.debugging || o.verbose) log_write(LOG_STDOUT, "identd port is active\n");
  2028.   return 1;
  2029. }
  2030.  
  2031. /* returns 0 for possibly temporary error, -1 means we shouldn't attempt
  2032.    inetd again on this host */
  2033. int getidentinfoz(struct in_addr target, u16 localport, u16 remoteport,
  2034.           char *owner, int ownersz) {
  2035.   int sd;
  2036.   struct sockaddr_in sock;
  2037.   int res;
  2038.   char request[16];
  2039.   char response[1024];
  2040.   char *p,*q;
  2041.   char  *os;
  2042.  
  2043.   if (ownersz == 0) return 0;
  2044.   owner[0] = '\0';
  2045.   if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
  2046.     {perror("Socket troubles"); exit(1);}
  2047.  
  2048.   sock.sin_family = AF_INET;
  2049.   sock.sin_addr.s_addr = target.s_addr;
  2050.   sock.sin_port = htons(113);
  2051.   usleep(50000);   /* If we aren't careful, we really MIGHT take out inetd, 
  2052.               some are very fragile */
  2053.   res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  2054.  
  2055.   if (res < 0 ) {
  2056.     if (o.debugging)
  2057.       fprintf(stderr, "Identd port not open, cannot obtain port owner info.\n"); 
  2058.     close(sd);
  2059.     return -1;
  2060.   }
  2061.   snprintf(request, sizeof(request), "%hu,%hu\r\n", remoteport, localport);
  2062.   if (o.debugging > 1) log_write(LOG_STDOUT, "Connected to identd, sending request: %s", request);
  2063.   if (write(sd, request, strlen(request) + 1) == -1) {
  2064.     perror("identd write");
  2065.     close(sd);
  2066.     return 0;
  2067.   }
  2068.   else if ((res = read(sd, response, sizeof(response))) == -1) {
  2069.     perror("reading from identd");
  2070.     close(sd);
  2071.     return 0;
  2072.   }
  2073.   else {
  2074.     close(sd);
  2075.     if (o.debugging > 1) log_write(LOG_STDOUT, "Read %d bytes from identd: %s\n", res, response);
  2076.     if ((p = strchr(response, ':'))) {
  2077.       p++;
  2078.       if ((q = strtok(p, " :"))) {
  2079.     if (!strcasecmp( q, "error")) {
  2080.       if (strstr(response, "HIDDEN-USER") || strstr(response, "hidden-user")) {
  2081.         log_write(LOG_STDOUT, "identd returning HIDDEN-USER, giving up on it\n");
  2082.         return -1;
  2083.       }
  2084.       if (o.debugging) log_write(LOG_STDOUT, "ERROR returned from identd for port %d\n", remoteport);
  2085.       return 0;
  2086.     }
  2087.     if ((os = strtok(NULL, " :"))) {
  2088.       if ((p = strtok(NULL, " :"))) {
  2089.         if ((q = strchr(p, '\r'))) *q = '\0';
  2090.         if ((q = strchr(p, '\n'))) *q = '\0';
  2091.         Strncpy(owner, p, ownersz);
  2092.       }
  2093.     }
  2094.       } 
  2095.     }  
  2096.   }
  2097.   return 1;
  2098. }
  2099.  
  2100.  
  2101.  
  2102. /* Determine whether firewall mode should be on for a scan */
  2103. /* If firewall mode is active, we increase the scan group size every
  2104.    30 seconds */
  2105. int check_firewallmode(struct hoststruct *target, struct scanstats *ss) {
  2106.   struct firewallmodeinfo *fm = &(target->firewallmode);
  2107.   struct timeval current_time;
  2108.   static struct timeval last_adjust;
  2109.   static int init = 0;
  2110.  
  2111.   if (!init) {
  2112.     gettimeofday(&last_adjust, NULL);
  2113.     init = 1;
  2114.   }
  2115.  
  2116.   if (fm->nonresponsive_ports > 50 && ((double)fm->responsive_ports / (fm->responsive_ports + fm->nonresponsive_ports)) < 0.05) {  
  2117.     if (fm->active == 0 && o.debugging)
  2118.       error("Activating firewall speed-optimization mode for host %s (%s)", target->name, inet_ntoa(target->host)); 
  2119.     fm->active = 1;
  2120.   }
  2121.  
  2122.   if (fm->active) {
  2123.     gettimeofday(¤t_time, NULL);
  2124.     if (TIMEVAL_SEC_SUBTRACT(current_time, last_adjust) > 5) {
  2125.       ss->numqueries_ideal = MIN(ss->numqueries_ideal + (ss->packet_incr/ss->numqueries_ideal), ss->max_width); 
  2126.       if (o.debugging) {
  2127.     error("Raising ideal number of queries to %10.7g to account for firewalling", ss->numqueries_ideal);
  2128.       }
  2129.       last_adjust = current_time;
  2130.     }
  2131.   }
  2132.   return fm->active;
  2133. }
  2134.  
  2135. int ftp_anon_connect(struct ftpinfo *ftp) {
  2136.   int sd;
  2137.   struct sockaddr_in sock;
  2138.   int res;
  2139.   char recvbuf[2048];
  2140.   char command[512];
  2141.  
  2142.   if (o.verbose || o.debugging) 
  2143.     log_write(LOG_STDOUT, "Attempting connection to ftp://%s:%s@%s:%i\n", ftp->user, ftp->pass,
  2144.           ftp->server_name, ftp->port);
  2145.  
  2146.   if ((sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
  2147.     perror("Couldn't create ftp_anon_connect socket");
  2148.     return 0;
  2149.   }
  2150.  
  2151.   sock.sin_family = AF_INET;
  2152.   sock.sin_addr.s_addr = ftp->server.s_addr;
  2153.   sock.sin_port = htons(ftp->port); 
  2154.   res = connect(sd, (struct sockaddr *) &sock, sizeof(struct sockaddr_in));
  2155.   if (res < 0 ) {
  2156.     fprintf(stderr, "Your ftp bounce proxy server won't talk to us!\n");
  2157.     exit(1);
  2158.   }
  2159.   if (o.verbose || o.debugging) log_write(LOG_STDOUT, "Connected:");
  2160.   while ((res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,7)) > 0) 
  2161.     if (o.debugging || o.verbose) {
  2162.       recvbuf[res] = '\0';
  2163.       log_write(LOG_STDOUT, "%s", recvbuf);
  2164.     }
  2165.   if (res < 0) {
  2166.     perror("recv problem from ftp bounce server");
  2167.     exit(1);
  2168.   }
  2169.  
  2170.   snprintf(command, 511, "USER %s\r\n", ftp->user);
  2171.  
  2172.   send(sd, command, strlen(command), 0);
  2173.   res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,12);
  2174.   if (res <= 0) {
  2175.     perror("recv problem from ftp bounce server");
  2176.     exit(1);
  2177.   }
  2178.   recvbuf[res] = '\0';
  2179.   if (o.debugging) log_write(LOG_STDOUT, "sent username, received: %s", recvbuf);
  2180.   if (recvbuf[0] == '5') {
  2181.     fprintf(stderr, "Your ftp bounce server doesn't like the username \"%s\"\n", 
  2182.         ftp->user);
  2183.     exit(1);
  2184.   }
  2185.  
  2186.   snprintf(command, 511, "PASS %s\r\n", ftp->pass);
  2187.  
  2188.   send(sd, command, strlen(command), 0);
  2189.   res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,12);
  2190.   if (res < 0) {
  2191.     perror("recv problem from ftp bounce server\n");
  2192.     exit(1);
  2193.   }
  2194.   if (!res) fprintf(stderr, "Timeout from bounce server ...");
  2195.   else {
  2196.     recvbuf[res] = '\0';
  2197.     if (o.debugging) log_write(LOG_STDOUT, "sent password, received: %s", recvbuf);
  2198.     if (recvbuf[0] == '5') {
  2199.       fprintf(stderr, "Your ftp bounce server refused login combo (%s/%s)\n",
  2200.           ftp->user, ftp->pass);
  2201.       exit(1);
  2202.     }
  2203.   }
  2204.   while ((res = recvtime(sd, recvbuf, sizeof(recvbuf) - 1,2)) > 0) 
  2205.     if (o.debugging) {
  2206.       recvbuf[res] = '\0';
  2207.       log_write(LOG_STDOUT, "%s", recvbuf);
  2208.     }
  2209.   if (res < 0) {
  2210.     perror("recv problem from ftp bounce server");
  2211.     exit(1);
  2212.   }
  2213.   if (o.verbose) log_write(LOG_STDOUT, "Login credentials accepted by ftp server!\n");
  2214.  
  2215.   ftp->sd = sd;
  2216.   return sd;
  2217. }
  2218.  
  2219. #ifndef WIN32
  2220.  
  2221. void reaper(int signo) {
  2222.   int status;
  2223.   pid_t pid;
  2224.  
  2225.   if ((pid = wait(&status)) == -1) {
  2226.     gh_perror("waiting to reap child");
  2227.   } else {
  2228.     fprintf(stderr, "\n[%d finished status=%d (%s)]\nnmap> ", (int) pid, status, (status == 0)? "success"  : "failure");
  2229.   }
  2230. }
  2231.  
  2232. void sigdie(int signo) {
  2233.   switch(signo) {
  2234.   case SIGINT:
  2235.     fprintf(stderr, "caught SIGINT signal, cleaning up\n");
  2236.     break;
  2237.   case SIGTERM:
  2238.     fprintf(stderr, "caught SIGTERM signal, cleaning up\n");
  2239.     break;
  2240.   case SIGHUP:
  2241.     fprintf(stderr, "caught SIGHUP signal, cleaning up\n");
  2242.     break;
  2243.   case SIGSEGV:
  2244.     fprintf(stderr, "caught SIGSEGV signal, cleaning up\n");
  2245.     if (o.debugging) abort();
  2246.     break;
  2247.   case SIGBUS:
  2248.     fprintf(stderr, "caught SIGBUS signal, cleaning up\n");
  2249.     break;
  2250.   default:
  2251.     fprintf(stderr, "caught signal %d, cleaning up\n", signo);
  2252.     break;
  2253.   }
  2254.   fflush(stdout);
  2255.   log_close(LOG_MACHINE|LOG_NORMAL|LOG_SKID);
  2256.   exit(1);
  2257. }
  2258.  
  2259. #endif
  2260.  
  2261. int nmap_fetchfile(char *filename_returned, int bufferlen, char *file) {
  2262.   char *dirptr;
  2263.   int res;
  2264.   int foundsomething = 0;
  2265.   struct passwd *pw;
  2266.   char dot_buffer[512];
  2267.   static int warningcount = 0;
  2268.  
  2269.   /* First we try $NMAPDIR/file
  2270.      next we try ~user/nmap/file
  2271.      then we try NMAPDATADIR/file <--NMAPDATADIR 
  2272.      finally we try ./file
  2273.  
  2274.      -- or on Windows --
  2275.  
  2276.      $NMAPDIR -> nmap.exe directory -> NMAPDATADIR -> .
  2277.   */
  2278.   if ((dirptr = getenv("NMAPDIR"))) {
  2279.     res = snprintf(filename_returned, bufferlen, "%s/%s", dirptr, file);
  2280.     if (res > 0 && res < bufferlen) {
  2281.       if (fileexistsandisreadable(filename_returned))
  2282.     foundsomething = 1;
  2283.     }
  2284.   }
  2285. #ifndef WIN32
  2286.   if (!foundsomething) {
  2287.     pw = getpwuid(getuid());
  2288.     if (pw) {
  2289.       res = snprintf(filename_returned, bufferlen, "%s/.nmap/%s", pw->pw_dir, file);
  2290.       if (res > 0 && res < bufferlen) {
  2291.     if (fileexistsandisreadable(filename_returned))
  2292.       foundsomething = 1;
  2293.       }
  2294.     }
  2295.     if (!foundsomething && getuid() != geteuid()) {
  2296.       pw = getpwuid(geteuid());
  2297.       if (pw) {
  2298.     res = snprintf(filename_returned, bufferlen, "%s/nmap/%s", pw->pw_dir, file);
  2299.     if (res > 0 && res < bufferlen) {
  2300.       if (fileexistsandisreadable(filename_returned))
  2301.         foundsomething = 1;
  2302.     }
  2303.       }
  2304.     }
  2305.   }
  2306. #else
  2307.   if (!foundsomething) { /* Try the nMap directory */
  2308.       char fnbuf[MAX_PATH];
  2309.       int i;
  2310.       res = GetModuleFileName(GetModuleHandle(0), fnbuf, 1024);
  2311.       if(!res) fatal("GetModuleFileName failed (!)\n");
  2312.       //    Strip it
  2313.       for(i = res - 1; i >= 0 && fnbuf[i] != '/' && fnbuf[i] != '\\'; i--);
  2314.       if(i >= 0) // we found it
  2315.           fnbuf[i] = 0;
  2316.       res = snprintf(filename_returned, bufferlen, "%s/%s", fnbuf, file);
  2317.       if(res > 0 && res < bufferlen) {
  2318.           if (fileexistsandisreadable(filename_returned))
  2319.             foundsomething = 1;
  2320.       }
  2321.   }
  2322. #endif
  2323.   if (!foundsomething) {
  2324.     res = snprintf(filename_returned, bufferlen, "%s/%s", NMAPDATADIR, file);
  2325.     if (res > 0 && res < bufferlen) {
  2326.       if (fileexistsandisreadable(filename_returned))
  2327.     foundsomething = 1;
  2328.     }
  2329.   }
  2330.   if (foundsomething && (*filename_returned != '.')) {    
  2331.     res = snprintf(dot_buffer, sizeof(dot_buffer), "./%s", file);
  2332.     if (res > 0 && res < bufferlen) {
  2333.       if (fileexistsandisreadable(dot_buffer)) {
  2334.     if (warningcount++ < 5)
  2335.       error("WARNING!  The following files exist and are readable: %s and %s.  I am choosing %s for security reasons.  set NMAPDIR=. to give priority to files in your local directory", filename_returned, dot_buffer, filename_returned);
  2336.       }
  2337.     }
  2338.   }
  2339.  
  2340.   if (!foundsomething) {
  2341.     res = snprintf(filename_returned, bufferlen, "./%s", file);
  2342.     if (res > 0 && res < bufferlen) {
  2343.       if (fileexistsandisreadable(filename_returned))
  2344.     foundsomething = 1;
  2345.     }
  2346.   }
  2347.  
  2348.   if (!foundsomething) {
  2349.     filename_returned[0] = '\0';
  2350.     return -1;
  2351.   }
  2352.  
  2353.   if (o.debugging > 1)
  2354.     error("Fetchfile found %s\n", filename_returned);
  2355.  
  2356.   return 0;
  2357.  
  2358. }
  2359.  
  2360. int fileexistsandisreadable(char *pathname) {
  2361.   FILE *fp;
  2362.   /* We check this the easy way! */
  2363.   fp = fopen(pathname, "r");
  2364.   if (fp) fclose(fp);
  2365.   return (fp == NULL)? 0 : 1;
  2366. }
  2367.  
  2368.