home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / nmap254b.zip / scan_engine.c < prev    next >
C/C++ Source or Header  |  2001-08-10  |  63KB  |  1,724 lines

  1. /***********************************************************************/
  2. /* scanengine.c -- Includes much of the "engine" functions for         */
  3. /* scanning, such as pos_scan and super_scan.  It also includes        */
  4. /* dependant functions such as those for collectiong SYN/connect scan  */
  5. /* responses.                                                          */
  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: scan_engine.c,v 1.8 2001/08/10 05:53:08 fyodor Exp $ */
  47.  
  48. #include "scan_engine.h"
  49. #include "timing.h"
  50.  
  51. extern struct ops o;
  52.  
  53. /*  predefined filters -- I need to kill these globals at some pont. */
  54. extern unsigned long flt_dsthost, flt_srchost, flt_baseport;
  55.  
  56.  
  57. /* Does the appropriate stuff when the port we are looking at is found
  58.    to be open trynum is the try number that was successful 
  59.    I USE CURRENT->STATE TO DETERMINE WHETHER THE PORT IS OPEN
  60.    OR FIREWALLED */
  61. static void posportupdate(struct hoststruct *target, struct portinfo *current, 
  62.            int trynum, struct portinfo *scan,
  63.            struct scanstats *ss ,stype scantype, int newstate,
  64.            struct portinfolist *pil, struct connectsockinfo *csi) {
  65.   static int tryident = -1;
  66.   static u32 lasttarget = 0;
  67.   struct sockaddr_in mysock;
  68.   NET_SIZE_T sockaddr_in_len = sizeof(SA);
  69.   int i;
  70.   char owner[1024];
  71.  
  72.   if (tryident == -1 || target->host.s_addr != lasttarget) 
  73.     tryident = o.identscan;
  74.   lasttarget = target->host.s_addr;
  75.   owner[0] = '\0';
  76.   if (current->state != PORT_OPEN && current->state != PORT_CLOSED &&
  77.       current->state != PORT_FIREWALLED && current->state != PORT_TESTING) {
  78.     if (o.debugging) error("Whacked packet to port %lu passed to posportupdate with state %s (%d)\n", current->portno, statenum2str(current->state), current->state);
  79.     return;
  80.   }
  81.  
  82.   /* Lets do the timing stuff */
  83.   if (trynum > -1) {
  84.     adjust_timeouts(current->sent[trynum], &(target->to));
  85.     target->firewallmode.responsive_ports++; 
  86.   }
  87.   /* If a non-zero trynum finds a port that hasn't been discovered, the
  88.    earlier packets(s) were probably dropped.  So we decrease our 
  89.    numqueries_ideal, otherwise we increase it slightly */
  90.   if (trynum == 0) {
  91.     ss->numqueries_ideal = MIN(ss->numqueries_ideal + (ss->packet_incr/ss->numqueries_ideal), ss->max_width);
  92.   } else if (trynum != -1) {
  93.     if (!ss->alreadydecreasedqueries) {
  94.       ss->alreadydecreasedqueries = 1;
  95.       ss->numqueries_ideal *= ss->fallback_percent;
  96.       if (target->firewallmode.active)
  97.     ss->numqueries_ideal *= ss->fallback_percent; /* We need to act 
  98.                              forcefully on what 
  99.                              little info we have */
  100.       if (ss->numqueries_ideal < 1.0) ss->numqueries_ideal = 1.0;
  101.     }
  102.   }
  103.  
  104.   /* Collect IDENT info if requested */
  105.   if (newstate == PORT_OPEN && scantype == CONNECT_SCAN && tryident) {
  106.     if (getsockname(current->sd[trynum], (SA *) &mysock,
  107.             &sockaddr_in_len )) {
  108.       pfatal("getsockname");
  109.     }
  110.     if (getidentinfoz(target->host, ntohs(mysock.sin_port), current->portno, owner, sizeof(owner)) == -1)
  111.       tryident = 0;
  112.   }
  113.  
  114.   /* Now we convert current->state to state by making whatever adjustments
  115.    are neccessary */
  116.   switch(current->state) {
  117.   case PORT_OPEN:
  118.     return; /* Whew!  That was easy! */
  119.     break;
  120.   case PORT_FRESH:
  121.     fprintf(stderr, "Fresh port %lu passed to posportupdate!\n", current->portno);
  122.     return;
  123.     break;
  124.   case PORT_CLOSED:
  125.     if (newstate == PORT_CLOSED)
  126.       return; /* Closed -> Closed is not important and can cause some 
  127.          dup port problems */
  128.     ss->changed++;
  129.     current->state = newstate;
  130.     break;
  131.   case PORT_TESTING:
  132.     /* If the newstate is FIREWALLED, nothing really "changed" since the
  133.        default if there is no responses is to put the port into the firewalled
  134.        state.  OK, OK, I don't know if this justification completely holds 
  135.        water, but the shortcut of not updating change can save us a LOT of 
  136.        time in cases of infrequent host unreachable packets (for example).  
  137.        In that case, a few unreachables during each scan run causes the changed
  138.        flag to be set and we need to try again.  Eventually the systems notices
  139.        all the tries and starts increasing senddelay() and we are in even 
  140.        worse shape */
  141.     if (newstate != PORT_FIREWALLED)
  142.       ss->changed++;
  143.     if (scantype == SYN_SCAN)
  144.       ss->numqueries_outstanding--;
  145.     else {
  146.       for(i=0; i <= current->trynum; i++)
  147.     if (current->sd[i] > -1) {
  148.       csi->socklookup[current->sd[i]] = NULL;
  149.       FD_CLR(current->sd[i], &(csi->fds_read));
  150.       FD_CLR(current->sd[i], &(csi->fds_write));
  151.       FD_CLR(current->sd[i], &(csi->fds_except));
  152.       if (current->sd[i] == csi->maxsd)
  153.         csi->maxsd--;
  154.       close(current->sd[i]);
  155.       current->sd[i] = -1;
  156.       ss->numqueries_outstanding--;
  157.     }
  158.     }
  159.     /* Now we delete the port from the testinglist */
  160.     if (current == pil->testinglist)
  161.       pil->testinglist = (current->next >= 0)? &scan[current->next] : NULL;
  162.     if (current->next >= 0)  scan[current->next].prev = current->prev;
  163.     if (current->prev >= 0)  scan[current->prev].next = current->next;
  164.     break;
  165.   case PORT_FIREWALLED:
  166.     if (newstate != PORT_FIREWALLED)
  167.       ss->changed++;
  168.     if (current == pil->firewalled)
  169.       pil->firewalled = (current->next >= 0)? &scan[current->next] : NULL;
  170.     if (current->next >= 0)  scan[current->next].prev = current->prev;
  171.     if (current->prev >= 0)  scan[current->prev].next = current->next;
  172.     break;
  173.   default:
  174.     fatal("Unexpected port state: %d\n", current->state);
  175.     break;
  176.   } 
  177.   current->state = newstate;
  178.   current->next = -1;
  179.   current->prev = -1;
  180.   addport(&target->ports, current->portno, IPPROTO_TCP, owner, newstate);
  181.   return;
  182. }
  183.  
  184. /* Grab results from a connect() scan (eg check all the non-blocking
  185.    outstanding connect requests for completion.  */
  186. static int get_connect_results(struct hoststruct *target, 
  187.                    struct portinfo *scan, 
  188.                    struct scanstats *ss, struct portinfolist *pil, 
  189.                    int *portlookup, u32 *sequences, 
  190.                    struct connectsockinfo *csi) {
  191.   fd_set fds_rtmp, fds_wtmp, fds_xtmp;
  192.   int selectres;
  193.   int selectedfound;
  194.   int optval;
  195.   NET_SIZE_T optlen = sizeof(int);
  196.   struct timeval timeout;
  197.   int i, sd;
  198.   int trynum;
  199.   char buf[2048];
  200.   struct portinfo *current = NULL;
  201.   struct timeval tv;
  202.   int res;
  203. #ifdef LINUX
  204.   struct sockaddr_in sin,sout;
  205.   NET_SIZE_T sinlen = sizeof(sin);
  206.   NET_SIZE_T soutlen = sizeof(sout);
  207. #endif
  208.  
  209.   res = 0;  /* to prevent compiler warning */
  210.   do {
  211.     fds_rtmp = csi->fds_read;
  212.     fds_wtmp = csi->fds_write;
  213.     fds_xtmp = csi->fds_except;
  214.     timeout.tv_sec = 0;
  215.     timeout.tv_usec = 20000;
  216.     selectedfound = 0;
  217.  
  218.     /* Insure there is no timeout ... */
  219.     if (o.host_timeout) {    
  220.       gettimeofday(&tv, NULL);
  221.       if (TIMEVAL_MSEC_SUBTRACT(tv, target->host_timeout) >= 0) {
  222.     target->timedout = 1;
  223.     return 0;
  224.       }
  225.     }
  226.  
  227.     selectres = select(csi->maxsd+1, &fds_rtmp, &fds_wtmp, &fds_xtmp, &timeout);
  228.     for(sd=0; selectedfound < selectres && sd <= csi->maxsd; sd++) {
  229.       current = csi->socklookup[sd];
  230.       if (!current) continue;
  231.       trynum = -1;
  232.       if  (FD_ISSET(sd, &fds_rtmp)  || FD_ISSET(sd, &fds_wtmp) || 
  233.        FD_ISSET(sd, &fds_xtmp)) {
  234.     /*      current = csi->socklookup[i];*/
  235.     for(i=0; i < 3; i++)
  236.       if (current->sd[i] == sd) {    
  237.         trynum = i;
  238.         break;
  239.       }
  240.  
  241.     if (o.debugging > 1 && current != NULL)
  242.       log_write(LOG_STDOUT, "portnumber %lu (try %d) selected for", current->portno, trynum);
  243.     if (FD_ISSET(sd, &fds_rtmp)) {
  244.       if (o.debugging > 1) log_write(LOG_STDOUT, " READ");
  245.       selectedfound++;
  246.     }
  247.     if (FD_ISSET(sd, &fds_wtmp)) {
  248.       if (o.debugging > 1) log_write(LOG_STDOUT, " WRITE");
  249.       selectedfound++;
  250.     }
  251.     if (FD_ISSET(sd, &fds_xtmp)) {
  252.       if (o.debugging > 1) log_write(LOG_STDOUT, " EXCEPT");
  253.       selectedfound++;
  254.     }
  255.     if (o.debugging > 1 && current != NULL)
  256.       log_write(LOG_STDOUT, "\n");
  257.  
  258.     assert(trynum != -1);
  259.  
  260.     if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (char *) &optval, &optlen) != 0)
  261.       optval = errno; /* Stupid Solaris ... */
  262.  
  263.     switch(optval) {
  264.     case 0:
  265. #ifdef LINUX
  266.       if (!FD_ISSET(sd, &fds_rtmp)) {
  267.         /* Linux goofiness -- We need to actually test that it is writeable */
  268.         res = send(current->sd[trynum], "", 0, 0);
  269.  
  270.         if (res < 0 ) {
  271.           if (o.debugging > 1) {
  272.         log_write(LOG_STDOUT, "Bad port %lu caught by 0-byte write: ", current->portno);
  273.         perror("");
  274.           }
  275.           posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_CLOSED, pil, csi);
  276.         } else {
  277.           if (getpeername(sd, (struct sockaddr *) &sin, &sinlen) < 0) {
  278.         pfatal("error in getpeername of connect_results for port %hu", current->portno);
  279.           } else {
  280.         if (current->portno != ntohs(sin.sin_port)) {
  281.           error("Mismatch!!!! we think we have port %hu but we really have %hu", current->portno, ntohs(sin.sin_port));
  282.         }
  283.           }
  284.  
  285.           if (getsockname(sd, (struct sockaddr *) &sout, &soutlen) < 0) {
  286.         pfatal("error in getsockname for port %hu", current->portno);
  287.           }
  288.           if (htons(sout.sin_port) == current->portno) {
  289.         /* Linux 2.2 bug can lead to bogus successful connect()ions
  290.            in this case -- we treat the port as bogus even though it
  291.            is POSSIBLE that this is a real connection */
  292.         posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_CLOSED, pil, csi);
  293.           } else {
  294.         posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_OPEN, pil, csi);
  295.           }
  296.         }
  297.       } else {
  298.         posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_OPEN, pil, csi);
  299.       }
  300. #else
  301.       posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_OPEN, pil, csi);
  302. #endif
  303.       break;
  304.     case ECONNREFUSED:
  305.       posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_CLOSED, pil, csi);
  306.       break;
  307.     case EHOSTUNREACH:
  308.     case ETIMEDOUT:
  309.     case EHOSTDOWN:
  310.       /* It could be the host is down, or it could be firewalled.  We
  311.          will go on the safe side & assume port is closed ... on second
  312.          thought, lets go firewalled! and see if it causes any trouble */
  313.       posportupdate(target, current, trynum, scan, ss, CONNECT_SCAN, PORT_FIREWALLED, pil, csi);
  314.       break;
  315.     case ENETDOWN:
  316.     case ENETUNREACH:
  317.     case ENETRESET:
  318.     case ECONNABORTED:
  319.       snprintf(buf, sizeof(buf), "Strange SO_ERROR from connection to %s (%d) -- bailing scan", inet_ntoa(target->host), optval);
  320.       perror(buf);
  321.       return -1;
  322.       break;
  323.     default:
  324.       snprintf(buf, sizeof(buf), "Strange read error from %s (%d)", inet_ntoa(target->host), optval);
  325.       perror(buf);
  326.       break;
  327.     }
  328.       } else continue;
  329.     }
  330.   } while(ss->numqueries_outstanding > 0 && selectres > 0);
  331.  
  332.   return 0;
  333. }
  334.  
  335. /* Grab results for a SYN scan.  We assume the SYNs have already been sent,
  336.    and we sniff for SYN|ACK or RST packets */
  337. static void get_syn_results(struct hoststruct *target, struct portinfo *scan,
  338.              struct scanstats *ss, struct portinfolist *pil, 
  339.              int *portlookup, pcap_t *pd, u32 *sequences, 
  340.              stype scantype) {
  341.  
  342.   struct ip *ip;
  343.   unsigned int bytes;
  344.   struct tcphdr *tcp;
  345.   int trynum;
  346.   int newstate = -1;
  347.   int i;
  348.   int newport;
  349.   struct portinfo *current = NULL;
  350.   struct icmp *icmp;
  351.   struct ip *ip2;
  352.   u16 *data;
  353.   struct timeval tv;
  354.   struct timeval start;
  355.   int quit = 0;
  356.  
  357.   gettimeofday(&start, NULL);
  358.  
  359.   while (!quit && ss->numqueries_outstanding > 0 && 
  360.      ( ip = (struct ip*) readip_pcap(pd, &bytes, target->to.timeout))) {
  361.     if (bytes < (4 * ip->ip_hl) + 4U)
  362.       continue;
  363.     current = NULL;
  364.     trynum = newport = -1;
  365.     newstate = PORT_UNKNOWN;
  366.  
  367.     gettimeofday(&tv, NULL);
  368.     
  369.     /* Insure there is no timeout ... */
  370.     if (o.host_timeout) {    
  371.       if (TIMEVAL_MSEC_SUBTRACT(tv, target->host_timeout) >= 0) {
  372.     target->timedout = 1;
  373.     return;
  374.       }
  375.     }
  376.  
  377.     /* If this takes at least 1.5 secs and is more than the targets
  378.        timeout, lets get out of here.  Otherwise stray network packets
  379.        could cause us trouble. */
  380.     if ( TIMEVAL_SUBTRACT(tv, start) > MAX(target->to.timeout, 1500)) {
  381.       /* Lets quit after we process this packet */
  382.       quit = 1;
  383.     }
  384.  
  385.     if (ip->ip_src.s_addr == target->host.s_addr && ip->ip_p == IPPROTO_TCP) {
  386.       tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
  387.       i = ntohs(tcp->th_dport);
  388.       if (i < o.magic_port || i > o.magic_port + 15) {
  389.     if (o.debugging > 1)
  390.       error("SYN scan got TCP packet to port %d (magic port is %d) ... ignoring", i, o.magic_port);
  391.     continue;
  392.       }
  393.       newport = ntohs(tcp->th_sport);
  394.       /* In case we are scanning localhost and see outgoing packets */
  395.       /* If only one of SYN, ACK flags are set, we skip it */
  396.       if (ip->ip_src.s_addr == target->source_ip.s_addr && ((tcp->th_flags == TH_ACK) || (tcp->th_flags == TH_SYN))) {
  397.     continue;
  398.       }
  399.       if (portlookup[newport] < 0) {
  400.     if (o.debugging) {
  401.       log_write(LOG_STDOUT, "Strange packet from port %d:\n", ntohs(tcp->th_sport));
  402.       readtcppacket((unsigned char *)ip, bytes);
  403.     }
  404.     current = NULL;
  405.     continue;
  406.       }          
  407.  
  408.       current = &scan[portlookup[newport]];
  409.       for(i=0; i < 3; i++) {
  410.     if (MOD_DIFF(sequences[i],ntohl(tcp->th_ack)) < 5)
  411.       break;
  412.       }
  413.       if (i < 3) trynum = i;
  414.       else {
  415.     if (o.debugging) 
  416.       log_write(LOG_STDOUT, "Strange ACK number from target: %lX\n", (unsigned long) ntohl(tcp->th_ack));
  417.     trynum = (current->trynum == 0)? 0 : -1;        
  418.       }
  419.       if (current->trynum < trynum) {
  420.     if (o.debugging)         
  421.       error("Received SYN packet implying trynum %d from port %hu even though that port is only on trynum %d (could be from an earlier round)", trynum, newport, current->trynum);
  422.     trynum = -1;
  423.       }
  424.       if (scantype == SYN_SCAN) {
  425.     if (tcp->th_flags & TH_RST) {
  426.       newstate = PORT_CLOSED;
  427.     } else if ((tcp->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
  428.       newstate = PORT_OPEN;
  429.     } else {
  430.       if (o.debugging)
  431.         error("Received response to SYN scan with unexpected tcp flags: %d\n", tcp->th_flags);
  432.       continue;
  433.     }
  434.       }
  435.       else if (scantype == WINDOW_SCAN) {
  436.     if (tcp->th_flags & TH_RST) {
  437.       if (tcp->th_win) {
  438.         newstate = PORT_OPEN;
  439.       } else {
  440.         newstate = PORT_CLOSED;
  441.       }
  442.     } else {
  443.       if (o.debugging)
  444.         error("Received response to WINDOW scan with unexpected tcp flags: %d\n", tcp->th_flags);
  445.       continue;
  446.     }
  447.       }
  448.       else if (scantype == ACK_SCAN) {
  449.     if (tcp->th_flags & TH_RST) {      
  450.       newstate = PORT_UNFIREWALLED;
  451.     } else {
  452.       if (o.debugging)
  453.         error("Received response to ACK scan with unexpected tcp flags: %d\n", tcp->th_flags);
  454.       continue;
  455.     }
  456.       } else {
  457.     fatal("Unknown scan type!#$!@#$ passed to get_syn_results!  Please notify fyodor@insecure.org");
  458.       }
  459.     } else if (ip->ip_p == IPPROTO_ICMP) {
  460.       icmp = (struct icmp *) ((char *)ip + 4 * ip->ip_hl);
  461.       ip2 = (struct ip *) (((char *) ip) + 4 * ip->ip_hl + 8);
  462.       if (bytes <= 4 * ip->ip_hl + 28U ||
  463.       bytes <= /* IP1len */ 4 * ip->ip_hl + /*ICMPlen */ 8 + 
  464.       /* IP2len */ 4 * ip2->ip_hl + 4U /* TCP ports */)
  465.     {
  466.       if (o.debugging) {
  467.         error("Icmp message too short (%d bytes)", bytes);
  468.       }
  469.       continue;
  470.     }
  471.  
  472.       /* Lets ensure this packet relates to a packet to the host
  473.      we are scanning ... */
  474.       if (ip2->ip_dst.s_addr != target->host.s_addr) {
  475.     if (o.debugging > 1)
  476.       error("Got an ICMP message which does not relate to a packet sent to the host being scanned");
  477.     continue;
  478.       }
  479.  
  480.       data = (u16 *) ((char *)ip2 + 4 * ip2->ip_hl);
  481.       /*        log_write(LOG_STDOUT, "Caught ICMP packet:\n");
  482.             hdump(icmp, ntohs(ip->ip_len) - sizeof(struct ip)); */
  483.       if (icmp->icmp_type == 3) {
  484.     if (icmp->icmp_code != 0 && icmp->icmp_code != 1 && 
  485.         icmp->icmp_code != 2 && 
  486.         icmp->icmp_code != 3 && icmp->icmp_code != 13 &&
  487.         icmp->icmp_code != 9 && icmp->icmp_code != 10) {
  488.       error("Unexpected ICMP type/code 3/%d unreachable packet:", icmp->icmp_code);
  489.       hdump((unsigned char *)icmp, ntohs(ip->ip_len) - sizeof(struct ip));
  490.       continue;
  491.     }
  492.        
  493.     newport = ntohs(data[1]);
  494.     if (portlookup[newport] >= 0) {
  495.       current = &scan[portlookup[newport]];
  496.       trynum = (current->trynum == 0)? 0 : -1;
  497.       newstate = PORT_FIREWALLED;
  498.     } else { 
  499.       if (o.debugging) {
  500.         error("Illegal ICMP type/code 3/%d unreachable packet:", 
  501.           icmp->icmp_code);
  502.         hdump((unsigned char *)icmp, ntohs(ip->ip_len) - sizeof(struct ip));
  503.       }
  504.       continue;
  505.     }          
  506.       }
  507.     }      
  508.     /* OK, now we manipulate the port lists and adjust the time */
  509.     if (current) {
  510.       posportupdate(target, current, trynum, scan, ss, SYN_SCAN, newstate,
  511.             pil, NULL);
  512.       current = NULL;
  513.       trynum = -1;
  514.       newstate = PORT_UNKNOWN;
  515.     }
  516.   }
  517.   return;
  518. }
  519.  
  520. /* Handles the "positive-response" scans (where we get a response
  521.    telling us that the port is open based on the probe.  This includes
  522.    SYN Scan, Connect Scan, RPC scan, Window Scan, and ACK scan */
  523. void pos_scan(struct hoststruct *target, u16 *portarray, int numports, stype scantype) {
  524.   int initial_packet_width;  /* How many scan packets in parallel (to start with) */
  525.   struct scanstats ss;
  526.   int rawsd;
  527.   char myname[513];
  528.   int scanflags = 0;
  529.   int victim;
  530.   int senddelay = 0;
  531.   pcap_t *pd = NULL;
  532.   char filter[512];
  533.   char *p;
  534.   u32 ack_number = 0;
  535.   int tries = 0;
  536.   int  res;
  537.   int connecterror = 0;
  538.   int starttime;
  539.   struct hostent *myhostent = NULL;
  540.   struct sockaddr_in sock;
  541.   struct portinfo *scan = NULL,  *current, *next;
  542.   struct portinfolist pil;
  543.   int portlookup[65536]; /* Indexes port number -> scan[] index */
  544.   struct timeval now;
  545.   struct connectsockinfo csi;
  546.   struct rpcscaninfo rsi;
  547.   u32 sequences[3]; /* for various reasons we use 3 separate
  548.                  ones rather than simply incrementing from
  549.                  a base */
  550.   int i;
  551.   unsigned long j;
  552.  
  553.   if (target->timedout)
  554.     return;
  555.  
  556.   if (! numports) return;         /* nothing to scan for */
  557.  
  558.   /* If it is a SYN scan and we have already figured out the states
  559.      of all the TCP ports, might as well skip the scan (this can happen
  560.      if the ping scan determined the states) */
  561.   if (target->ports.state_counts_tcp[PORT_OPEN] + target->ports.state_counts_tcp[PORT_CLOSED] + target->ports.state_counts_tcp[PORT_FIREWALLED] == numports && scantype == SYN_SCAN) {
  562.     if (o.debugging)
  563.       error("Skipping SYN scan since all ports already known");
  564.     return;
  565.   }
  566.  
  567.   if (o.debugging)
  568.     log_write(LOG_STDOUT, "Starting pos_scan (%s)\n", scantype2str(scantype));
  569.  
  570.   if (scantype == RPC_SCAN) initial_packet_width = 2;
  571.   else initial_packet_width = 10;
  572.  
  573.   ss.packet_incr = 4;
  574.   ss.fallback_percent = 0.7;
  575.   ss.numqueries_outstanding = 0;
  576.   ss.ports_left = numports;
  577.   ss.alreadydecreasedqueries = 0;
  578.  
  579.   bzero(&pil, sizeof(pil));
  580.  
  581.   FD_ZERO(&csi.fds_read);
  582.   FD_ZERO(&csi.fds_write);
  583.   FD_ZERO(&csi.fds_except);
  584.   csi.maxsd = 0;
  585.  
  586.   /* Start the firewall mode with a clean slate ... */
  587.   target->firewallmode.active = 0;
  588.   target->firewallmode.nonresponsive_ports = 0;
  589.   target->firewallmode.responsive_ports = 0;
  590.  
  591.   if (o.max_parallelism) {
  592.     ss.max_width = o.max_parallelism;
  593.   } else {
  594.     if (scantype == CONNECT_SCAN) {
  595.       ss.max_width = MAX(5, max_sd() - 4);
  596.     } else {
  597.       ss.max_width = 150;
  598.     }
  599.   }
  600.  
  601.   if (initial_packet_width > ss.max_width)
  602.     initial_packet_width = ss.max_width;
  603.   ss.numqueries_ideal = initial_packet_width;
  604.  
  605.   memset(portlookup, 255, sizeof(portlookup)); /* 0xffffffff better always be (int) -1 */
  606.   bzero(csi.socklookup, sizeof(csi.socklookup));
  607.  
  608.   if (scantype != RPC_SCAN) {
  609.     /* Initialize our portlist (scan) */
  610.     scan = (struct portinfo *) safe_malloc(numports * sizeof(struct portinfo));
  611.     for(i = 0; i < numports; i++) {
  612.       scan[i].state = PORT_FRESH;
  613.       scan[i].portno = portarray[i];
  614.       scan[i].trynum = 0;
  615.       scan[i].prev = i-1;
  616.       scan[i].sd[0] = scan[i].sd[1] = scan[i].sd[2] = -1;
  617.       if (i < numports -1 ) scan[i].next = i+1;
  618.       else scan[i].next = -1;
  619.       portlookup[portarray[i]] = i;
  620.     }
  621.     current = pil.testinglist = &scan[0]; /* testinglist is a list of all 
  622.                          ports that haven't been determined                         to be closed yet */
  623.   }
  624.    
  625.   /* Init our raw socket */
  626.   if ((scantype == SYN_SCAN) || (scantype == WINDOW_SCAN) || 
  627.       (scantype == ACK_SCAN)) {  
  628.     if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  629.       pfatal("socket troubles in pos_scan");
  630.     /* We do not wan't to unblock the socket since we want to wait 
  631.        if kernel send buffers fill up rather than get ENOBUF, and
  632.        we won't be receiving on the socket anyway 
  633.        unblock_socket(rawsd);*/
  634.  
  635.     broadcast_socket(rawsd);
  636.     
  637.  
  638.     /* Init ISNs */
  639.     get_random_bytes(sequences, sizeof(sequences));
  640.  
  641.     /* Do we have a correct source address? */
  642.     if (!target->source_ip.s_addr) {
  643.       if (gethostname(myname, MAXHOSTNAMELEN) != 0 && 
  644.       !((myhostent = gethostbyname(myname))))
  645.     fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n"); 
  646.       memcpy(&target->source_ip, myhostent->h_addr_list[0], sizeof(struct in_addr));
  647.       if (o.debugging || o.verbose) 
  648.     log_write(LOG_STDOUT, "We skillfully deduced that your address is %s\n",
  649.         inet_ntoa(target->source_ip));
  650.     }
  651.     
  652.     /* Now for the pcap opening nonsense ...
  653.        Note that the snaplen is 100 = 64 byte max IPhdr + 24 byte max 
  654.        link_layer header + first 12 bytes of TCP header.
  655.     */
  656.     
  657.     pd = my_pcap_open_live(target->device, 100,  (o.spoofsource)? 1 : 0, 20);
  658.     
  659.     flt_srchost = target->host.s_addr;
  660.     flt_dsthost = target->source_ip.s_addr;
  661.  
  662.     p = strdup(inet_ntoa(target->host));
  663.     snprintf(filter, sizeof(filter), "(icmp and dst host %s) or (tcp and src host %s and dst host %s)", inet_ntoa(target->source_ip), p, inet_ntoa(target->source_ip));
  664.     free(p);
  665.  
  666.     set_pcap_filter(target, pd, flt_icmptcp, filter);
  667.  
  668.     if (scantype == SYN_SCAN)
  669.       scanflags = TH_SYN;
  670.     else
  671.       scanflags = TH_ACK;
  672.   } else if (scantype == CONNECT_SCAN) {
  673.     rawsd = -1;
  674.     /* Init our sock */
  675.     bzero((char *)&sock,sizeof(struct sockaddr_in));
  676.     sock.sin_addr.s_addr = target->host.s_addr;
  677.     sock.sin_family=AF_INET;
  678.   } else {
  679.     /* RPC Scan */
  680.     get_rpc_procs(&(rsi.rpc_progs), &(rsi.rpc_number));
  681.     scan = (struct portinfo *) safe_malloc(rsi.rpc_number * sizeof(struct portinfo));
  682.     for(j = 0; j < rsi.rpc_number; j++) {
  683.       scan[j].state = PORT_FRESH;
  684.       scan[j].portno = rsi.rpc_progs[j];
  685.       scan[j].trynum = 0;
  686.       scan[j].prev = j-1;
  687.       scan[j].sd[0] = scan[j].sd[1] = scan[j].sd[2] = -1;
  688.       if (j < rsi.rpc_number -1 ) scan[j].next = j+1;
  689.       else scan[j].next = -1;
  690.     }
  691.     current = pil.testinglist = &scan[0]; 
  692.     rawsd = -1;
  693.     rsi.rpc_current_port = NULL; /*nextport(&target->ports, NULL, 0, PORT_OPEN); */
  694.   }
  695.  
  696.   starttime = time(NULL);
  697.  
  698.   if (scantype != SYN_SCAN)
  699.     ack_number = get_random_uint();
  700.   else ack_number = 0;
  701.  
  702.   if (o.debugging || o.verbose) {  
  703.     log_write(LOG_STDOUT, "Initiating %s against %s (%s)\n", scantype2str(scantype), target->name, inet_ntoa(target->host));
  704.   }
  705.  
  706.   do {
  707.     ss.changed = 0;
  708.     if (tries > 3 && tries < 10) {
  709.       senddelay += 10000 * (tries - 3); 
  710.       if (o.verbose) log_write(LOG_STDOUT, "Bumping up senddelay by %d (to %d), due to excessive drops\n", 10000 * (tries - 3), senddelay);
  711.     } else if (tries >= 10) {
  712.       senddelay += 75000; 
  713.       if (o.verbose) log_write(LOG_STDOUT, "Bumping up senddelay by 75000 (to %d), due to excessive drops\n", senddelay);
  714.     }
  715.     
  716.     if (senddelay > 200000) {
  717.       ss.max_width = MIN(ss.max_width, 5);
  718.     }
  719.  
  720.     if (target->timedout)
  721.       goto posscan_timedout;
  722.  
  723.     /* Find a good port to scan if we are rpc scanning */
  724.     if (scantype == RPC_SCAN) {    
  725.       /* Make sure we have ports left to scan */
  726.       rsi.rpc_current_port = nextport(&target->ports, rsi.rpc_current_port,
  727.                       0, PORT_OPEN);
  728.       if (!rsi.rpc_current_port) /* Woop!  Done! */ break;
  729.  
  730.       /* Reinit our testinglist so we try each RPC prog */
  731.       pil.testinglist = &scan[0];
  732.       rsi.valid_responses_this_port = 0;
  733.       rsi.rpc_status = RPC_STATUS_UNKNOWN;
  734.     }
  735.  
  736.     while(pil.testinglist != NULL)  /* While we have live queries or more ports to scan */
  737.       {
  738.     /* Check the possible retransmissions first */
  739.     gettimeofday(&now, NULL);
  740.       
  741.     /* Insure we haven't overrun our allotted time ... */
  742.     if (o.host_timeout && (TIMEVAL_MSEC_SUBTRACT(now, target->host_timeout) >= 0))
  743.       {
  744.         target->timedout = 1;
  745.         goto posscan_timedout;
  746.       }
  747.  
  748.     /* Check if we should be in firewall mode and occasionally make 
  749.        related adjustments*/
  750.     check_firewallmode(target, &ss);
  751.  
  752.     for( current = pil.testinglist; current ; current = next) {
  753.       /* For each port or RPC program */
  754.       next = (current->next > -1)? &scan[current->next] : NULL;
  755.       if (current->state == PORT_TESTING) {
  756.         if ( TIMEVAL_SUBTRACT(now, current->sent[current->trynum]) > target->to.timeout) {
  757.           if (current->trynum > 1 ||
  758.           (current->trynum > 0 && target->firewallmode.active)) {
  759.         /* No responses !#$!#@$ firewalled? */
  760.         if (scantype == RPC_SCAN) {
  761.           if (rsi.valid_responses_this_port == 0) {           
  762.             if (o.debugging) {
  763.               log_write(LOG_STDOUT, "RPC Scan giving up on port %hu proto %d due to repeated lack of response\n", rsi.rpc_current_port->portno,  rsi.rpc_current_port->proto);
  764.             }
  765.             rsi.rpc_status = RPC_STATUS_NOT_RPC;
  766.             break;
  767.           }
  768.           else {
  769.             /* I think I am going to slow down a little */
  770.             target->to.rttvar = MIN(2000000, (int) (target->to.rttvar * 1.2));
  771.           }          
  772.         }
  773.         if (o.debugging) { log_write(LOG_STDOUT, "Moving port or prog %lu to the potentially firewalled list\n", current->portno); }
  774.         target->firewallmode.nonresponsive_ports++;
  775.         current->state = PORT_FIREWALLED; /* For various reasons */
  776.         /* First delete from old list */
  777.         if (current->next > -1) scan[current->next].prev = current->prev;
  778.         if (current->prev > -1) scan[current->prev].next = current->next;
  779.         if (current == pil.testinglist)
  780.           pil.testinglist = (current->next >= 0)?  &scan[current->next] : NULL;
  781.         current->next = -1;
  782.         current->prev = -1;
  783.         /* Now move into new list */
  784.         if (scantype != RPC_SCAN) {          
  785.           if (!pil.firewalled) pil.firewalled = current;
  786.           else {
  787.             current->next = pil.firewalled - scan;
  788.             pil.firewalled = current;
  789.             scan[current->next].prev = current - scan;          
  790.           }
  791.         }
  792.         if (scantype == CONNECT_SCAN) {
  793.           /* close the appropriate sd for each try */
  794.           for(i=0; i <= current->trynum; i++) {
  795.             if (current->sd[i] >= 0) {
  796.               csi.socklookup[current->sd[i]] = NULL;
  797.               FD_CLR(current->sd[i], &csi.fds_read);
  798.               FD_CLR(current->sd[i], &csi.fds_write);
  799.               FD_CLR(current->sd[i], &csi.fds_except);
  800.               close(current->sd[i]);
  801.               current->sd[i] = -1;
  802.               ss.numqueries_outstanding--;
  803.             }
  804.           }
  805.         } else { ss.numqueries_outstanding--; }
  806.           } else {  /* timeout ... we've got to resend */
  807.         if (o.scan_delay) enforce_scan_delay(NULL);
  808.         if (o.debugging > 1) { log_write(LOG_STDOUT, "Timeout, resending to portno/progno %lu\n", current->portno); }
  809.         current->trynum++;
  810.         gettimeofday(¤t->sent[current->trynum], NULL);
  811.         now = current->sent[current->trynum];
  812.         if ((scantype == SYN_SCAN) || (scantype == WINDOW_SCAN) || (scantype == ACK_SCAN)) {          
  813.           if (o.fragscan)
  814.             send_small_fragz_decoys(rawsd, &target->host, sequences[current->trynum], o.magic_port + tries * 3 + current->trynum, current->portno, scanflags);
  815.           else 
  816.             send_tcp_raw_decoys(rawsd, &target->host, o.magic_port + 
  817.                     tries * 3 + current->trynum, 
  818.                     current->portno, 
  819.                     sequences[current->trynum], 
  820.                     ack_number, scanflags, 0, NULL, 0, 
  821.                     o.extra_payload, 
  822.                     o.extra_payload_length);
  823.  
  824.         } else if (scantype == RPC_SCAN) {
  825.           if (send_rpc_query(&target->host, rsi.rpc_current_port->portno,
  826.                      rsi.rpc_current_port->proto, 
  827.                      current->portno, current - scan, 
  828.                      current->trynum) == -1) {
  829.             /* Futz, I'll give up on this guy ... */
  830.             rsi.rpc_status = RPC_STATUS_NOT_RPC;
  831.             break;
  832.           }
  833.         } else { /* Connect scan */
  834.           /* Unfortunately, retries cost us a socket!  If we are
  835.              out of sockets, we must drop one of our earlier tries
  836.              :( */
  837.           if (ss.numqueries_outstanding >= ss.max_width) {        
  838.             victim = -1;
  839.             for(i=0; i < current->trynum; i++)
  840.               if (current->sd[i] >= 0) {
  841.             victim = i;
  842.             break;
  843.               }
  844.             if (victim == -1) 
  845.               fatal("Illegal situation in pos_scan -- please report to fyodor@dhp.com");
  846.             csi.socklookup[current->sd[victim]] = NULL;
  847.             FD_CLR(current->sd[victim], &csi.fds_read);
  848.             FD_CLR(current->sd[victim], &csi.fds_write);
  849.             FD_CLR(current->sd[victim], &csi.fds_except);
  850.             close(current->sd[victim]);
  851.             current->sd[victim] = -1;
  852.           } else {
  853.             ss.numqueries_outstanding++;
  854.           }
  855.           res = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  856.           if (res == -1) pfatal("Socket troubles in pos_scan 143");
  857.           csi.socklookup[res] = current;
  858.           unblock_socket(res);
  859.           init_socket(res);
  860.           sock.sin_port = htons(current->portno);
  861.           current->sd[current->trynum] = res;        
  862.           res =  connect(res,(struct sockaddr *)&sock,sizeof(struct sockaddr));
  863.           if (res != -1) {
  864.             posportupdate(target, current, current->trynum, scan, &ss, scantype, PORT_OPEN, &pil, &csi);
  865.           } else {
  866.             switch(errno) {
  867.             case EINPROGRESS: /* The one I always see */
  868.             case EAGAIN:
  869.               /* GOOD REASON FOR THIS????block_socket(sockets[current_socket]); */
  870.               if (csi.maxsd < current->sd[current->trynum])
  871.             csi.maxsd = current->sd[current->trynum];
  872.               FD_SET( current->sd[current->trynum], &csi.fds_write);
  873.               FD_SET( current->sd[current->trynum], &csi.fds_read);
  874.               FD_SET( current->sd[current->trynum], &csi.fds_except);
  875.               break;
  876.             default:
  877.               if (!connecterror) {    
  878.             connecterror++;
  879.             fprintf(stderr, "Strange error from connect (%d):", errno);
  880.             fflush(stdout);
  881.             perror(""); /*falling through intentionally*/
  882.               }
  883.             case ECONNREFUSED:
  884.               posportupdate(target, current, current->trynum, scan, &ss, scantype, PORT_CLOSED, &pil, &csi);
  885.               break;
  886.             }            
  887.           }
  888.         }
  889.         if (senddelay) usleep(senddelay);
  890.           }
  891.         }
  892.       } else { 
  893.         if (current->state != PORT_FRESH) 
  894.           fatal("State mismatch!!@ %d", current->state);
  895.         /* current->state == PORT_FRESH */
  896.         /* OK, now we have gone through our list of in-transit queries, so now
  897.            we try to send off new queries if we can ... */
  898.         if (ss.numqueries_outstanding >= (int) ss.numqueries_ideal) break;
  899.         if (o.scan_delay) enforce_scan_delay(NULL);
  900.         if (o.debugging > 1) log_write(LOG_STDOUT, "Sending initial query to port/prog %lu\n", current->portno);
  901.         /* Otherwise lets send a packet! */
  902.         current->state = PORT_TESTING;
  903.         current->trynum = 0;
  904.         /*    if (!testinglist) testinglist = current; */
  905.         ss.numqueries_outstanding++;
  906.         gettimeofday(¤t->sent[0], NULL);
  907.         if ((scantype == SYN_SCAN) || (scantype == WINDOW_SCAN) || 
  908.         (scantype == ACK_SCAN)) {      
  909.           if (o.fragscan)
  910.         send_small_fragz_decoys(rawsd, &target->host, sequences[current->trynum], o.magic_port + tries * 3, current->portno, scanflags);
  911.           else
  912.         send_tcp_raw_decoys(rawsd, &target->host, 
  913.                     o.magic_port + tries * 3, current->portno,
  914.                     sequences[current->trynum], ack_number, 
  915.                     scanflags, 0, NULL, 0, o.extra_payload, 
  916.                     o.extra_payload_length);
  917.         } else if (scantype == RPC_SCAN) {
  918.           if (send_rpc_query(&target->host, rsi.rpc_current_port->portno,
  919.                  rsi.rpc_current_port->proto, current->portno, 
  920.                  current - scan, current->trynum) == -1) {
  921.         /* Futz, I'll give up on this guy ... */
  922.         rsi.rpc_status = RPC_STATUS_NOT_RPC;
  923.         break;
  924.           }
  925.         } else { /* CONNECT SCAN */
  926.           res = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  927.           if (res == -1) pfatal("Socket troubles in pos_scan 11234");
  928. #ifdef WIN32
  929.           if(res > 2047)
  930.             fatal("got sd > 2047 in pos_scan\n");
  931. #endif
  932.           csi.socklookup[res] = current;
  933.           unblock_socket(res);
  934.           init_socket(res);
  935.           sock.sin_port = htons(current->portno);
  936.           current->sd[current->trynum] = res;        
  937.           res =  connect(res,(struct sockaddr *)&sock,sizeof(struct sockaddr));
  938.           if (res != -1) {
  939.         posportupdate(target, current, current->trynum, scan, &ss, scantype, PORT_OPEN, &pil, &csi);
  940.           } else {
  941.         switch(errno) {
  942.         case EINPROGRESS: /* The one I always see */
  943.         case EAGAIN:
  944.           /* GOOD REASON FOR THIS????block_socket(sockets[current_socket]); */
  945.           if (csi.maxsd < current->sd[current->trynum])
  946.             csi.maxsd = current->sd[current->trynum];
  947.           FD_SET( current->sd[current->trynum], &csi.fds_write);
  948.           FD_SET( current->sd[current->trynum], &csi.fds_read);
  949.           FD_SET( current->sd[current->trynum], &csi.fds_except);
  950.           break;
  951.         default:
  952.           if (!connecterror) {    
  953.             connecterror++;
  954.             fprintf(stderr, "Strange error from connect (%d):", errno);
  955.             fflush(stdout);
  956.             perror(""); /*falling through intentionally*/
  957.           }
  958.         case ECONNREFUSED:
  959.           posportupdate(target, current, current->trynum, scan, &ss, scantype, PORT_CLOSED, &pil, &csi);
  960.           break;
  961.         }            
  962.           }        
  963.         }
  964.         if (senddelay) usleep(senddelay);
  965.       }
  966.     }
  967.     /*      if (o.debugging > 1) log_write(LOG_STDOUT, "Ideal number of queries: %d outstanding: %d max %d ports_left %d timeout %d\n", (int) ss.numqueries_ideal, ss.numqueries_outstanding, ss.max_width, ss.ports_left, target->to.timeout);*/
  968.  
  969.     /* Now that we have sent the packets we wait for responses */
  970.     ss.alreadydecreasedqueries = 0;
  971.     if ((scantype == SYN_SCAN) || (scantype == WINDOW_SCAN) || (scantype == ACK_SCAN))
  972.       get_syn_results(target, scan, &ss, &pil, portlookup, pd, sequences, scantype);
  973.     else if (scantype == RPC_SCAN) {
  974.       /* We only bother worrying about responses if we haven't reached
  975.          a conclusion yet */
  976.       if (rsi.rpc_status == RPC_STATUS_UNKNOWN) {      
  977.         get_rpc_results(target, scan, &ss, &pil, &rsi);
  978.       }
  979.       if (rsi.rpc_status != RPC_STATUS_UNKNOWN)
  980.         break;
  981.     }
  982.     else {
  983.       get_connect_results(target, scan, &ss, &pil, portlookup, sequences, &csi);    
  984.     }
  985.  
  986.     /* If we timed out while trying to get results -- we're outta here! */
  987.     if (target->timedout)
  988.       goto posscan_timedout;
  989.       }
  990.  
  991.     if (scantype == RPC_SCAN) {
  992.       /* Now we figure out the results of the port we just RPC scanned */
  993.       rsi.rpc_current_port->rpc_status = rsi.rpc_status;
  994.       if (rsi.rpc_status == RPC_STATUS_GOOD_PROG) {      
  995.     rsi.rpc_current_port->rpc_program = rsi.rpc_program;
  996.     rsi.rpc_current_port->rpc_lowver = rsi.rpc_lowver;
  997.     rsi.rpc_current_port->rpc_highver = rsi.rpc_highver;
  998.       }
  999.       
  1000.       /* Next let us increment the port we are working on, since
  1001.      this one is done ... */
  1002.       /*      rsi.rpc_current_port = nextport(&target->ports, rsi.rpc_current_port,
  1003.                              0, PORT_OPEN);
  1004.        if (!rsi.rpc_current_port)
  1005.       break; */
  1006.       /* Time to put our RPC program scan list back together for the
  1007.      next port ... */
  1008.       for(j = 0; j < rsi.rpc_number; j++) {
  1009.     scan[j].state = PORT_FRESH;
  1010.     scan[j].trynum = 0;
  1011.     scan[j].prev = j-1;
  1012.     if (j < rsi.rpc_number -1 ) scan[j].next = j+1;
  1013.     else scan[j].next = -1;
  1014.       }
  1015.       current = pil.testinglist = &scan[0]; 
  1016.       pil.firewalled = NULL;
  1017.       ss.numqueries_outstanding = 0;
  1018.       /* Now we out o' here! */
  1019.       continue;
  1020.     }
  1021.  
  1022.     if (ss.numqueries_outstanding != 0) {
  1023.       fatal("Bean counting error no. 4321897: ports_left: %d numqueries_outstanding: %d\n", ss.ports_left, ss.numqueries_outstanding);
  1024.     }
  1025.  
  1026.     /* We only want to try again if the 'firewalled' list contains elements,
  1027.        meaning that some ports timed out.  We retry until nothing
  1028.        changes for a round (not counting the very first round).
  1029.     */
  1030.     if (pil.firewalled) {
  1031.       if (tries == 0 || ss.changed) {    
  1032.     pil.testinglist = pil.firewalled;
  1033.     for( current = pil.testinglist; current ; 
  1034.          current = (current->next > -1)? &scan[current->next] : NULL) {
  1035.       current->state = PORT_FRESH;
  1036.       current->trynum = 0;
  1037.       current->sd[0] = current->sd[1] = current->sd[2] = -1;
  1038.       if (o.debugging) { 
  1039.         log_write(LOG_STDOUT, "Preparing for retry, nonresponsive port %lu noted\n", current->portno); 
  1040.       }
  1041.     }
  1042.     pil.firewalled = NULL;
  1043.       } else {
  1044.     /* Consider the ports firewalled */    
  1045.     for( current = pil.firewalled; current ; 
  1046.          current = (current->next > -1)? &scan[current->next] : NULL) {
  1047.       addport(&target->ports, current->portno, IPPROTO_TCP, NULL, PORT_FIREWALLED);
  1048.     }
  1049.     pil.testinglist = NULL;
  1050.       }
  1051.       tries++;
  1052.     }
  1053.     ss.numqueries_ideal = initial_packet_width;
  1054.     if (o.debugging)
  1055.       log_write(LOG_STDOUT, "Done with round %d\n", tries);
  1056.   } while(pil.testinglist && tries < 20);
  1057.  
  1058.   if (tries == 20) {
  1059.     error("WARNING: GAVE UP ON SCAN AFTER 20 RETRIES");
  1060.   }
  1061.   
  1062.   if (o.verbose)
  1063.     log_write(LOG_STDOUT, "The %s took %ld %s to scan %d ports.\n", scantype2str(scantype),  (long) time(NULL) - starttime, (((long) time(NULL) - starttime) == 1)? "second" : "seconds", numports);
  1064.   
  1065.  posscan_timedout:
  1066.   
  1067.   free(scan);
  1068.   if (rawsd >= 0) 
  1069.     close(rawsd);
  1070.   if (pd)
  1071.     pcap_close(pd);
  1072.   if (scantype == RPC_SCAN)
  1073.     close_rpc_query_sockets();
  1074.   return;
  1075. }
  1076.  
  1077. /* FTP bounce attack scan.  This function is rather lame and should be
  1078.    rewritten.  But I don't think it is used much anyway.  If I'm going to
  1079.    allow FTP bounce scan, I should really allow SOCKS proxy scan.  */
  1080. void bounce_scan(struct hoststruct *target, u16 *portarray, int numports,
  1081.          struct ftpinfo *ftp) {
  1082.   int starttime,  res , sd = ftp->sd,  i=0;
  1083.   char *t = (char *)&target->host; 
  1084.   int retriesleft = FTP_RETRIES;
  1085.   char recvbuf[2048]; 
  1086.   char targetstr[20];
  1087.   char command[512];
  1088.   unsigned short portno,p1,p2;
  1089.   struct timeval now;
  1090.  
  1091.   if (! numports) return;         /* nothing to scan for */
  1092.  
  1093.   snprintf(targetstr, 20, "%d,%d,%d,%d,", UC(t[0]), UC(t[1]), UC(t[2]), UC(t[3]));
  1094.  
  1095.   starttime = time(NULL);
  1096.   if (o.verbose || o.debugging)
  1097.     log_write(LOG_STDOUT, "Initiating TCP ftp bounce scan against %s (%s)\n",
  1098.         target->name,  inet_ntoa(target->host));
  1099.   for(i=0; portarray[i]; i++) {
  1100.  
  1101.     /* Check for timeout */
  1102.     if (o.host_timeout) {
  1103.       gettimeofday(&now, NULL);
  1104.       if ((TIMEVAL_MSEC_SUBTRACT(now, target->host_timeout) >= 0))
  1105.     {
  1106.       target->timedout = 1;
  1107.       return;
  1108.     }
  1109.     }
  1110.  
  1111.     portno = htons(portarray[i]);
  1112.     p1 = ((unsigned char *) &portno)[0];
  1113.     p2 = ((unsigned char *) &portno)[1];
  1114.     snprintf(command, 512, "PORT %s%i,%i\r\n", targetstr, p1,p2);
  1115.     if (o.debugging) log_write(LOG_STDOUT, "Attempting command: %s", command);
  1116.     if (send(sd, command, strlen(command), 0) < 0 ) {
  1117.       perror("send in bounce_scan");
  1118.       if (retriesleft) {
  1119.     if (o.verbose || o.debugging) 
  1120.       log_write(LOG_STDOUT, "Our ftp proxy server hung up on us!  retrying\n");
  1121.     retriesleft--;
  1122.     close(sd);
  1123.     ftp->sd = ftp_anon_connect(ftp);
  1124.     if (ftp->sd < 0) return;
  1125.     sd = ftp->sd;
  1126.     i--;
  1127.       }
  1128.       else {
  1129.     fprintf(stderr, "Our socket descriptor is dead and we are out of retries. Giving up.\n");
  1130.     close(sd);
  1131.     ftp->sd = -1;
  1132.     return;
  1133.       }
  1134.     } else { /* Our send is good */
  1135.       res = recvtime(sd, recvbuf, 2048,15);
  1136.       if (res <= 0) perror("recv problem from ftp bounce server\n");
  1137.   
  1138.       else { /* our recv is good */
  1139.     recvbuf[res] = '\0';
  1140.     if (o.debugging) log_write(LOG_STDOUT, "result of port query on port %i: %s", 
  1141.                  portarray[i],  recvbuf);
  1142.     if (recvbuf[0] == '5') {
  1143.       if (portarray[i] > 1023) {
  1144.         fprintf(stderr, "Your ftp bounce server sucks, it won't let us feed bogus ports!\n");
  1145.         exit(1);
  1146.       }
  1147.       else {
  1148.         fprintf(stderr, "Your ftp bounce server doesn't allow priviliged ports, skipping them.\n");
  1149.         while(portarray[i] && portarray[i] < 1024) i++;
  1150.         if (!portarray[i]) {
  1151.           fprintf(stderr, "And you didn't want to scan any unpriviliged ports.  Giving up.\n");
  1152.           /*      close(sd);
  1153.               ftp->sd = -1;
  1154.               return *ports;*/
  1155.           /* screw this gentle return crap!  This is an emergency! */
  1156.           exit(1);
  1157.         }
  1158.       }  
  1159.     }
  1160.     else  /* Not an error message */
  1161.       if (send(sd, "LIST\r\n", 6, 0) > 0 ) {
  1162.         res = recvtime(sd, recvbuf, 2048,12);
  1163.         if (res <= 0) {
  1164.           perror("recv problem from ftp bounce server\n");
  1165.         }
  1166.         else {
  1167.           recvbuf[res] = '\0';
  1168.           if (o.debugging) log_write(LOG_STDOUT, "result of LIST: %s", recvbuf);
  1169.           if (!strncmp(recvbuf, "500", 3)) {
  1170.         /* fuck, we are not aligned properly */
  1171.         if (o.verbose || o.debugging)
  1172.           fprintf(stderr, "FTP command misalignment detected ... correcting.\n");
  1173.         res = recvtime(sd, recvbuf, 2048,10);
  1174.           }
  1175.           if (recvbuf[0] == '1' || recvbuf[0] == '2') {
  1176.         addport(&target->ports, portarray[i], IPPROTO_TCP, NULL, PORT_OPEN);
  1177.         if (recvbuf[0] == '1') {
  1178.           res = recvtime(sd, recvbuf, 2048,5);
  1179.           recvbuf[res] = '\0';
  1180.           if (res > 0) {
  1181.             if (o.debugging) log_write(LOG_STDOUT, "nxt line: %s", recvbuf);
  1182.             if (recvbuf[0] == '4' && recvbuf[1] == '2' && 
  1183.             recvbuf[2] == '6') {              
  1184.               deleteport(&target->ports, portarray[i], IPPROTO_TCP);
  1185.               if (o.debugging || o.verbose)
  1186.             log_write(LOG_STDOUT, "Changed my mind about port %i\n", portarray[i]);
  1187.             }
  1188.           }
  1189.         }
  1190.           } else {
  1191.         /* This means the port is closed ... */
  1192.         addport(&target->ports, portarray[i], IPPROTO_TCP, NULL, PORT_CLOSED);
  1193.           }
  1194.         }
  1195.       }
  1196.       }
  1197.     }
  1198.   }
  1199.  
  1200.   if (o.debugging || o.verbose) 
  1201.     log_write(LOG_STDOUT, "Scanned %d ports in %ld seconds via the Bounce scan.\n",
  1202.         numports, (long) time(NULL) - starttime);
  1203.   return;
  1204. }
  1205.  
  1206. /* Handles the scan types where no positive-acknowledgement of open
  1207.    port is received (those scans are in pos_scan).  Super_scan
  1208.    includes scans such as FIN/XMAS/NULL/Maimon/UDP and IP Proto scans */
  1209. void super_scan(struct hoststruct *target, u16 *portarray, int numports,
  1210.         stype scantype) {
  1211.   int initial_packet_width;  /* How many scan packets in parallel (to start with) */
  1212.   int packet_incr = 4; /* How much we increase the parallel packets by each round */
  1213.   double fallback_percent = 0.7;
  1214.   int rawsd;
  1215.   char myname[513];
  1216.   int scanflags = 0;
  1217.  
  1218.   int dropped = 0;  /* These three are for UDP squelching */
  1219.   int freshportstried = 0;
  1220.   int senddelay = 0;
  1221.   pcap_t *pd;
  1222.   unsigned int bytes;
  1223.   struct ip *ip, *ip2;
  1224.   struct tcphdr *tcp;
  1225.   char filter[512];
  1226.   char *p;
  1227.   int changed = 0;  /* Have we found new ports (or rejected earlier "found" ones) this round? */
  1228.   int numqueries_outstanding = 0; /* How many unexpired queries are on the 'net right now? */
  1229.   double numqueries_ideal; /* How many do we WANT to be on the 'net right now? */
  1230.   int max_width; /* No more packets than this at once, pleeze */
  1231.   int tries = 0;
  1232.   int tmp = 0;
  1233.   int starttime;
  1234.   u16 newport;
  1235.   int newstate = 999; /* This ought to break something if used illegally */
  1236.   struct hostent *myhostent = NULL;
  1237.   struct portinfo *scan, *openlist, *current, *testinglist, *next;
  1238.   int portlookup[65536]; /* Indexes port number -> scan[] index */
  1239.   struct timeval now, end;
  1240.   int packcount, timedout;
  1241.   int UDPPacketWarning = 0;
  1242.   int i;
  1243.   u16 *data;
  1244.   int packet_trynum = 0;
  1245.   int windowdecrease = 0; /* Has the window been decreased this round yet? */
  1246.   struct icmp *icmp;
  1247.   int portno;
  1248.   struct port *current_port_tmp;
  1249.  
  1250.   if (target->timedout)
  1251.     return;
  1252.  
  1253.   if (! numports) return;         /* nothing to scan for */
  1254.  
  1255.   if (o.debugging) 
  1256.     log_write(LOG_STDOUT, "Starting super_scan\n");
  1257.  
  1258.   max_width = (o.max_parallelism)? o.max_parallelism : 125;
  1259.   numqueries_ideal = initial_packet_width = MIN(max_width, 10);
  1260.  
  1261.   memset(portlookup, 255, 65536 * sizeof(int)); /* 0xffffffff better always be (int) -1 */
  1262.   scan = (struct portinfo *) safe_malloc(numports * sizeof(struct portinfo));
  1263.  
  1264.   /* Initialize timeout info */
  1265.   /*
  1266.     target->to.srtt = (target->rtt > 0)? 4 * target->rtt : 1000000;
  1267.     target->to.rttvar = (target->rtt > 0)? target->rtt / 2 : 1000000;
  1268.     target->to.timeout = target->to.srtt + 4 * target->to.rttvar;
  1269.   */
  1270.  
  1271.   /* Initialize our portlist (scan) */
  1272.   for(i = 0; i < numports; i++) {
  1273.     scan[i].state = PORT_FRESH;
  1274.     scan[i].portno = portarray[i];
  1275.     scan[i].trynum = 0;
  1276.     scan[i].prev = i-1;
  1277.     if (i < numports -1 ) scan[i].next = i+1;
  1278.     else scan[i].next = -1;
  1279.     portlookup[portarray[i]] = i;
  1280.   }
  1281.  
  1282.   current = testinglist = &scan[0]; /* fresh == unscanned ports, testinglist is a list of all ports that haven't been determined to be closed yet */
  1283.   openlist = NULL; /* we haven't shown any ports to be open yet... */
  1284.  
  1285.  
  1286.     
  1287.   /* Init our raw socket */
  1288.   if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  1289.     pfatal("socket troubles in super_scan");
  1290.   broadcast_socket(rawsd); /* This isn't pretty, but I don't have much of a
  1291.                   choice */
  1292.   /* No reason to do this since we don't receive on this socket,
  1293.      and it can cause ENOBUF errors if socket transmit buffers
  1294.      overflow 
  1295.      unblock_socket(rawsd);
  1296.   */
  1297.  
  1298.   /* Do we have a correct source address? */
  1299.   if (!target->source_ip.s_addr) {
  1300.     if (gethostname(myname, MAXHOSTNAMELEN) != 0 && 
  1301.     !((myhostent = gethostbyname(myname))))
  1302.       fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n"); 
  1303.     memcpy(&target->source_ip, myhostent->h_addr_list[0], sizeof(struct in_addr));
  1304.     if (o.debugging || o.verbose) 
  1305.       log_write(LOG_STDOUT, "We skillfully deduced that your address is %s\n",
  1306.           inet_ntoa(target->source_ip));
  1307.   }
  1308.  
  1309.   /* Now for the pcap opening nonsense ... */
  1310.   /* Note that the snaplen is 92 = 64 byte max IPhdr + 24 byte max link_layer
  1311.    * header + 4 bytes of TCP port info.
  1312.    */
  1313.  
  1314.   pd = my_pcap_open_live(target->device, 92,  (o.spoofsource)? 1 : 0, 10);
  1315.  
  1316.  
  1317.   flt_srchost = target->host.s_addr;
  1318.   flt_dsthost = target->source_ip.s_addr;
  1319.   flt_baseport = o.magic_port;
  1320.  
  1321.   p = strdup(inet_ntoa(target->host));
  1322.   snprintf(filter, sizeof(filter), "(icmp and dst host %s) or (tcp and src host %s and dst host %s and ( dst port %d or dst port %d))", inet_ntoa(target->source_ip), p, inet_ntoa(target->source_ip), o.magic_port , o.magic_port + 1);
  1323.   free(p);
  1324.  
  1325.   set_pcap_filter(target, pd, flt_icmptcp_2port, filter);
  1326.  
  1327.   if (scantype == XMAS_SCAN) scanflags = TH_FIN|TH_URG|TH_PUSH;
  1328.   else if (scantype == NULL_SCAN) scanflags = 0;
  1329.   else if (scantype == FIN_SCAN) scanflags = TH_FIN;
  1330.   else if (scantype == MAIMON_SCAN) scanflags = TH_FIN|TH_ACK;
  1331.   else if (scantype != UDP_SCAN && scantype != IPPROT_SCAN) {
  1332.     fatal("Unknown scan type for super_scan"); }
  1333.  
  1334.   starttime = time(NULL);
  1335.  
  1336.   if (o.debugging || o.verbose)
  1337.     log_write(LOG_STDOUT, "Initiating %s against %s (%s)\n", scantype2str(scantype), target->name, inet_ntoa(target->host));
  1338.   
  1339.  
  1340.   do {
  1341.     changed = 0;
  1342.     if (tries > 3 && senddelay == 0) senddelay = 10000; 
  1343.                                
  1344.     while(testinglist != NULL)  /* While we have live queries or more ports to scan */
  1345.       {
  1346.     /* Check the possible retransmissions first */
  1347.     gettimeofday(&now, NULL);
  1348.  
  1349.     /* Insure we haven't overrun our allotted time ... */
  1350.     if (o.host_timeout && numqueries_outstanding > 0 && (TIMEVAL_MSEC_SUBTRACT(now, target->host_timeout) >= 0))
  1351.       {
  1352.         target->timedout = 1;
  1353.         goto superscan_timedout;
  1354.       }
  1355.  
  1356.     for( current = testinglist; current ; current = next) {
  1357.       next = (current->next > -1)? &scan[current->next] : NULL;
  1358.       if (current->state == PORT_TESTING) {
  1359.         if ( TIMEVAL_SUBTRACT(now, current->sent[current->trynum]) > target->to.timeout) {
  1360.           if (current->trynum > 0) {
  1361.         /* We consider this port valid, move it to open list */
  1362.         if (o.debugging > 1) { log_write(LOG_STDOUT, "Moving port %lu to the open list\n", current->portno); }
  1363.         freshportstried--;
  1364.         current->state = PORT_OPEN;
  1365.         /* First delete from old list */
  1366.         if (current->next > -1) scan[current->next].prev = current->prev;
  1367.         if (current->prev > -1) scan[current->prev].next = current->next;
  1368.         if (current == testinglist)
  1369.           testinglist = (current->next >= 0)?  &scan[current->next] : NULL;
  1370.         current->next = current->prev = -1;
  1371.  
  1372.         /* Now move into new list */
  1373.         if (!openlist) openlist = current;
  1374.         else {
  1375.           current->next = openlist - scan;
  1376.           openlist = current;
  1377.           scan[current->next].prev = current - scan;          
  1378.         }
  1379.         numqueries_outstanding--;
  1380.           } else {
  1381.         /* Initial timeout ... we've got to resend */
  1382.         if (o.scan_delay) enforce_scan_delay(NULL);
  1383.         if (o.debugging > 1) { log_write(LOG_STDOUT, "Initial timeout, resending to portno %lu\n", current->portno); }
  1384.         current->trynum++;
  1385.         /* If they didn't specify the magic port, we use magic_port +1
  1386.            so we can tell that it was a retransmit later */
  1387.         i = (o.magic_port_set)? o.magic_port : o.magic_port + 1;
  1388.         gettimeofday(¤t->sent[1], NULL);
  1389.         now = current->sent[1];
  1390.         if (o.fragscan)
  1391.           send_small_fragz_decoys(rawsd, &target->host, 0,i, current->portno, scanflags);
  1392.         else if (scantype == UDP_SCAN)
  1393.           send_udp_raw_decoys(rawsd, &target->host, i,
  1394.                       current->portno, o.extra_payload, o.extra_payload_length);
  1395.         else if (scantype == IPPROT_SCAN)
  1396.           send_ip_raw_decoys(rawsd, &target->host, current->portno, o.extra_payload, o.extra_payload_length);
  1397.         else
  1398.           send_tcp_raw_decoys(rawsd, &target->host, i, 
  1399.                       current->portno, 0, 0, scanflags, 0, NULL, 0,
  1400.                       o.extra_payload, o.extra_payload_length);
  1401.         if (senddelay &&
  1402.             (scantype == UDP_SCAN || scantype == IPPROT_SCAN))
  1403.           usleep(senddelay);
  1404.           }
  1405.         }
  1406.       } else { 
  1407.         /* current->state == PORT_FRESH */
  1408.         /* OK, now we have gone through our list of in-transit queries, 
  1409.            so now we try to send off new queries if we can ... */
  1410.         if (numqueries_outstanding >= (int) numqueries_ideal) break;
  1411.         if (o.scan_delay) enforce_scan_delay(NULL);
  1412.         if (o.debugging > 1) log_write(LOG_STDOUT, "Sending initial query to port %lu\n", current->portno);
  1413.         freshportstried++;
  1414.         /* lets send a packet! */
  1415.         current->state = PORT_TESTING;
  1416.         /*    if (!testinglist) testinglist = current; */
  1417.         numqueries_outstanding++;
  1418.         gettimeofday(¤t->sent[0], NULL);
  1419.         if (o.fragscan)
  1420.           send_small_fragz_decoys(rawsd, &target->host, 0, o.magic_port, current->portno, scanflags);
  1421.         else if (scantype == UDP_SCAN)
  1422.           send_udp_raw_decoys(rawsd, &target->host, o.magic_port,
  1423.                   current->portno, o.extra_payload, o.extra_payload_length);
  1424.         else if (scantype == IPPROT_SCAN)
  1425.           send_ip_raw_decoys(rawsd, &target->host,
  1426.                  current->portno, o.extra_payload, o.extra_payload_length);
  1427.         else
  1428.           send_tcp_raw_decoys(rawsd, &target->host, o.magic_port, 
  1429.                   current->portno, 0, 0, scanflags, 0, NULL, 0,
  1430.                   o.extra_payload, o.extra_payload_length);
  1431.         if ((scantype == UDP_SCAN || scantype == IPPROT_SCAN) &&
  1432.         senddelay)
  1433.           usleep(senddelay);
  1434.       }
  1435.     }
  1436.  
  1437.     if (o.debugging > 1) log_write(LOG_STDOUT, "Ideal number of queries: %d\n", (int) numqueries_ideal);
  1438.     tmp++;
  1439.     /* Now that we have sent the packets we wait for responses */
  1440.     windowdecrease = 0;
  1441.     timedout = packcount = 0;
  1442.     gettimeofday(&now, NULL);
  1443.     if (o.host_timeout && (TIMEVAL_MSEC_SUBTRACT(now, target->host_timeout) >= 0))
  1444.       {
  1445.         target->timedout = 1;
  1446.         goto superscan_timedout;
  1447.       }
  1448.     while (!timedout && numqueries_outstanding > 0 && ( ip = (struct ip*) readip_pcap(pd, &bytes, target->to.timeout)))
  1449.       {
  1450.         if (++packcount >= 30) {
  1451.           /* We don't want to allow for the possibility if this going
  1452.          forever */
  1453.           gettimeofday(&end, NULL);
  1454.           if (TIMEVAL_SUBTRACT(end, now) > 8000000)
  1455.         timedout = 1;
  1456.         }
  1457.         if (bytes < (4 * ip->ip_hl) + 4U)
  1458.           continue;    
  1459.         current = NULL;
  1460.         if (ip->ip_p == IPPROTO_ICMP ||
  1461.         ip->ip_src.s_addr == target->host.s_addr) {
  1462.           if (ip->ip_p == IPPROTO_TCP) {
  1463.         tcp = (struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl);
  1464.         if (tcp->th_flags & TH_RST) {        
  1465.           newstate = PORT_CLOSED;
  1466.           newport = ntohs(tcp->th_sport);
  1467.           if (portlookup[newport] < 0) {
  1468.             if (o.debugging) {
  1469.               log_write(LOG_STDOUT, "Strange packet from port %d:\n", ntohs(tcp->th_sport));
  1470.               readtcppacket((unsigned char *)ip, bytes);
  1471.             }
  1472.             current = NULL;
  1473.             continue;
  1474.           }      
  1475.           current = &scan[portlookup[newport]];
  1476.         
  1477.           if (ntohs(tcp->th_dport) != o.magic_port && 
  1478.               ntohs(tcp->th_dport) != o.magic_port + 1) {
  1479.             if (o.debugging)  {        
  1480.               error("BAD TCP packet detected to port %d from port %d", ntohs(tcp->th_dport), newport);
  1481.             }
  1482.             continue;        
  1483.           }
  1484.         
  1485.           if (current->state != PORT_TESTING && o.debugging) {
  1486.             error("TCP packet detected from port %d which is in state %d (should usually be PORT_TESTING (but not always)", 
  1487.               newport, current->state); 
  1488.           }
  1489.         
  1490.           if (!o.magic_port_set) {
  1491.             packet_trynum = ntohs(tcp->th_dport) - o.magic_port;
  1492.             if ((packet_trynum|1) != 1) packet_trynum = -1;
  1493.           }  else packet_trynum = -1;
  1494.           if (current->trynum == 0) packet_trynum = 0;
  1495.         } else { continue; } /* Wrong TCP flags */
  1496.           
  1497.           } else if (ip->ip_p == IPPROTO_ICMP) {
  1498.         icmp = (struct icmp *) ((char *)ip + 4 * ip->ip_hl);
  1499.         ip2 = (struct ip *) (((char *) icmp) + 8);
  1500.         if (ip2->ip_dst.s_addr != target->host.s_addr)
  1501.           continue;
  1502.         data = (u16 *) ((char *)ip2 + 4 * ip2->ip_hl);
  1503.         /*        log_write(LOG_STDOUT, "Caught ICMP packet:\n");
  1504.                 hdump(icmp, ntohs(ip->ip_len) - sizeof(struct ip)); */
  1505.  
  1506.         if (icmp->icmp_type == 3) {
  1507.           if (scantype != IPPROT_SCAN)
  1508.             newport = ntohs(data[1]);
  1509.           else
  1510.             newport = ip2->ip_p;
  1511.           if (portlookup[newport] < 0) {
  1512.             if (o.debugging) {
  1513.               log_write(LOG_STDOUT, "Strange ICMP packet type 3 code %d related to port %d:\n", icmp->icmp_code, newport);
  1514.               readtcppacket((unsigned char *)ip, bytes);        
  1515.             }
  1516.             continue;        
  1517.           }
  1518.           current = &scan[portlookup[newport]];
  1519.           if (!o.magic_port_set) {
  1520.             packet_trynum = ntohs(data[0]) - o.magic_port;
  1521.             if ((packet_trynum|1) != 1) packet_trynum = -1;
  1522.           } else {
  1523.             if (current->trynum == 0)  {
  1524.               packet_trynum = 0;
  1525.             }
  1526.             else packet_trynum = -1;
  1527.           }
  1528.         
  1529.           switch(icmp->icmp_code) {
  1530.           
  1531.           case 1: /* Host unreachable */
  1532.           case 2: /* pr0t0c0l unreachable */
  1533.             if (scantype == IPPROT_SCAN) {
  1534.               newstate = PORT_CLOSED;
  1535.             } else
  1536.               newstate = PORT_FIREWALLED;
  1537.             break;
  1538.           
  1539.           case 3: /* p0rt unreachable */        
  1540.             if (scantype == UDP_SCAN) {
  1541.               newstate = PORT_CLOSED;
  1542.             } else newstate = PORT_FIREWALLED;
  1543.             break;
  1544.           
  1545.           case 9:
  1546.           case 10:
  1547.           case 13: /* Administratively prohibited packet */
  1548.             newstate = PORT_FIREWALLED;
  1549.             break;        
  1550.           
  1551.           default:
  1552.             if (o.debugging) {
  1553.               error("Received strange ICMP destunreach response -- code: %d", icmp->icmp_code);
  1554.               hdump((unsigned char *)icmp, ntohs(ip->ip_len) - 
  1555.                 sizeof(struct ip));
  1556.             }
  1557.             continue;
  1558.           }
  1559.         }
  1560.           } else if (ip->ip_p == IPPROTO_UDP) {
  1561.         if (UDPPacketWarning == 0) {
  1562.           UDPPacketWarning = 1;
  1563.           if (o.debugging)
  1564.             error("UDP packet received\n");
  1565.         }
  1566.         continue;
  1567.           } else if (scantype == IPPROT_SCAN) {
  1568.         if (o.debugging)
  1569.           error("packet with protocol %d received\n", ip->ip_p);
  1570.           }
  1571.         
  1572.           if (current) {      
  1573.         if (current->state == PORT_CLOSED && (packet_trynum < 0)) {
  1574.           target->to.rttvar = (int) (target->to.rttvar * 1.2);
  1575.           if (o.debugging) { log_write(LOG_STDOUT, "Late packet, couldn't figure out sendno so we do varianceincrease to %d\n", target->to.rttvar); 
  1576.           }
  1577.         } 
  1578.         if (packet_trynum > -1) {        
  1579.           /* Update our records */
  1580.           adjust_timeouts(current->sent[packet_trynum], &(target->to));
  1581.           numqueries_ideal = MIN(numqueries_ideal + (packet_incr/numqueries_ideal), max_width);
  1582.           if (packet_trynum > 0 && current->trynum > 0) {
  1583.             /* The first packet was apparently lost, slow down */
  1584.             dropped++;
  1585.             if (freshportstried > 50 && ((double) dropped/freshportstried) > 0.3) {
  1586.               if (!senddelay) senddelay = 50000;
  1587.               else senddelay = MIN(senddelay * 2, 1000000);
  1588.               if (senddelay >= 200000 &&
  1589.               (scantype == UDP_SCAN || scantype == IPPROT_SCAN))
  1590.             max_width = MIN(max_width,2);
  1591.               freshportstried = 0;
  1592.               dropped = 0;
  1593.               if (o.verbose || o.debugging )  
  1594.             log_write(LOG_STDOUT, "Too many drops ... increasing senddelay to %d\n", senddelay);
  1595.             }
  1596.             if (windowdecrease == 0) {
  1597.               numqueries_ideal *= fallback_percent;
  1598.               if (numqueries_ideal < 1) numqueries_ideal = 1;
  1599.               if (o.debugging) { log_write(LOG_STDOUT, "Lost a packet, decreasing window to %d\n", (int) numqueries_ideal);
  1600.               windowdecrease++;
  1601.               if (scantype == UDP_SCAN || scantype == IPPROT_SCAN)
  1602.             usleep(250000);
  1603.               }
  1604.             } else if (o.debugging > 1) { 
  1605.               log_write(LOG_STDOUT, "Lost a packet, but not decreasing\n");
  1606.             }
  1607.           }
  1608.         }    
  1609.         if (current->state != newstate) {
  1610.           changed++;
  1611.         }
  1612.         if (current->state != PORT_OPEN && 
  1613.             current->state != PORT_CLOSED) {        
  1614.           numqueries_outstanding--;
  1615.         }
  1616.         if (current->state == PORT_TESTING && current == testinglist)
  1617.           testinglist = (current->next >= 0)?  &scan[current->next] : NULL;
  1618.         else if (current->state == PORT_OPEN && current == openlist)
  1619.           openlist = (current->next >= 0)? &scan[current->next] : NULL;
  1620.         if (current->next >= 0) scan[current->next].prev = current->prev;
  1621.         if (current->prev >= 0) scan[current->prev].next = current->next;
  1622.         current->next = current->prev = -1;
  1623.         current->state = newstate;
  1624.         addport(&target->ports, current->portno, 
  1625.             (scantype == UDP_SCAN)? IPPROTO_UDP :
  1626.               (scantype == IPPROT_SCAN? IPPROTO_IP: IPPROTO_TCP), 
  1627.             NULL, current->state);
  1628.           }
  1629.         }
  1630.       }
  1631.       } 
  1632.   
  1633.     
  1634.     /* Prepare for retry */
  1635.     testinglist = openlist;
  1636.     for(current = openlist; current; current = (current->next >= 0)? &scan[current->next] : NULL) {
  1637.       current->state = PORT_FRESH;
  1638.       current->trynum = 0;
  1639.       if (o.debugging) { 
  1640.     log_write(LOG_STDOUT, "Preparing for retry, open port %lu noted\n", current->portno); 
  1641.       }
  1642.     }
  1643.     
  1644.     openlist = NULL;
  1645.     numqueries_ideal = initial_packet_width;
  1646.     if (o.debugging)
  1647.       log_write(LOG_STDOUT, "Done with round %d\n", tries);
  1648.     if (scantype == UDP_SCAN && changed && (tries + 1) < 100) {
  1649.       if (o.debugging) {
  1650.     log_write(LOG_STDOUT, "Sleeping for 1/2 second to overcome ICMP error rate limiting\n");
  1651.       }
  1652.       usleep(500000);
  1653.     }
  1654.   } while(changed && ++tries < 100);   
  1655.  
  1656.   openlist = testinglist;
  1657.  
  1658.   if (o.debugging || o.verbose)
  1659.     log_write(LOG_STDOUT, "The %s took %ld %s to scan %d ports.\n", scantype2str(scantype), (long) time(NULL) - starttime, (((long) time(NULL) - starttime) == 1)? "second" : "seconds",  numports);
  1660.   
  1661.   for (current = openlist; current;  current = (current->next >= 0)? &scan[current->next] : NULL) {
  1662.     if (scantype == IPPROT_SCAN)
  1663.       addport(&target->ports, current->portno, IPPROTO_IP, NULL, PORT_OPEN);
  1664.     else if (scantype != UDP_SCAN)
  1665.       addport(&target->ports, current->portno, IPPROTO_TCP, NULL, PORT_OPEN);
  1666.     else
  1667.       addport(&target->ports, current->portno, IPPROTO_UDP, NULL, PORT_OPEN);
  1668.   }
  1669.  
  1670.  superscan_timedout:
  1671.  
  1672.   free(scan);
  1673.   close(rawsd);
  1674.   pcap_close(pd);
  1675.  
  1676.   /* Super scan relies on us receiving a response if the port is
  1677.      CLOSED and no response if the port is OPEN.  A problem with
  1678.      this is that when a machine is doing heavy filtering, all ports
  1679.      will seem to be open.  Thus we add a little metric: if > 25
  1680.      ports were scanned and they are ALL considered open by this
  1681.      function, then it is reasonably to assume that the REAL reason
  1682.      they are all open is that they have been filtered. */
  1683.   if (numports > 25) {    
  1684.     if (scantype == UDP_SCAN) {
  1685.       if (target->ports.state_counts_udp[PORT_OPEN] == numports) {
  1686.     if (o.verbose) { 
  1687.       error("(no udp responses received -- assuming all ports filtered)");
  1688.     }
  1689.     for(portno = 0; portno < 65536; portno++)
  1690.       {
  1691.         current_port_tmp = lookupport(&target->ports, portno, IPPROTO_UDP);
  1692.         if (current_port_tmp) {
  1693.           assert(current_port_tmp->state == PORT_OPEN);
  1694.           current_port_tmp->state = PORT_FIREWALLED;
  1695.           target->ports.state_counts[PORT_OPEN]--;
  1696.           target->ports.state_counts[PORT_FIREWALLED]++;
  1697.           target->ports.state_counts_udp[PORT_OPEN]--;
  1698.           target->ports.state_counts_udp[PORT_FIREWALLED]++;
  1699.         }
  1700.       }
  1701.       }
  1702.     } else { 
  1703.       if (target->ports.state_counts_tcp[PORT_OPEN] == numports) {
  1704.     if (o.verbose) { 
  1705.       error("(no tcp responses received -- assuming all ports filtered)");
  1706.     }
  1707.     for(portno = 0; portno < 65536; portno++)
  1708.       {
  1709.         current_port_tmp = lookupport(&target->ports, portno, IPPROTO_TCP);
  1710.         if (current_port_tmp) {
  1711.           assert(current_port_tmp->state == PORT_OPEN);
  1712.           current_port_tmp->state = PORT_FIREWALLED;
  1713.           target->ports.state_counts[PORT_OPEN]--;
  1714.           target->ports.state_counts[PORT_FIREWALLED]++;
  1715.           target->ports.state_counts_tcp[PORT_OPEN]--;
  1716.           target->ports.state_counts_tcp[PORT_FIREWALLED]++;
  1717.         }
  1718.       }
  1719.       }
  1720.     }
  1721.   }
  1722.   return;
  1723. }
  1724.