home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / nmap254b.zip / idle_scan.c < prev    next >
C/C++ Source or Header  |  2001-10-14  |  37KB  |  905 lines

  1.  
  2. /***********************************************************************/
  3. /* idle_scan.c -- Includes the function specific to "Idle Scan"        */
  4. /* support (-sI).  This is an extraordinarily cool scan type that      */
  5. /* can allow for completely blind scanning (eg no packets sent to the  */
  6. /* target from your own IP address) and can also be used to penetrate  */
  7. /* firewalls and scope out router ACLs.  This is one of the "advanced" */
  8. /* scans meant for epxerienced Nmap users.                             */
  9. /*                                                                     */
  10. /***********************************************************************/
  11. /*  The Nmap Security Scanner is (C) 1995-2001 Insecure.Com LLC. This  */
  12. /*  program is free software; you can redistribute it and/or modify    */
  13. /*  it under the terms of the GNU General Public License as published  */
  14. /*  by the Free Software Foundation; Version 2.  This guarantees your  */
  15. /*  right to use, modify, and redistribute this software under certain */
  16. /*  conditions.  If this license is unacceptable to you, we may be     */
  17. /*  willing to sell alternative licenses (contact sales@insecure.com). */
  18. /*                                                                     */
  19. /*  If you received these files with a written license agreement       */
  20. /*  stating terms other than the (GPL) terms above, then that          */
  21. /*  alternative license agreement takes precendence over this comment. */
  22. /*                                                                     */
  23. /*  Source is provided to this software because we believe users have  */
  24. /*  a right to know exactly what a program is going to do before they  */
  25. /*  run it.  This also allows you to audit the software for security   */
  26. /*  holes (none have been found so far).                               */
  27. /*                                                                     */
  28. /*  Source code also allows you to port Nmap to new platforms, fix     */
  29. /*  bugs, and add new features.  You are highly encouraged to send     */
  30. /*  your changes to fyodor@insecure.org for possible incorporation     */
  31. /*  into the main distribution.  By sending these changes to Fyodor or */
  32. /*  one the insecure.org development mailing lists, it is assumed that */
  33. /*  you are offering Fyodor the unlimited, non-exclusive right to      */
  34. /*  reuse, modify, and relicense the code.  This is important because  */
  35. /*  the inability to relicense code has caused devastating problems    */
  36. /*  for other Free Software projects (such as KDE and NASM).  Nmap     */
  37. /*  will always be available Open Source.  If you wish to specify      */
  38. /*  special license conditions of your contributions, just say so      */
  39. /*  when you send them.                                                */
  40. /*                                                                     */
  41. /*  This program is distributed in the hope that it will be useful,    */
  42. /*  but WITHOUT ANY WARRANTY; without even the implied warranty of     */
  43. /*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  */
  44. /*  General Public License for more details (                          */
  45. /*  http://www.gnu.org/copyleft/gpl.html ).                            */
  46. /*                                                                     */
  47. /***********************************************************************/
  48.  
  49. /* $Id: idle_scan.c,v 1.11 2001/10/14 09:38:26 fyodor Exp $ */
  50.  
  51. #include "idle_scan.h"
  52. #include "scan_engine.h"
  53. #include "timing.h"
  54. #include "osscan.h"
  55. #include "nmap.h"
  56.  
  57. #include <stdio.h>
  58.  
  59. extern struct ops o;
  60.  
  61. /*  predefined filters -- I need to kill these globals at some point. */
  62. extern unsigned long flt_dsthost, flt_srchost, flt_baseport;
  63.  
  64.  
  65. struct idle_proxy_info {
  66.   struct hoststruct host; /* contains name, IP, source IP, timing info, etc. */
  67.   int seqclass; /* IPID sequence class (IPID_SEQ_* defined in nmap.h) */
  68.   u16 latestid; /* The most recent IPID we have received from the proxy */
  69.   u16 probe_port; /* The port we use for probing IPID infoz */
  70.   u16 max_groupsz; /* We won't test groups larger than this ... */
  71.   double current_groupsz; /* Current group size being used ... depends on
  72.                           conditions ... won't be higher than
  73.                           max_groupsz */
  74.   int senddelay; /* Delay between sending pr0be SYN packets to target
  75.                     (in microseconds) */
  76.   int max_senddelay; /* Maximum time we are allowed to wait between
  77.                         sending pr0bes (when we send a bunch in a row.
  78.                         In microseconds. */
  79.  
  80.   pcap_t *pd; /* A Pcap descriptor which (starting in
  81.                  initialize_idleproxy) listens for TCP packets from
  82.                  the probe_port of the proxy box */
  83.   int rawsd; /* Socket descriptor for sending probe packets to the proxy */
  84. };
  85.  
  86.  
  87. /* Sends an IPID probe to the proxy machine and returns the IPID.
  88.    This function handles retransmissions, and returns -1 if it fails.
  89.    Proxy timing is adjusted, but proxy->latestid is NOT ADJUSTED --
  90.    you'll have to do that yourself.   Probes_sent is set to the number
  91.    of probe packets sent during execution */
  92. int ipid_proxy_probe(struct idle_proxy_info *proxy, int *probes_sent,
  93.              int *probes_rcvd) {
  94.   struct timeval tv_end;
  95.   int tries = 0;
  96.   int trynum;
  97.   int sent=0, rcvd=0;
  98.   int maxtries = 3; /* The maximum number of tries before we give up */
  99.   struct timeval tv_sent[3];
  100.   int ipid = -1;
  101.   int to_usec;
  102.   int bytes;
  103.   int timedout = 0;
  104.   int base_port;
  105.   struct ip *ip;
  106.   struct tcphdr *tcp;
  107.   static u32 seq_base = 0;
  108.   static u32 ack = 0;
  109.   static int packet_send_count = 0; /* Total # of probes sent by this program -- to ensure that our sequence # always changes */
  110.  
  111.   if (o.magic_port_set)
  112.     base_port = o.magic_port;
  113.   else base_port = o.magic_port + get_random_u8();
  114.  
  115.   if (seq_base == 0) seq_base = get_random_u32();
  116.   if (!ack) ack = get_random_u32();
  117.  
  118.  
  119.   do {
  120.     timedout = 0;
  121.     gettimeofday(&tv_sent[tries], NULL);
  122.  
  123.     /* Time to send the pr0be!*/
  124.     send_tcp_raw(proxy->rawsd, &(proxy->host.source_ip), &(proxy->host.host), 
  125.          base_port + tries , proxy->probe_port, 
  126.          seq_base + (packet_send_count++ * 500) + 1, ack, 
  127.          TH_SYN|TH_ACK, 0, 
  128.          NULL, 0, NULL, 0);
  129.     sent++;
  130.     tries++;
  131.  
  132.     /* Now it is time to wait for the response ... */
  133.     to_usec = proxy->host.to.timeout;
  134.     gettimeofday(&tv_end, NULL);
  135.     while((ipid == -1 || sent > rcvd) && to_usec >= 0) {
  136.  
  137.       to_usec = proxy->host.to.timeout - TIMEVAL_SUBTRACT(tv_end, tv_sent[tries-1]);
  138.     
  139.       ip = (struct ip *) readip_pcap(proxy->pd, &bytes, to_usec);      
  140.       gettimeofday(&tv_end, NULL);
  141.       if (ip) {
  142.     if (bytes < ( 4 * ip->ip_hl) + 14U)
  143.       continue;
  144.  
  145.     if (ip->ip_p == IPPROTO_TCP) {
  146.  
  147.       tcp = ((struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl));
  148.       if (ntohs(tcp->th_dport) < base_port || ntohs(tcp->th_dport) - base_port >= tries  || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) {
  149.         if (ntohs(tcp->th_dport) > o.magic_port && ntohs(tcp->th_dport) < (o.magic_port + 260)) {
  150.           if (o.debugging) {
  151.         error("Received IPID zombie probe response which probably came from an earlier prober instance ... increasing rttvar from %d to %d", 
  152.               proxy->host.to.rttvar, (int) (proxy->host.to.rttvar * 1.2));
  153.           }
  154.           proxy->host.to.rttvar = proxy->host.to.rttvar * 1.2;
  155.           rcvd++;
  156.         }
  157.         else if (o.debugging > 1) {
  158.           error("Received unexpected response packet from %s during ipid zombie probing:", inet_ntoa(ip->ip_src));
  159.           readtcppacket((char *)ip,BSDUFIX(ip->ip_len));
  160.         }
  161.         continue;
  162.       }
  163.       
  164.       trynum = ntohs(tcp->th_dport) - base_port;
  165.       rcvd++;
  166.  
  167.       ipid = ntohs(ip->ip_id);
  168.       adjust_timeouts2(&(tv_sent[trynum]), &tv_end, &(proxy->host.to));
  169.     }
  170.       }
  171.     }
  172.   } while(ipid == -1 && tries < maxtries);
  173.  
  174.   if (probes_sent) *probes_sent = sent;
  175.   if (probes_rcvd) *probes_rcvd = rcvd;
  176.  
  177.   return ipid;
  178. }
  179.  
  180.  
  181. /* Returns the number of increments between an early IPID and a later
  182.    one, assuming the given IPID Sequencing class.  Returns -1 if the
  183.    distance cannot be determined */
  184.  
  185. int ipid_distance(int seqclass , u16 startid, u16 endid) {
  186.   if (seqclass == IPID_SEQ_INCR)
  187.     return endid - startid;
  188.   
  189.   if (seqclass == IPID_SEQ_BROKEN_INCR) {
  190.     /* Convert to network byte order */
  191.     startid = (startid >> 8) + ((startid & 0xFF) << 8);
  192.     endid = (endid >> 8) + ((endid & 0xFF) << 8);
  193.     return endid - startid;
  194.   }
  195.  
  196.   return -1;
  197.  
  198. }
  199.  
  200.  
  201. /* takes a proxy name/IP, resolves it if neccessary, tests it for IPID
  202.    suitability, and fills out an idle_proxy_info structure.  If the
  203.    proxy is determined to be unsuitable, the function whines and exits
  204.    the program */
  205. #define NUM_IPID_PROBES 6
  206. void initialize_idleproxy(struct idle_proxy_info *proxy, char *proxyName,
  207.               struct in_addr *first_target) {
  208.   int probes_sent = 0, probes_returned = 0;
  209.   int hardtimeout = 9000000; /* Generally don't wait more than 9 secs total */
  210.   int bytes, to_usec;
  211.   int timedout = 0;
  212.   char *p, *q;
  213.   char *endptr = NULL;
  214.   int seq_response_num;
  215.   char *dev;
  216.   int newipid;
  217.   int i;
  218.   char filter[512]; /* Libpcap filter string */
  219.   char name[MAXHOSTNAMELEN + 1];
  220.   u32 sequence_base;
  221.   u32 ack = 0;
  222.   struct timeval probe_send_times[NUM_IPID_PROBES], tmptv;
  223.   u16 lastipid = 0;
  224.   struct ip *ip;
  225.   struct tcphdr *tcp;
  226.   int distance;
  227.   u16 ipids[NUM_IPID_PROBES]; 
  228.   u8 probe_returned[NUM_IPID_PROBES];
  229.   assert(proxy);
  230.   assert(proxyName);
  231.  
  232.   ack = get_random_u32();
  233.  
  234.   for(i=0; i < NUM_IPID_PROBES; i++) probe_returned[i] = 0;
  235.  
  236.   bzero(proxy, sizeof(*proxy));
  237.   proxy->host.to.srtt = -1;
  238.   proxy->host.to.rttvar = -1;
  239.   proxy->host.to.timeout = o.initial_rtt_timeout * 1000;
  240.  
  241.   proxy->max_groupsz = (o.max_parallelism)? o.max_parallelism : 100;
  242.   proxy->max_senddelay = 100000;
  243.  
  244.   Strncpy(name, proxyName, sizeof(name));
  245.   q = strchr(name, ':');
  246.   if (q) {
  247.     *q++ = '\0';
  248.     proxy->probe_port = strtoul(q, &endptr, 10);
  249.     if (*q==0 || !endptr || *endptr != '\0' || !proxy->probe_port) {
  250.       fatal("Invalid port number given in IPID zombie specification: %s", proxyName);
  251.     }
  252.   } else proxy->probe_port = o.tcp_probe_port;
  253.  
  254.   proxy->host.name = strdup(name);
  255.  
  256.   if (resolve(name, &(proxy->host.host)) == 0) {
  257.     fatal("Could not resolve idlescan zombie host: %s", name);
  258.   }
  259.  
  260.   /* Lets figure out the appropriate source address to use when sending
  261.      the pr0bez */
  262.   if (o.source && o.source->s_addr) {
  263.     proxy->host.source_ip.s_addr = o.source->s_addr;
  264.     Strncpy(proxy->host.device, o.device, sizeof(proxy->host.device));
  265.   } else {
  266.     dev = routethrough(&(proxy->host.host), &(proxy->host.source_ip));  
  267.     if (!dev) fatal("Unable to find appropriate source address and device interface to use when sending packets to %s", proxyName);
  268.     Strncpy(proxy->host.device, dev, sizeof(proxy->host.device));
  269.   }
  270.   /* Now lets send some probes to check IPID algorithm ... */
  271.   /* First we need a raw socket ... */
  272.   if ((proxy->rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  273.     pfatal("socket trobles in get_fingerprint");
  274.   unblock_socket(proxy->rawsd);
  275.   broadcast_socket(proxy->rawsd);
  276.  
  277.  
  278. /* Now for the pcap opening nonsense ... */
  279.  /* Note that the snaplen is 152 = 64 byte max IPhdr + 24 byte max link_layer
  280.   * header + 64 byte max TCP header. */
  281.   proxy->pd = my_pcap_open_live(proxy->host.device, 152,  (o.spoofsource)? 1 : 0, 50);
  282.  
  283.   p = strdup(inet_ntoa(proxy->host.host));
  284.   q = strdup(inet_ntoa(proxy->host.source_ip));
  285.   snprintf(filter, sizeof(filter), "tcp and src host %s and dst host %s and src port %hu", p, q, proxy->probe_port);
  286.  free(p); 
  287.  free(q);
  288.  set_pcap_filter(&(proxy->host), proxy->pd, flt_icmptcp, filter);
  289. /* Windows nonsense -- I am not sure why this is needed, but I should
  290.    get rid of it at sometime */
  291.  
  292.  flt_srchost = proxy->host.source_ip.s_addr;
  293.  flt_dsthost = proxy->host.host.s_addr;
  294.  
  295.  sequence_base = get_random_u32();
  296.  
  297.  /* Yahoo!  It is finally time to send our pr0beZ! */
  298.  
  299.   while(probes_sent < NUM_IPID_PROBES) {
  300.     if (o.scan_delay) enforce_scan_delay(NULL);
  301.     else if (probes_sent) usleep(30000);
  302.  
  303.     /* TH_SYN|TH_ACK is what the proxy will really be receiving from
  304.        the target, and is more likely to get through firewalls.  But
  305.        TH_SYN allows us to get a nonzero ACK back so we can associate
  306.        a response with the exact request for timing purposes.  So I
  307.        think I'll use TH_SYN, although it is a tough call. */
  308.     /* We can't use decoys 'cause that would screw up the IPIDs */
  309.     send_tcp_raw(proxy->rawsd, &(proxy->host.source_ip), &(proxy->host.host), 
  310.          o.magic_port + probes_sent + 1, proxy->probe_port, 
  311.          sequence_base + probes_sent + 1, 0, TH_SYN|TH_ACK, 
  312.          ack, NULL, 0, NULL, 0);
  313.     gettimeofday(&probe_send_times[probes_sent], NULL);
  314.     probes_sent++;
  315.  
  316.     /* Time to collect any replies */
  317.     while(probes_returned < probes_sent && !timedout) {
  318.  
  319.       to_usec = (probes_sent == NUM_IPID_PROBES)? hardtimeout : 1000;
  320.       ip = (struct ip *) readip_pcap(proxy->pd, &bytes, to_usec);
  321.  
  322.       gettimeofday(&tmptv, NULL);
  323.       
  324.       if (!ip) {
  325.     if (probes_sent < NUM_IPID_PROBES)
  326.       break;
  327.     if (TIMEVAL_SUBTRACT(tmptv, probe_send_times[probes_sent - 1]) >= hardtimeout) {
  328.       timedout = 1;
  329.     }
  330.     continue;
  331.       } else if (TIMEVAL_SUBTRACT(tmptv, probe_send_times[probes_sent - 1]) >=
  332.          hardtimeout)  {      
  333.     timedout = 1;
  334.       }
  335.  
  336.       if (lastipid != 0 && ip->ip_id == lastipid) {
  337.     continue; /* probably a duplicate */
  338.       }
  339.       lastipid = ip->ip_id;
  340.  
  341.       if (bytes < ( 4 * ip->ip_hl) + 14U)
  342.     continue;
  343.  
  344.       if (ip->ip_p == IPPROTO_TCP) {
  345.     /*       readtcppacket((char *) ip, ntohs(ip->ip_len));  */
  346.     tcp = ((struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl));
  347.     if (ntohs(tcp->th_dport) < (o.magic_port+1) || ntohs(tcp->th_dport) - o.magic_port > NUM_IPID_PROBES  || ntohs(tcp->th_sport) != proxy->probe_port || ((tcp->th_flags & TH_RST) == 0)) {
  348.       if (o.debugging > 1) error("Received unexpected response packet from %s during initial ipid zombie testing", inet_ntoa(ip->ip_src));
  349.       continue;
  350.     }
  351.     
  352.     seq_response_num = probes_returned;
  353.  
  354.     /* The stuff below only works when we send SYN packets instead of
  355.        SYN|ACK, but then are slightly less stealthy and have less chance
  356.        of sneaking through the firewall.  Plus SYN|ACK is what they will
  357.        be receiving back from the target */
  358.     /*    seq_response_num = (ntohl(tcp->th_ack) - 2 - sequence_base);
  359.         if (seq_response_num < 0 || seq_response_num >= probes_sent) {
  360.         if (o.debugging) {
  361.         error("Unable to associate IPID proxy probe response with sent packet (received ack: %lX; sequence base: %lX. Packet:", ntohl(tcp->th_ack), sequence_base);
  362.         readtcppacket((char *)ip,BSDUFIX(ip->ip_len));
  363.         }
  364.         seq_response_num = probes_returned;
  365.         }
  366.     */
  367.     probes_returned++;
  368.     ipids[seq_response_num] = (u16) ntohs(ip->ip_id);
  369.     probe_returned[seq_response_num] = 1;
  370.     adjust_timeouts2(&probe_send_times[seq_response_num], &(tmptv), &(proxy->host.to));
  371.       }
  372.     }
  373.   }
  374.  
  375.   /* Yeah!  We're done sending/receiving probes ... now lets ensure all of our responses are adjacent in the array */
  376.   for(i=0,probes_returned=0; i < NUM_IPID_PROBES; i++) {
  377.     if (probe_returned[i]) {    
  378.       if (i > probes_returned)
  379.     ipids[probes_returned] = ipids[i];
  380.       probes_returned++;
  381.     }
  382.   }
  383.  
  384.   proxy->seqclass = ipid_sequence(probes_returned, ipids, 0);
  385.   switch(proxy->seqclass) {
  386.   case IPID_SEQ_INCR:
  387.   case IPID_SEQ_BROKEN_INCR:
  388.     log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "Idlescan using zombie %s (%s:%hu); Class: %s\n", proxy->host.name, inet_ntoa(proxy->host.host), proxy->probe_port, ipidclass2ascii(proxy->seqclass));
  389.     break;
  390.   default:
  391.     fatal("Idlescan zombie %s (%s) port %hu cannot be used because IPID sequencability class is: %s.  Try another proxy.", proxy->host.name, inet_ntoa(proxy->host.host), proxy->probe_port, ipidclass2ascii(proxy->seqclass));
  392.   }
  393.  
  394.   proxy->latestid = ipids[probes_returned - 1];
  395.   proxy->current_groupsz = MIN(proxy->max_groupsz, 30);
  396.  
  397.   if (probes_returned < NUM_IPID_PROBES) {
  398.     /* Yikes!  We're already losing packets ... clamp down a bit ... */
  399.     if (o.debugging)
  400.       error("idlescan initial zombie qualification test: %d probes sent, only %d returned", NUM_IPID_PROBES, probes_returned);
  401.     proxy->current_groupsz = MIN(12, proxy->max_groupsz);
  402.     proxy->senddelay += 5000;
  403.   }
  404.  
  405.   /* OK, through experimentation I have found that some hosts *cough*
  406.    Solaris APPEAR to use simple IPID incrementing, but in reality they
  407.    assign a new IPID base to each host which connects with them.  This
  408.    is actually a good idea on several fronts, but it totally
  409.    frustrates our efforts (which rely on side-channel IPID info
  410.    leaking to different hosts).  The good news is that we can easily
  411.    detect the problem by sending some spoofed packets "from" the first
  412.    target to the zombie and then probing to verify that the proxy IPID
  413.    changed.  This will also catch the case where the Nmap user is
  414.    behind an egress filter or other measure that prevents this sort of
  415.    sp00fery */
  416.   if (first_target) {  
  417.     for (probes_sent = 0; probes_sent < 4; probes_sent++) {  
  418.       if (probes_sent) usleep(50000);
  419.       send_tcp_raw(proxy->rawsd, first_target, &(proxy->host.host), 
  420.            o.magic_port, proxy->probe_port, 
  421.            sequence_base + probes_sent + 1, 0, TH_SYN|TH_ACK, 
  422.            ack, NULL, 0, NULL, 0);
  423.  
  424.     }
  425.  
  426.     /* Sleep a little while to give packets time to reach their destination */
  427.     usleep(300000);
  428.     newipid = ipid_proxy_probe(proxy, NULL, NULL);
  429.     if (newipid == -1)
  430.       newipid = ipid_proxy_probe(proxy, NULL, NULL); /* OK, we'll give it one more try */
  431.  
  432.     if (newipid < 0) fatal("Your IPID Zombie (%s; %s) is behaving strangely -- suddenly cannot obtain IPID", proxy->host.name, inet_ntoa(proxy->host.host));
  433.       
  434.     distance = ipid_distance(proxy->seqclass, proxy->latestid, newipid);
  435.     if (distance <= 0) {
  436.       fatal("Your IPID Zombie (%s; %s) is behaving strangely -- suddenly cannot obtain valid IPID distance.", proxy->host.name, inet_ntoa(proxy->host.host));
  437.     } else if (distance == 1) {
  438.       fatal("Even though your Zombie (%s; %s) appears to be vulnerable to IPID sequence prediction (class: %s), our attempts have failed.  There generally means that either the Zombie uses a separate IPID base for each host (like Solaris), or because you cannot spoof IP packets (perhaps your ISP has enabled egress filtering to prevent IP spoofing), or maybe the target network recognizes the packet source as bogus and drops them", proxy->host.name, inet_ntoa(proxy->host.host), ipidclass2ascii(proxy->seqclass));
  439.     }
  440.     if (o.debugging && distance != 5) {
  441.       error("WARNING: IPID spoofing test sent 4 packets and expected a distance of 5, but instead got %d", distance);
  442.     }
  443.     proxy->latestid = newipid;
  444.   }
  445.   
  446. }
  447.  
  448.  
  449.  
  450.  
  451. /* Adjust timing parameters up or down given that an idlescan found a
  452.    count of 'testcount' while the 'realcount' is as given.  If the
  453.    testcount was correct, timing is made more aggressive, while it is
  454.    slowed down in the case of an error */
  455. void adjust_idle_timing(struct idle_proxy_info *proxy, 
  456.             struct hoststruct *target, int testcount, 
  457.             int realcount) {
  458.  
  459.   static int notidlewarning = 0;
  460.  
  461.   if (o.debugging > 1)
  462.     log_write(LOG_STDOUT, 
  463.       "adjust_idle_timing: tested/true %d/%d -- old grpsz/delay: %f/%d ",
  464.       testcount, realcount, proxy->current_groupsz, proxy->senddelay);
  465.   else if (o.debugging && testcount != realcount) {
  466.     error("adjust_idle_timing: testcount: %d  realcount: %d -- old grpsz/delay: %f/%d", testcount, realcount, proxy->current_groupsz, proxy->senddelay);
  467.   }
  468.  
  469.     if (testcount < realcount) {
  470.       /* We must have missed a port -- our probe could have been
  471.      dropped, the response to proxy could have been dropped, or we
  472.      didn't wait long enough before probing the proxy IPID.  The
  473.      third case is covered elsewhere in the scan, so we worry most
  474.      about the first two.  The solution is to decrease our group
  475.      size and add a sending delay */
  476.  
  477.       proxy->current_groupsz = proxy->current_groupsz * 0.80; /* packets
  478.                     could be dropped because too
  479.                     many sent at once */
  480.       proxy->current_groupsz = MAX(proxy->current_groupsz, 1);
  481.       proxy->senddelay += 10000;
  482.       proxy->senddelay = MIN(proxy->max_senddelay, proxy->senddelay);
  483.        /* No group size should be greater than .5s of send delays */
  484.       proxy->current_groupsz = MAX(2, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay + 1)));
  485.  
  486.     } else if (testcount > realcount) {
  487.       /* Perhaps the proxy host is not really idle ... */
  488.       /* I guess all I can do is decrease the group size, so that if the proxy is not really idle, at least we may be able to scan cnunks more quickly in between outside packets */
  489.       proxy->current_groupsz = proxy->current_groupsz * 0.8;
  490.       proxy->current_groupsz = MAX(proxy->current_groupsz, 2);
  491.  
  492.       if (!notidlewarning && o.verbose) {
  493.     notidlewarning = 1;
  494.     error("WARNING: Idlescan has erroneously detected phantom ports -- is the proxy %s (%s) really idle?", proxy->host.name, inet_ntoa(proxy->host.host));
  495.       }
  496.     } else {
  497.       /* W00p We got a perfect match.  That means we get a slight increase
  498.      in allowed group size and we can lightly decrease the senddelay */
  499.  
  500.       proxy->senddelay = proxy->senddelay * 0.9;
  501.       proxy->current_groupsz = MIN(proxy->current_groupsz * 1.1, 500000 / (proxy->senddelay + 1));
  502.       proxy->current_groupsz = MIN(proxy->max_groupsz, proxy->current_groupsz);
  503.  
  504.     }
  505.     if (o.debugging > 1)
  506.       log_write(LOG_STDOUT, "-> %f/%d\n", proxy->current_groupsz, proxy->senddelay);
  507. }
  508.  
  509.  
  510. /* OK, now this is the hardcore idlescan function which actually does
  511.    the testing (most of the other cruft in this file is just
  512.    coordination, preparation, etc).  This function simply uses the
  513.    Idlescan technique to try and count the number of open ports in the
  514.    given port array.  The sent_time and rcv_time are filled in with
  515.    the times that the probe packet & response were sent/received.
  516.    They can be NULL if you don't want to use them.  The purpose is for
  517.    timing adjustments if the numbers turn out to be accurate */
  518.  
  519. int idlescan_countopen2(struct idle_proxy_info *proxy, 
  520.             struct hoststruct *target, u16 *ports, int numports,
  521.             struct timeval *sent_time, struct timeval *rcv_time) 
  522. {
  523.  
  524. #if 0 /* Testing code */
  525.   int i;
  526.   for(i=0; i < numports; i++)
  527.     if (ports[i] == 22)
  528.       return 1;
  529.   return 0;
  530. #endif
  531.  
  532.   int openports;
  533.   int tries;
  534.   int proxyprobes_sent = 0; /* diff. from tries 'cause sometimes we 
  535.                    skip tries */
  536.   int proxyprobes_rcvd = 0; /* To determine if packets were dr0pped */
  537.   int sent, rcvd;
  538.   int ipid_dist;
  539.   struct timeval start, end, latestchange, now;
  540.   struct timeval probe_times[4];
  541.   int pr0be;
  542.   static u32 seq = 0;
  543.   int newipid;
  544.   int sleeptime;
  545.   int lasttry = 0;
  546.   int dotry3 = 0;
  547.  
  548.   if (seq == 0) seq = get_random_u32();
  549.  
  550.   bzero(&end, sizeof(end));
  551.   bzero(&latestchange, sizeof(latestchange));
  552.   gettimeofday(&start, NULL);
  553.   if (sent_time) bzero(sent_time, sizeof(*sent_time));
  554.   if (rcv_time) bzero(rcv_time, sizeof(*rcv_time));
  555.  
  556.   /* I start by sending out the SYN pr0bez */
  557.   for(pr0be = 0; pr0be < numports; pr0be++) {
  558.     if (o.scan_delay) enforce_scan_delay(NULL);
  559.     else if (proxy->senddelay && pr0be > 0) usleep(proxy->senddelay);
  560.  
  561.     /* Maybe I should involve decoys in the picture at some point --
  562.        but doing it the straightforward way (using the same decoys as
  563.        we use in probing the proxy box is risky.  I'll have to think
  564.        about this more. */
  565.  
  566.     send_tcp_raw(proxy->rawsd, &(proxy->host.host), &target->host, 
  567.          proxy->probe_port, ports[pr0be], seq, 0, TH_SYN, 0, NULL, 0, 
  568.          o.extra_payload, o.extra_payload_length);
  569.   }
  570.   gettimeofday(&end, NULL);
  571.  
  572.  
  573.   openports = -1;
  574.   tries = 0;
  575.   /* CHANGEME: I d'nt think that MAX() line works right */
  576.   TIMEVAL_MSEC_ADD(probe_times[0], start, MAX(50, (target->to.srtt * 3/4) / 1000));
  577.   TIMEVAL_MSEC_ADD(probe_times[1], start, target->to.srtt / 1000 );
  578.   TIMEVAL_MSEC_ADD(probe_times[2], end, MAX(75, (target->to.srtt + 
  579.                            target->to.rttvar) / 1000));
  580.   TIMEVAL_MSEC_ADD(probe_times[3], end, MIN(4000, (target->to.srtt + 
  581.                              (target->to.rttvar << 2 )) / 1000));
  582.  
  583.   do {
  584.     if (tries == 2) dotry3 = (get_random_u8() > 200);
  585.     if (tries == 3 && !dotry3)
  586.       break; /* We usually want to skip the long-wait test */
  587.     if (tries == 3 || (tries == 2 && !dotry3))
  588.       lasttry = 1;
  589.  
  590.     gettimeofday(&now, NULL);
  591.     sleeptime = TIMEVAL_SUBTRACT(probe_times[tries], now);
  592.     if (!lasttry && proxyprobes_sent > 0 && sleeptime < 50000)
  593.       continue; /* No point going again so soon */
  594.  
  595.     if (tries == 0 && sleeptime < 500)
  596.       sleeptime = 500;
  597.     if (o.debugging > 1) error("In preparation for idlescan probe try #%d, sleeping for %d usecs", tries, sleeptime);
  598.     if (sleeptime > 0)
  599.       usleep(sleeptime);
  600.  
  601.     newipid = ipid_proxy_probe(proxy, &sent, &rcvd);
  602.     proxyprobes_sent += sent;
  603.     proxyprobes_rcvd += rcvd;
  604.  
  605.     if (newipid > 0) {
  606.       ipid_dist = ipid_distance(proxy->seqclass, proxy->latestid, newipid);
  607.       /* I used to only do this if ipid_sit >= proxyprobes_sent, but I'd
  608.      rather have a negative number in that case */
  609.       if (ipid_dist < proxyprobes_sent) {
  610.     if (o.debugging) 
  611.            error("idlescan_countopen2: Must have lost a sent packet because ipid_dist is %d while proxyprobes_sent is %d.", ipid_dist, proxyprobes_sent);
  612.     /* I no longer whack timing here ... done at bottom */
  613.       }
  614.       ipid_dist -= proxyprobes_sent;
  615.       if (ipid_dist > openports) {
  616.     openports = ipid_dist;
  617.     gettimeofday(&latestchange, NULL);
  618.       } else if (ipid_dist < openports && ipid_dist >= 0) {
  619.     /* Uh-oh.  Perhaps I dropped a packet this time */
  620.     if (o.debugging > 1) {
  621.       error("idlescan_countopen2: Counted %d open ports in try #%d, but counted %d earlier ... probably a proxy_probe problem", ipid_dist, tries, openports);
  622.     }    
  623.     /* I no longer whack timing here ... done at bottom */
  624.       }
  625.     }
  626.     
  627.     if (openports > numports || (numports <= 2 && (openports == numports))) 
  628.       break;    
  629.   } while(tries++ < 3);
  630.  
  631.   if (proxyprobes_sent > proxyprobes_rcvd) {
  632.     /* Uh-oh.  It looks like we lost at least one proxy probe packet */
  633.     if (o.debugging) {
  634.       error("idlescan_countopen2: Sent %d probes; only %d responses.  Slowing scan.", proxyprobes_sent, proxyprobes_rcvd);
  635.     }
  636.     proxy->senddelay += 5000;
  637.     proxy->senddelay = MIN(proxy->max_senddelay, proxy->senddelay);
  638.     /* No group size should be greater than .5s of send delays */
  639.     proxy->current_groupsz = MAX(2, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay+1)));
  640.   } else {
  641.     /* Yeah, we got as many responses as we sent probes.  This calls for a 
  642.        very light timing acceleration ... */
  643.     proxy->senddelay = proxy->senddelay * 0.95;
  644.     proxy->current_groupsz = MAX(2, MIN(proxy->current_groupsz, 500000 / (proxy->senddelay+1)));
  645.   }
  646.  
  647.   if ((openports > 0) && (openports <= numports)) {
  648.     /* Yeah, we found open ports... lets adjust the timing ... */
  649.     if (o.debugging > 2) error("idlescan_countopen2:  found %d open ports (out of %d) in %d usecs", openports, numports, TIMEVAL_SUBTRACT(latestchange, start));
  650.     if (sent_time) *sent_time = start;
  651.     if (rcv_time) *rcv_time = latestchange;
  652.   }
  653.   if (newipid > 0) proxy->latestid = newipid;
  654.   return openports;
  655. }
  656.  
  657.  
  658.  
  659. /* The job of this function is to use the Idlescan technique to count
  660.    the number of open ports in the given list.  Under the covers, this
  661.    function just farms out the hard work to another function */
  662. int idlescan_countopen(struct idle_proxy_info *proxy, 
  663.                struct hoststruct *target, u16 *ports, int numports,
  664.                struct timeval *sent_time, struct timeval *rcv_time) {
  665.   int tries = 0;
  666.   int openports;
  667.  
  668.   do {
  669.     openports = idlescan_countopen2(proxy, target, ports, numports, sent_time,
  670.                     rcv_time);
  671.     tries++;
  672.     if (tries == 6 || (openports >= 0 && openports <= numports))
  673.       break;
  674.     
  675.     if (o.debugging) {
  676.       error("idlescan_countopen: In try #%d, counted %d open ports out of %d.  Retrying", tries, openports, numports);
  677.     }
  678.     /* Sleep for a little while -- maybe proxy host had brief birst of 
  679.        traffic or similar problem */
  680.     sleep(tries * tries);
  681.     if (tries == 5)
  682.       sleep(45); /* We're gonna give up if this fails, so we will be a bit
  683.             patient */
  684.   } while(1);
  685.  
  686.   if (openports < 0 || openports > numports ) {
  687.     /* Oh f*ck!!!! */
  688.     fatal("Idlescan is unable to obtain meaningful results from proxy %s (%s).  I'm sorry it didn't work out.", proxy->host.name, inet_ntoa(proxy->host.host));
  689.   }
  690.  
  691.   if (o.debugging > 2) error("idlescan_countopen: %d ports found open out of %d, starting with %hu", openports, numports, ports[0]);
  692.  
  693.   return openports;
  694. }
  695.  
  696. /* Recursively Idlescans scans a group of ports using a depth-first
  697.    divide-and-conquer strategy to find the open one(s) */
  698.  
  699. int idle_treescan(struct idle_proxy_info *proxy, struct hoststruct *target,
  700.          u16 *ports, int numports, int expectedopen) {
  701.  
  702.   int firstHalfSz = (numports + 1)/2;
  703.   int secondHalfSz = numports - firstHalfSz;
  704.   int flatcount1, flatcount2;
  705.   int deepcount1 = -1, deepcount2 = -1;
  706.   struct timeval sentTime1, rcvTime1, sentTime2, rcvTime2;
  707.   int retrycount = -1, retry2 = -1;
  708.   int totalfound = 0;
  709.   /* Scan the first half of the range */
  710.  
  711.   if (o.debugging > 1) {  
  712.     error("idle_treescan: Called against %s with %d ports, starting with %hu. expectedopen: %d", inet_ntoa(target->host), numports, ports[0], expectedopen);
  713.     error("IDLESCAN TIMING: grpsz: %.3f delay: %d srtt: %d rttvar: %d\n",
  714.       proxy->current_groupsz, proxy->senddelay, target->to.srtt,
  715.       target->to.rttvar);
  716.   }
  717.  
  718.   flatcount1 = idlescan_countopen(proxy, target, ports, firstHalfSz, 
  719.                   &sentTime1, &rcvTime1);
  720.   
  721.  
  722.   
  723.   if (firstHalfSz > 1 && flatcount1 > 0) {
  724.     /* A port appears open!  We dig down deeper to find it ... */
  725.     deepcount1 = idle_treescan(proxy, target, ports, firstHalfSz, flatcount1);
  726.     /* Now we assume deepcount1 is right, and adjust timing if flatcount1 was
  727.        wrong */
  728.     adjust_idle_timing(proxy, target, flatcount1, deepcount1);
  729.   }
  730.  
  731.   /* I guess we had better do the second half too ... */
  732.  
  733.   flatcount2 = idlescan_countopen(proxy, target, ports + firstHalfSz, 
  734.                   secondHalfSz, &sentTime2, &rcvTime2);
  735.   
  736.   if ((secondHalfSz) > 1 && flatcount2 > 0) {
  737.     /* A port appears open!  We dig down deeper to find it ... */
  738.     deepcount2 = idle_treescan(proxy, target, ports + firstHalfSz, 
  739.                    secondHalfSz, flatcount2);
  740.     /* Now we assume deepcount1 is right, and adjust timing if flatcount1 was
  741.        wrong */
  742.     adjust_idle_timing(proxy, target, flatcount2, deepcount2);
  743.   }
  744.  
  745.   totalfound = (deepcount1 == -1)? flatcount1 : deepcount1;
  746.   totalfound += (deepcount2 == -1)? flatcount2 : deepcount2;
  747.  
  748.   if ((flatcount1 + flatcount2 == totalfound) && 
  749.       (expectedopen == totalfound || expectedopen == -1)) {
  750.     
  751.     if (flatcount1 > 0) {    
  752.       if (o.debugging > 1) {
  753.     error("Adjusting timing -- idlescan_countopen correctly found %d open ports (out of %d, starting with %hu)", flatcount1, firstHalfSz, ports[0]);
  754.       }
  755.       adjust_timeouts2(&sentTime1, &rcvTime1, &(target->to));
  756.     }
  757.     
  758.     if (flatcount2 > 0) {    
  759.       if (o.debugging > 2) {
  760.     error("Adjusting timing -- idlescan_countopen correctly found %d open ports (out of %d, starting with %hu)", flatcount2, secondHalfSz, 
  761.           ports[firstHalfSz]);
  762.       }
  763.       adjust_timeouts2(&sentTime2, &rcvTime2, &(target->to));
  764.     }
  765.   }
  766.   
  767.   if (totalfound != expectedopen) {  
  768.     if (deepcount1 == -1) {
  769.       retrycount = idlescan_countopen(proxy, target, ports, firstHalfSz, NULL,
  770.                       NULL);
  771.       if (retrycount != flatcount1) {      
  772.     /* We have to do a deep count if new ports were found and
  773.        there are more than 1 total */
  774.     if (firstHalfSz > 1 && retrycount > 0) {    
  775.       retry2 = retrycount;
  776.       retrycount = idle_treescan(proxy, target, ports, firstHalfSz, 
  777.                      retrycount);
  778.       adjust_idle_timing(proxy, target, retry2, retrycount);
  779.     } else {
  780.       if (o.debugging)
  781.         error("Adjusting timing because my first scan of %d ports, starting with %hu found %d open, while second scan yielded %d", firstHalfSz, ports[0], flatcount1, retrycount);
  782.       adjust_idle_timing(proxy, target, flatcount1, retrycount);
  783.     }
  784.     totalfound += retrycount - flatcount1;
  785.     flatcount1 = retrycount;
  786.  
  787.     /* If our first count erroneously found and added an open port,
  788.        we must delete it */
  789.     if (firstHalfSz == 1 && flatcount1 == 1 && retrycount == 0)
  790.       deleteport(&target->ports, ports[0], IPPROTO_TCP);
  791.  
  792.       }
  793.     }
  794.     
  795.     if (deepcount2 == -1) {
  796.       retrycount = idlescan_countopen(proxy, target, ports + firstHalfSz, 
  797.                       secondHalfSz, NULL, NULL);
  798.       if (retrycount != flatcount2) {
  799.     if (secondHalfSz > 1 && retrycount > 0) {    
  800.       retry2 = retrycount;
  801.       retrycount = idle_treescan(proxy, target, ports + firstHalfSz, 
  802.                      secondHalfSz, retrycount);
  803.       adjust_idle_timing(proxy, target, retry2, retrycount);
  804.     } else {
  805.       if (o.debugging)
  806.         error("Adjusting timing because my first scan of %d ports, starting with %hu found %d open, while second scan yeilded %d", secondHalfSz, ports[firstHalfSz], flatcount2, retrycount);
  807.       adjust_idle_timing(proxy, target, flatcount2, retrycount);
  808.     }
  809.  
  810.     totalfound += retrycount - flatcount2;
  811.     flatcount2 = retrycount;
  812.  
  813.     /* If our first count erroneously found and added an open port,
  814.        we must delete it */
  815.     if (secondHalfSz == 1 && flatcount2 == 1 && retrycount == 0)
  816.       deleteport(&target->ports, ports[firstHalfSz], IPPROTO_TCP);
  817.  
  818.  
  819.       }
  820.     }
  821.   }
  822.  
  823.   if (firstHalfSz == 1 && flatcount1 == 1) 
  824.     addport(&target->ports, ports[0], IPPROTO_TCP, NULL, PORT_OPEN);
  825.   
  826.   if ((secondHalfSz == 1) && flatcount2 == 1) 
  827.     addport(&target->ports, ports[firstHalfSz], IPPROTO_TCP, NULL, PORT_OPEN);
  828.   return totalfound;
  829.  
  830. }
  831.  
  832.  
  833.  
  834. /* The very top-level idle scan function -- scans the given target
  835.    host using the given proxy -- the proxy is cached so that you can keep
  836.    calling this function with different targets */
  837. void idle_scan(struct hoststruct *target, u16 *portarray, int numports,
  838.            char *proxyName) {
  839.  
  840.   static char lastproxy[MAXHOSTNAMELEN + 1] = ""; /* The proxy used in any previous call */
  841.   static struct idle_proxy_info proxy;
  842.   int groupsz;
  843.   int portidx = 0; /* Used for splitting the port array into chunks */
  844.   int portsleft;
  845.   time_t starttime;
  846.   
  847.   if (numports == 0) return; /* nothing to scan for */
  848.   if (!proxyName) fatal("Idlescan requires a proxy host");
  849.  
  850.   if (*lastproxy && strcmp(proxyName, lastproxy))
  851.     fatal("idle_scan(): You are not allowed to change proxies midstream.  Sorry");
  852.   assert(target);
  853.  
  854.  
  855.  
  856.   /* If this is the first call,  */
  857.   if (!*lastproxy) {
  858.     initialize_idleproxy(&proxy, proxyName, &(target->host));
  859.   }
  860.  
  861.   if (o.debugging || o.verbose) {  
  862.     log_write(LOG_STDOUT, "Initiating Idlescan against %s (%s)\n", target->name, inet_ntoa(target->host));
  863.   }
  864.   starttime = time(NULL);
  865.  
  866.   /* If we don't have timing infoz for the new target, we'll use values 
  867.      derived from the proxy */
  868.   if (target->to.srtt == -1 && target->to.rttvar == -1) {
  869.     target->to.srtt = 2 * proxy.host.to.srtt;
  870.     target->to.rttvar = MAX(10000, MIN(target->to.srtt, 2000000));
  871.     target->to.timeout = target->to.srtt + (target->to.rttvar << 2);
  872.   }
  873.  
  874.   /* Now I guess it is time to let the scanning begin!  Since Idle
  875.      scan is sort of tree structured (we scan a group and then divide
  876.      it up and drill down in subscans of the group), we split the port
  877.      space into smaller groups and then call a recursive
  878.      divide-and-counquer function to find the open ports */
  879.   while(portidx < numports) {
  880.     portsleft = numports - portidx;
  881.     /* current_groupsz is doubled below because idle_subscan cuts in half */
  882.     groupsz = MIN(portsleft, (int) (proxy.current_groupsz * 2));
  883.     idle_treescan(&proxy, target, portarray + portidx, groupsz, -1);
  884.     portidx += groupsz;
  885.   }
  886.  
  887.  
  888.   if (o.verbose) {
  889.     long timediff = time(NULL) - starttime;
  890.     log_write(LOG_STDOUT, "The Idlescan took %ld %s to scan %d ports.\n", 
  891.           timediff, (timediff == 1)? "second" : "seconds", numports);
  892.   }
  893.  
  894.   /* Now we go through the ports which were not determined were scanned
  895.      but not determined to be open, and add them in the "closed" state */
  896.   for(portidx = 0; portidx < numports; portidx++) {
  897.     if (lookupport(&target->ports, portarray[portidx], IPPROTO_TCP) == NULL) {
  898.       addport(&target->ports, portarray[portidx], IPPROTO_TCP, NULL,
  899.           PORT_CLOSED);
  900.     }
  901.   }
  902.  
  903.   return;
  904. }
  905.