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

  1.  
  2. /***********************************************************************/
  3. /* osscan.c -- Routines used for OS detection via TCP/IP               */
  4. /* fingerprinting.  For more information on how this works in Nmap,    */
  5. /* see my paper at                                                     */
  6. /* http://www.insecure.org/nmap/nmap-fingerprinting-article.html       */
  7. /*                                                                     */
  8. /***********************************************************************/
  9. /*  The Nmap Security Scanner is (C) 1995-2001 Insecure.Com LLC. This  */
  10. /*  program is free software; you can redistribute it and/or modify    */
  11. /*  it under the terms of the GNU General Public License as published  */
  12. /*  by the Free Software Foundation; Version 2.  This guarantees your  */
  13. /*  right to use, modify, and redistribute this software under certain */
  14. /*  conditions.  If this license is unacceptable to you, we may be     */
  15. /*  willing to sell alternative licenses (contact sales@insecure.com). */
  16. /*                                                                     */
  17. /*  If you received these files with a written license agreement       */
  18. /*  stating terms other than the (GPL) terms above, then that          */
  19. /*  alternative license agreement takes precendence over this comment. */
  20. /*                                                                     */
  21. /*  Source is provided to this software because we believe users have  */
  22. /*  a right to know exactly what a program is going to do before they  */
  23. /*  run it.  This also allows you to audit the software for security   */
  24. /*  holes (none have been found so far).                               */
  25. /*                                                                     */
  26. /*  Source code also allows you to port Nmap to new platforms, fix     */
  27. /*  bugs, and add new features.  You are highly encouraged to send     */
  28. /*  your changes to fyodor@insecure.org for possible incorporation     */
  29. /*  into the main distribution.  By sending these changes to Fyodor or */
  30. /*  one the insecure.org development mailing lists, it is assumed that */
  31. /*  you are offering Fyodor the unlimited, non-exclusive right to      */
  32. /*  reuse, modify, and relicense the code.  This is important because  */
  33. /*  the inability to relicense code has caused devastating problems    */
  34. /*  for other Free Software projects (such as KDE and NASM).  Nmap     */
  35. /*  will always be available Open Source.  If you wish to specify      */
  36. /*  special license conditions of your contributions, just say so      */
  37. /*  when you send them.                                                */
  38. /*                                                                     */
  39. /*  This program is distributed in the hope that it will be useful,    */
  40. /*  but WITHOUT ANY WARRANTY; without even the implied warranty of     */
  41. /*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  */
  42. /*  General Public License for more details (                          */
  43. /*  http://www.gnu.org/copyleft/gpl.html ).                            */
  44. /*                                                                     */
  45. /***********************************************************************/
  46.  
  47. /* $Id: osscan.c,v 1.73 2001/08/10 05:53:08 fyodor Exp $ */
  48.  
  49.  
  50. #include "osscan.h"
  51. #include "timing.h"
  52.  
  53. #if TIME_WITH_SYS_TIME
  54. # include <sys/time.h>
  55. # include <time.h>
  56. #else
  57. # if HAVE_SYS_TIME_H
  58. #  include <sys/time.h>
  59. # else
  60. #  include <time.h>
  61. # endif
  62. #endif
  63.  
  64. extern struct ops o;
  65. /*  predefined filters -- I need to kill these globals at some pont. */
  66. extern unsigned long flt_dsthost, flt_srchost, flt_baseport;
  67.  
  68.  
  69. FingerPrint *get_fingerprint(struct hoststruct *target, struct seq_info *si) {
  70. FingerPrint *FP = NULL, *FPtmp = NULL;
  71. FingerPrint *FPtests[9];
  72. struct AVal *seq_AVs;
  73. u16 lastipid=0; /* For catching duplicate packets */
  74. int last;
  75. u32 timestamp = 0; /* TCP timestamp we receive back */
  76. struct ip *ip;
  77. struct tcphdr *tcp;
  78. struct icmp *icmp;
  79. struct timeval t1,t2;
  80. int i;
  81. struct hostent *myhostent = NULL;
  82. pcap_t *pd;
  83. char myname[513];
  84. int rawsd;
  85. int tries = 0;
  86. int newcatches;
  87. int current_port = 0;
  88. int testsleft;
  89. int testno;
  90. int  timeout;
  91. int avnum;
  92. unsigned int sequence_base;
  93. unsigned int openport;
  94. unsigned int bytes;
  95. unsigned int closedport = 31337;
  96. struct port *tport = NULL;
  97. char *p;
  98. char filter[512];
  99. double seq_inc_sum = 0;
  100. unsigned int  seq_avg_inc = 0;
  101. struct udpprobeinfo *upi = NULL;
  102. u32 seq_gcd = 1;
  103. u32 seq_diffs[NUM_SEQ_SAMPLES];
  104. u32 ts_diffs[NUM_SEQ_SAMPLES];
  105. unsigned long time_usec_diffs[NUM_SEQ_SAMPLES];
  106. struct timeval seq_send_times[NUM_SEQ_SAMPLES];
  107. int ossofttimeout, oshardtimeout;
  108. int seq_packets_sent = 0;
  109. int seq_response_num; /* response # for sequencing */
  110. double avg_ts_hz = 0.0; /* Avg. amount that timestamps incr. each second */
  111. if (target->timedout)
  112.   return NULL;
  113.  
  114. /* The seqs must start out as zero for the si struct */
  115. bzero(si->seqs, sizeof(si->seqs));
  116. si->ipid_seqclass = IPID_SEQ_UNKNOWN;
  117. si->ts_seqclass = TS_SEQ_UNKNOWN;
  118. si->lastboot = 0;
  119.  
  120. /* Init our fingerprint tests to each be NULL */
  121. bzero(FPtests, sizeof(FPtests)); 
  122. get_random_bytes(&sequence_base, sizeof(unsigned int));
  123. /* Init our raw socket */
  124.  if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
  125.    pfatal("socket trobles in get_fingerprint");
  126.  unblock_socket(rawsd);
  127.  broadcast_socket(rawsd);
  128.  
  129.  /* Do we have a correct source address? */
  130.  if (!target->source_ip.s_addr) {
  131.    if (gethostname(myname, MAXHOSTNAMELEN) != 0 &&
  132.        !((myhostent = gethostbyname(myname))))
  133.      fatal("Cannot get hostname!  Try using -S <my_IP_address> or -e <interface to scan through>\n");
  134.    memcpy(&target->source_ip, myhostent->h_addr_list[0], sizeof(struct in_addr));
  135.    if (o.debugging || o.verbose)
  136.      log_write(LOG_STDOUT, "We skillfully deduced that your address is %s\n",
  137.         inet_ntoa(target->source_ip));
  138.  }
  139.  /* Now for the pcap opening nonsense ... */
  140.  /* Note that the snaplen is 152 = 64 byte max IPhdr + 24 byte max link_layer
  141.   * header + 64 byte max TCP header.  Had to up it for UDP test
  142.   */
  143.  
  144. ossofttimeout = MAX(200000, target->to.timeout);
  145. oshardtimeout = MAX(500000, 5 * target->to.timeout);
  146.  
  147.  pd = my_pcap_open_live(target->device, /*650*/ 8192,  (o.spoofsource)? 1 : 0, (ossofttimeout + 500)/ 1000);
  148.  
  149. if (o.debugging)
  150.    log_write(LOG_STDOUT, "Wait time is %dms\n", (ossofttimeout +500)/1000);
  151.  
  152.  flt_srchost = target->host.s_addr;
  153.  flt_dsthost = target->source_ip.s_addr;
  154.  
  155.  p = strdup(inet_ntoa(target->host));
  156.  
  157. 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));
  158.  free(p);
  159.  
  160.  set_pcap_filter(target, pd, flt_icmptcp, filter);
  161.  target->osscan_performed = 1; /* Let Nmap know that we did try an OS scan */
  162.  
  163.  /* Lets find an open port to used */
  164.  openport = (unsigned long) -1;
  165.  target->osscan_openport = -1;
  166.  target->osscan_closedport = -1;
  167.  tport = NULL;
  168.  if (target->ports.state_counts_tcp[PORT_OPEN] > 0) { 
  169.    tport = nextport(&target->ports, NULL, IPPROTO_TCP, PORT_OPEN);
  170.    assert(tport);
  171.    openport = tport->portno;
  172.    target->osscan_openport = tport->portno;
  173.  }
  174.  
  175.  /* Now we should find a closed port */
  176.  if (target->ports.state_counts_tcp[PORT_CLOSED] > 0) {
  177.    tport = nextport(&target->ports, NULL, IPPROTO_TCP, PORT_CLOSED);
  178.    assert(tport);
  179.    closedport = tport->portno;
  180.    target->osscan_closedport = tport->portno;
  181.  } else if (target->ports.state_counts_tcp[PORT_UNFIREWALLED] > 0) {
  182.    /* Well, we will settle for unfiltered */
  183.    tport = nextport(&target->ports, NULL, IPPROTO_TCP, PORT_UNFIREWALLED);
  184.    assert(tport);
  185.    closedport = tport->portno;
  186.  } else {
  187.    closedport = (get_random_uint() % 14781) + 30000;
  188.  }
  189.  
  190. if (o.verbose && openport != (unsigned long) -1)
  191.   log_write(LOG_STDOUT, "For OSScan assuming that port %d is open and port %d is closed and neither are firewalled\n", openport, closedport);
  192.  
  193.  current_port = o.magic_port + NUM_SEQ_SAMPLES +1;
  194.  
  195.  /* Now lets do the NULL packet technique */
  196.  testsleft = (openport == (unsigned long) -1)? 4 : 7;
  197.  FPtmp = NULL;
  198.  /* bzero(FPtests, sizeof(FPtests));*/
  199.  tries = 0;
  200.  do { 
  201.    newcatches = 0;
  202.    if (openport != (unsigned long) -1) {   
  203.      /* Test 1 */
  204.      if (!FPtests[1]) {     
  205.        if (o.scan_delay) enforce_scan_delay(NULL);
  206.        send_tcp_raw_decoys(rawsd, &target->host, current_port, 
  207.                openport, sequence_base, 0,TH_BOGUS|TH_SYN, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  208.      }
  209.      
  210.      /* Test 2 */
  211.      if (!FPtests[2]) {     
  212.        if (o.scan_delay) enforce_scan_delay(NULL);
  213.        send_tcp_raw_decoys(rawsd, &target->host, current_port +1, 
  214.                openport, sequence_base, 0,0, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  215.      }
  216.  
  217.      /* Test 3 */
  218.      if (!FPtests[3]) {     
  219.        if (o.scan_delay) enforce_scan_delay(NULL);
  220.        send_tcp_raw_decoys(rawsd, &target->host, current_port +2, 
  221.                openport, sequence_base, 0,TH_SYN|TH_FIN|TH_URG|TH_PUSH, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  222.      }
  223.  
  224.      /* Test 4 */
  225.      if (!FPtests[4]) {     
  226.        if (o.scan_delay) enforce_scan_delay(NULL);
  227.        send_tcp_raw_decoys(rawsd, &target->host, current_port +3, 
  228.                openport, sequence_base, 0,TH_ACK, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  229.      }
  230.    }
  231.    
  232.    /* Test 5 */
  233.    if (!FPtests[5]) {   
  234.      if (o.scan_delay) enforce_scan_delay(NULL);
  235.      send_tcp_raw_decoys(rawsd, &target->host, current_port +4,
  236.              closedport, sequence_base, 0,TH_SYN, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  237.    }
  238.  
  239.      /* Test 6 */
  240.    if (!FPtests[6]) {   
  241.      if (o.scan_delay) enforce_scan_delay(NULL);
  242.      send_tcp_raw_decoys(rawsd, &target->host, current_port +5, 
  243.              closedport, sequence_base, 0,TH_ACK, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  244.    }
  245.  
  246.      /* Test 7 */
  247.    if (!FPtests[7]) {
  248.      if (o.scan_delay) enforce_scan_delay(NULL);   
  249.      send_tcp_raw_decoys(rawsd, &target->host, current_port +6, 
  250.              closedport, sequence_base, 0,TH_FIN|TH_PUSH|TH_URG, 0,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  251.    }
  252.  
  253.    if (!FPtests[8]) {
  254.      if (o.scan_delay) enforce_scan_delay(NULL);
  255.      upi = send_closedudp_probe(rawsd, &target->host, o.magic_port, closedport);
  256.    }
  257.    gettimeofday(&t1, NULL);
  258.    timeout = 0;
  259.  
  260.    /* Insure we haven't overrun our allotted time ... */
  261.    if (o.host_timeout && (TIMEVAL_MSEC_SUBTRACT(t1, target->host_timeout) >= 0))
  262.      {
  263.        target->timedout = 1;
  264.        goto osscan_timedout;
  265.      }
  266.    while(( ip = (struct ip*) readip_pcap(pd, &bytes, oshardtimeout)) && !timeout) {
  267.      gettimeofday(&t2, NULL);
  268.      if (TIMEVAL_SUBTRACT(t2,t1) > oshardtimeout) {
  269.        timeout = 1;
  270.      }
  271.      if (o.host_timeout && (TIMEVAL_MSEC_SUBTRACT(t2, target->host_timeout) >= 0))
  272.        {
  273.      target->timedout = 1;
  274.      goto osscan_timedout;
  275.        }
  276.  
  277.      if (bytes < (4 * ip->ip_hl) + 4U)
  278.        continue;
  279.      if (ip->ip_p == IPPROTO_TCP) {
  280.        tcp = ((struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl));
  281.        testno = ntohs(tcp->th_dport) - current_port + 1;
  282.        if (testno <= 0 || testno > 7)
  283.      continue;
  284.        if (o.debugging > 1)
  285.      log_write(LOG_STDOUT, "Got packet for test number %d\n", testno);
  286.        if (FPtests[testno]) continue;
  287.        testsleft--;
  288.        newcatches++;
  289.        FPtests[testno] = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  290.        bzero(FPtests[testno], sizeof(FingerPrint));
  291.        FPtests[testno]->results = fingerprint_iptcppacket(ip, 265, sequence_base);
  292.        FPtests[testno]->name = (testno == 1)? "T1" : (testno == 2)? "T2" : (testno == 3)? "T3" : (testno == 4)? "T4" : (testno == 5)? "T5" : (testno == 6)? "T6" : (testno == 7)? "T7" : "PU";
  293.      } else if (ip->ip_p == IPPROTO_ICMP) {
  294.        icmp = ((struct icmp *)  (((char *) ip) + 4 * ip->ip_hl));
  295.        /* It must be a destination port unreachable */
  296.        if (icmp->icmp_type != 3 || icmp->icmp_code != 3) {
  297.      /* This ain't no stinking port unreachable! */
  298.      continue;
  299.        }
  300.        if (bytes < (unsigned int) ntohs(ip->ip_len)) {
  301.      error("We only got %d bytes out of %d on our ICMP port unreachable packet, skipping", bytes, ntohs(ip->ip_len));
  302.      continue;
  303.        }
  304.        if (FPtests[8]) continue;
  305.        FPtests[8] = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  306.        bzero(FPtests[8], sizeof(FingerPrint));
  307.        FPtests[8]->results = fingerprint_portunreach(ip, upi);
  308.        if (FPtests[8]->results) {       
  309.      FPtests[8]->name = "PU";
  310.      testsleft--;
  311.      newcatches++;
  312.        } else {
  313.      free(FPtests[8]);
  314.      FPtests[8] = NULL;
  315.        }
  316.      }
  317.     if (testsleft == 0)
  318.       break;
  319.    }     
  320.  } while ( testsleft > 0 && (tries++ < 5 && (newcatches || tries == 1)));
  321.  
  322.  si->responses = 0;
  323.  timeout = 0; 
  324.  gettimeofday(&t1,NULL);
  325.  /* First we send our initial NUM_SEQ_SAMPLES SYN packets  */
  326.  if (openport != (unsigned long) -1) {
  327.    seq_packets_sent = 0;
  328.    while (seq_packets_sent < NUM_SEQ_SAMPLES) {
  329.      if (o.scan_delay) enforce_scan_delay(NULL);
  330.      send_tcp_raw_decoys(rawsd, &target->host, 
  331.              o.magic_port + seq_packets_sent + 1, 
  332.              openport, 
  333.              sequence_base + seq_packets_sent + 1, 0, 
  334.              TH_SYN, 0 ,"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000" , 20, NULL, 0);
  335.      if (!o.scan_delay)
  336.        usleep( MAX(110000, target->to.srtt)); /* Main reason we wait so long is that we need to spend more than .5 seconds to detect 2HZ timestamp sequencing -- this also should make ISN sequencing more regular */
  337.    
  338.      gettimeofday(&seq_send_times[seq_packets_sent], NULL);
  339.      seq_packets_sent++;
  340.      
  341.      /* Now we collect  the replies */
  342.      
  343.      while(si->responses < seq_packets_sent && !timeout) {
  344.        
  345.        if (seq_packets_sent == NUM_SEQ_SAMPLES)
  346.      ip = (struct ip*) readip_pcap(pd, &bytes, oshardtimeout);
  347.        else ip = (struct ip*) readip_pcap(pd, &bytes, 10);
  348.        
  349.        gettimeofday(&t2, NULL);
  350.        /*     error("DEBUG: got a response (len=%d):\n", bytes);  */
  351.        /*     lamont_hdump((unsigned char *) ip, bytes); */
  352.        /* Insure we haven't overrun our allotted time ... */
  353.        if (o.host_timeout && (TIMEVAL_MSEC_SUBTRACT(t2, target->host_timeout) >= 0))
  354.      {
  355.        target->timedout = 1;
  356.        goto osscan_timedout;
  357.      }
  358.        if (!ip) { 
  359.      if (seq_packets_sent < NUM_SEQ_SAMPLES)
  360.        break;
  361.      if (TIMEVAL_SUBTRACT(t2,t1) > ossofttimeout)
  362.        timeout = 1;
  363.      continue; 
  364.        } else if (TIMEVAL_SUBTRACT(t2,t1) > oshardtimeout) {
  365.      timeout = 1;
  366.        }          
  367.        if (lastipid != 0 && ip->ip_id == lastipid) {
  368.      /* Probably a duplicate -- this happens sometimes when scanning localhost */
  369.      continue;
  370.        }
  371.        lastipid = ip->ip_id;
  372.  
  373.        if (bytes < (4 * ip->ip_hl) + 4U)
  374.      continue;
  375.        if (ip->ip_p == IPPROTO_TCP) {
  376.      /*       readtcppacket((char *) ip, ntohs(ip->ip_len));  */
  377.      tcp = ((struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl));
  378.      if (ntohs(tcp->th_dport) < o.magic_port || ntohs(tcp->th_dport) - o.magic_port > NUM_SEQ_SAMPLES || ntohs(tcp->th_sport) != openport) {
  379.        continue;
  380.      }
  381.      if ((tcp->th_flags & TH_RST)) {
  382.        /*     readtcppacket((char *) ip, ntohs(ip->ip_len));*/     
  383.        if (si->responses == 0) {     
  384.          fprintf(stderr, "WARNING:  RST from port %hu -- is this port really open?\n", openport);
  385.          /* We used to quit in this case, but left-overs from a SYN
  386.         scan or lame-ass TCP wrappers can cause this! */
  387.        } 
  388.        continue;
  389.      } else if ((tcp->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
  390.        /*    error("DEBUG: response is SYN|ACK to port %hu\n", ntohs(tcp->th_dport)); */
  391.        /*readtcppacket((char *)ip, ntohs(ip->ip_len));*/
  392.        /* We use the ACK value to match up our sent with rcv'd packets */
  393.        seq_response_num = (ntohl(tcp->th_ack) - 2 - 
  394.                    sequence_base); 
  395.        if (seq_response_num < 0 || seq_response_num >= seq_packets_sent) {
  396.          /* BzzT! Value out of range */
  397.          if (o.debugging) {
  398.            error("Unable to associate os scan response with sent packet (received ack: %lX; sequence base: %lX. Packet:", ntohl(tcp->th_ack), sequence_base);
  399.            readtcppacket((char *)ip,BSDUFIX(ip->ip_len));
  400.          }
  401.          seq_response_num = si->responses;
  402.        }
  403.        si->responses++;
  404.        si->seqs[seq_response_num] = ntohl(tcp->th_seq); /* TCP ISN */
  405.        si->ipids[seq_response_num] = ntohs(ip->ip_id);
  406.        if ((gettcpopt_ts(tcp, ×tamp, NULL) == 0))
  407.          si->ts_seqclass = TS_SEQ_UNSUPPORTED;
  408.        else {
  409.          if (timestamp == 0) {
  410.            si->ts_seqclass = TS_SEQ_ZERO;
  411.          }
  412.        }
  413.        si->timestamps[seq_response_num] = timestamp;
  414.        /*           printf("Response #%d -- ipid=%hu ts=%i\n", seq_response_num, ntohs(ip->ip_id), timestamp); */
  415.        if (si->responses > 1) {
  416.          seq_diffs[si->responses-2] = MOD_DIFF(ntohl(tcp->th_seq), si->seqs[si->responses-2]);
  417.        }      
  418.      }
  419.        }
  420.      }
  421.    }
  422.  
  423.    /* Now we make sure there are no gaps in our response array ... */
  424.    for(i=0, si->responses=0; i < seq_packets_sent; i++) {
  425.      if (si->seqs[i] != 0) /* We found a good one */ {
  426.        if (si->responses < i) {
  427.      si->seqs[si->responses] = si->seqs[i];
  428.      si->ipids[si->responses] = si->ipids[i];
  429.      si->timestamps[si->responses] = si->timestamps[i];
  430.      seq_send_times[si->responses] = seq_send_times[i];
  431.        }
  432.        if (si->responses > 0) {
  433.      seq_diffs[si->responses - 1] = MOD_DIFF(si->seqs[si->responses], si->seqs[si->responses - 1]);
  434.      ts_diffs[si->responses - 1] = MOD_DIFF(si->timestamps[si->responses], si->timestamps[si->responses - 1]);
  435.      time_usec_diffs[si->responses - 1] = TIMEVAL_SUBTRACT(seq_send_times[si->responses], seq_send_times[si->responses - 1]);
  436.      if (!time_usec_diffs[si->responses - 1]) time_usec_diffs[si->responses - 1]++; /* We divide by this later */
  437.      /*     printf("MOD_DIFF_USHORT(%hu, %hu) == %hu\n", si->ipids[si->responses], si->ipids[si->responses - 1], MOD_DIFF_USHORT(si->ipids[si->responses], si->ipids[si->responses - 1])); */
  438.        }
  439.  
  440.        si->responses++;
  441.      } /* Otherwise nothing good in this slot to copy */
  442.    }
  443.      
  444.  
  445.    si->ipid_seqclass = ipid_sequence(si->responses, si->ipids, 
  446.                      islocalhost(&(target->host)));
  447.  
  448.    /* Now we look at TCP Timestamp sequence prediction */
  449.    /* Battle plan:
  450.       1) Compute average increments per second, and variance in incr. per second 
  451.       2) If any are 0, set to constant
  452.       3) If variance is high, set to random incr. [ skip for now ]
  453.       4) if ~10/second, set to appropriate thing
  454.       5) Same with ~100/sec
  455.    */
  456.    if (si->ts_seqclass == TS_SEQ_UNKNOWN && si->responses >= 2) {
  457.      avg_ts_hz = 0.0;
  458.      for(i=0; i < si->responses - 1; i++) {
  459.        double hz;
  460.  
  461.        hz = (double) ts_diffs[i] / (time_usec_diffs[i] / 1000000.0);
  462.        /*       printf("ts incremented by %d in %li usec -- %fHZ\n", ts_diffs[i], time_usec_diffs[i], hz); */
  463.        avg_ts_hz += hz / ( si->responses - 1);
  464.      }
  465.  
  466.      if (o.debugging)
  467.        printf("The avg TCP TS HZ is: %f\n", avg_ts_hz);
  468.      
  469.      if (avg_ts_hz > 0 && avg_ts_hz < 3.9) { /* relatively wide range because sampling time so short and frequency so slow */
  470.        si->ts_seqclass = TS_SEQ_2HZ;
  471.        si->lastboot = seq_send_times[0].tv_sec - (si->timestamps[0] / 2); 
  472.      }
  473.      else if (avg_ts_hz > 85 && avg_ts_hz < 115) {
  474.        si->ts_seqclass = TS_SEQ_100HZ;
  475.        si->lastboot = seq_send_times[0].tv_sec - (si->timestamps[0] / 100); 
  476.      }
  477.      else if (avg_ts_hz > 900 && avg_ts_hz < 1100) {
  478.        si->ts_seqclass = TS_SEQ_1000HZ;
  479.        si->lastboot = seq_send_times[0].tv_sec - (si->timestamps[0] / 1000); 
  480.      }
  481.    }
  482.    
  483.    /* Time to look at the TCP ISN predictability */
  484.    if (si->responses >= 4 && o.scan_delay <= 1000) {
  485.      seq_gcd = gcd_n_uint(si->responses -1, seq_diffs);
  486.      /*     printf("The GCD is %u\n", seq_gcd);*/
  487.      if (seq_gcd) {     
  488.        for(i=0; i < si->responses - 1; i++)
  489.      seq_diffs[i] /= seq_gcd;
  490.        for(i=0; i < si->responses - 1; i++) {     
  491.      if (MOD_DIFF(si->seqs[i+1],si->seqs[i]) > 50000000) {
  492.        si->seqclass = SEQ_TR;
  493.        si->index = 9999999;
  494.        /*     printf("Target is a TR box\n");*/
  495.        break;
  496.      }    
  497.      seq_avg_inc += seq_diffs[i];
  498.        }
  499.      }
  500.      if (seq_gcd == 0) {
  501.        si->seqclass = SEQ_CONSTANT;
  502.        si->index = 0;
  503.      } else if (seq_gcd % 64000 == 0) {
  504.        si->seqclass = SEQ_64K;
  505.        /*       printf("Target is a 64K box\n");*/
  506.        si->index = 1;
  507.      } else if (seq_gcd % 800 == 0) {
  508.        si->seqclass = SEQ_i800;
  509.        /*       printf("Target is a i800 box\n");*/
  510.        si->index = 10;
  511.      } else if (si->seqclass == SEQ_UNKNOWN) {
  512.        seq_avg_inc = (unsigned int) ((0.5) + seq_avg_inc / (si->responses - 1));
  513.        /*       printf("seq_avg_inc=%u\n", seq_avg_inc);*/
  514.        for(i=0; i < si->responses -1; i++)       {     
  515.  
  516.      /*     printf("The difference is %u\n", seq_diffs[i]);
  517.          printf("Adding %u^2=%e", MOD_DIFF(seq_diffs[i], seq_avg_inc), pow(MOD_DIFF(seq_diffs[i], seq_avg_inc), 2));*/
  518.      /* pow() seems F#@!#$!ed up on some Linux systems so I will
  519.         not use it for now 
  520.           seq_inc_sum += pow(MOD_DIFF(seq_diffs[i], seq_avg_inc), 2);
  521.      */     
  522.      
  523.      seq_inc_sum += ((double)(MOD_DIFF(seq_diffs[i], seq_avg_inc)) * ((double)MOD_DIFF(seq_diffs[i], seq_avg_inc)));
  524.      /*     seq_inc_sum += pow(MOD_DIFF(seq_diffs[i], seq_avg_inc), 2);*/
  525.  
  526.        }
  527.        /*       printf("The sequence sum is %e\n", seq_inc_sum);*/
  528.        seq_inc_sum /= (si->responses - 1);
  529.  
  530.        /* Some versions of Linux libc seem to have broken pow ... so we
  531.       avoid it */
  532. #ifdef LINUX       
  533.        si->index = (unsigned int) (0.5 + sqrt(seq_inc_sum));
  534. #else
  535.        si->index = (unsigned int) (0.5 + pow(seq_inc_sum, 0.5));
  536. #endif
  537.  
  538.        /*       printf("The sequence index is %d\n", si->index);*/
  539.        if (si->index < 75) {
  540.      si->seqclass = SEQ_TD;
  541.      /*     printf("Target is a Micro$oft style time dependant box\n");*/
  542.        }
  543.        else {
  544.      si->seqclass = SEQ_RI;
  545.      /*     printf("Target is a random incremental box\n");*/
  546.        }
  547.      }
  548.      FPtests[0] = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  549.      bzero(FPtests[0], sizeof(FingerPrint));
  550.      FPtests[0]->name = "TSeq";
  551.      seq_AVs = (struct AVal *) safe_malloc(sizeof(struct AVal) * 5);
  552.      bzero(seq_AVs, sizeof(struct AVal) * 5);
  553.      FPtests[0]->results = seq_AVs;
  554.      avnum = 0;
  555.      seq_AVs[avnum].attribute = "Class";
  556.      switch(si->seqclass) {
  557.      case SEQ_CONSTANT:
  558.        strcpy(seq_AVs[avnum].value, "C");
  559.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  560.        seq_AVs[avnum].attribute= "Val";     
  561.        sprintf(seq_AVs[avnum].value, "%X", si->seqs[0]);
  562.        break;
  563.      case SEQ_64K:
  564.        strcpy(seq_AVs[avnum].value, "64K");      
  565.        break;
  566.      case SEQ_i800:
  567.        strcpy(seq_AVs[avnum].value, "i800");
  568.        break;
  569.      case SEQ_TD:
  570.        strcpy(seq_AVs[avnum].value, "TD");
  571.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  572.        seq_AVs[avnum].attribute= "gcd";     
  573.        sprintf(seq_AVs[avnum].value, "%X", seq_gcd);
  574.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  575.        seq_AVs[avnum].attribute="SI";
  576.        sprintf(seq_AVs[avnum].value, "%X", si->index);
  577.        break;
  578.      case SEQ_RI:
  579.        strcpy(seq_AVs[avnum].value, "RI");
  580.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  581.        seq_AVs[avnum].attribute= "gcd";     
  582.        sprintf(seq_AVs[avnum].value, "%X", seq_gcd);
  583.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  584.        seq_AVs[avnum].attribute="SI";
  585.        sprintf(seq_AVs[avnum].value, "%X", si->index);
  586.        break;
  587.      case SEQ_TR:
  588.        strcpy(seq_AVs[avnum].value, "TR");
  589.        break;
  590.      }
  591.  
  592.      /* IP ID Class */
  593.      switch(si->ipid_seqclass) {
  594.      case IPID_SEQ_CONSTANT:
  595.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  596.        seq_AVs[avnum].attribute = "IPID";
  597.        strcpy(seq_AVs[avnum].value, "C");
  598.        break;
  599.      case IPID_SEQ_INCR:
  600.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  601.        seq_AVs[avnum].attribute = "IPID";
  602.        strcpy(seq_AVs[avnum].value, "I");
  603.        break;
  604.      case IPID_SEQ_BROKEN_INCR:
  605.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  606.        seq_AVs[avnum].attribute = "IPID";
  607.        strcpy(seq_AVs[avnum].value, "BI");
  608.        break;
  609.      case IPID_SEQ_RPI:
  610.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  611.        seq_AVs[avnum].attribute = "IPID";
  612.        strcpy(seq_AVs[avnum].value, "RPI");
  613.        break;
  614.      case IPID_SEQ_RD:
  615.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  616.        seq_AVs[avnum].attribute = "IPID";
  617.        strcpy(seq_AVs[avnum].value, "RD");
  618.        break;
  619.      case IPID_SEQ_ZERO:
  620.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  621.        seq_AVs[avnum].attribute = "IPID";
  622.        strcpy(seq_AVs[avnum].value, "Z");
  623.        break;
  624.      }
  625.  
  626.      /* TCP Timestamp option sequencing */
  627.      switch(si->ts_seqclass) {
  628.      case TS_SEQ_ZERO:
  629.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  630.        seq_AVs[avnum].attribute = "TS";
  631.        strcpy(seq_AVs[avnum].value, "0");
  632.        break;
  633.      case TS_SEQ_2HZ:
  634.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  635.        seq_AVs[avnum].attribute = "TS";
  636.        strcpy(seq_AVs[avnum].value, "2HZ");
  637.        break;
  638.      case TS_SEQ_100HZ:
  639.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  640.        seq_AVs[avnum].attribute = "TS";
  641.        strcpy(seq_AVs[avnum].value, "100HZ");
  642.        break;
  643.      case TS_SEQ_1000HZ:
  644.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  645.        seq_AVs[avnum].attribute = "TS";
  646.        strcpy(seq_AVs[avnum].value, "1000HZ");
  647.        break;
  648.      case TS_SEQ_UNSUPPORTED:
  649.        seq_AVs[avnum].next = &seq_AVs[avnum+1]; avnum++;
  650.        seq_AVs[avnum].attribute = "TS";
  651.        strcpy(seq_AVs[avnum].value, "U");
  652.        break;
  653.      }
  654.    }
  655.    else {
  656.      log_write(LOG_STDOUT|LOG_NORMAL|LOG_SKID,"Insufficient responses for TCP sequencing (%d), OS detection may be less accurate\n", si->responses);
  657.    }
  658.  } else {
  659.  }
  660.  
  661. for(i=0; i < 9; i++) {
  662.   if (i > 0 && !FPtests[i] && ((openport != (unsigned long) -1) || i > 4)) {
  663.     /* We create a Resp (response) attribute with value of N (no) because
  664.        it is important here to note whether responses were or were not 
  665.        received */
  666.     FPtests[i] = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  667.     bzero(FPtests[i], sizeof(FingerPrint));
  668.     seq_AVs = (struct AVal *) safe_malloc(sizeof(struct AVal));
  669.     seq_AVs->attribute = "Resp";
  670.     strcpy(seq_AVs->value, "N");
  671.     seq_AVs->next = NULL;
  672.     FPtests[i]->results = seq_AVs;
  673.     FPtests[i]->name =  (i == 1)? "T1" : (i == 2)? "T2" : (i == 3)? "T3" : (i == 4)? "T4" : (i == 5)? "T5" : (i == 6)? "T6" : (i == 7)? "T7" : "PU";
  674.   }
  675. }
  676.  last = -1;
  677.  FP = NULL;
  678.  for(i=0; i < 9 ; i++) {
  679.    if (!FPtests[i]) continue; 
  680.    if (!FP) FP = FPtests[i];
  681.    if (last > -1) {
  682.      FPtests[last]->next = FPtests[i];    
  683.    }
  684.    last = i;
  685.  }
  686.  if (last) FPtests[last]->next = NULL;
  687.  
  688.  osscan_timedout:
  689.  if (target->timedout)
  690.    FP = NULL;
  691.  close(rawsd);
  692.  pcap_close(pd);
  693.  return FP;
  694. }
  695.  
  696.  
  697. struct AVal *fingerprint_iptcppacket(struct ip *ip, int mss, u32 syn) {
  698.   struct AVal *AVs;
  699.   int length;
  700.   int opcode;
  701.   u16 tmpshort;
  702.   char *p,*q;
  703.   struct tcphdr *tcp = ((struct tcphdr *) (((char *) ip) + 4 * ip->ip_hl));
  704.  
  705.   AVs = (struct AVal *) malloc(6 * sizeof(struct AVal));
  706.  
  707.   /* Link them together */
  708.   AVs[0].next = &AVs[1];
  709.   AVs[1].next = &AVs[2];
  710.   AVs[2].next = &AVs[3];
  711.   AVs[3].next = &AVs[4];
  712.   AVs[4].next = &AVs[5];
  713.   AVs[5].next = NULL;
  714.  
  715.   /* First we give the "response" flag to say we did actually receive
  716.      a packet -- this way we won't match a template with Resp=N */
  717.   AVs[0].attribute = "Resp";
  718.   strcpy(AVs[0].value, "Y");
  719.  
  720.  
  721.   /* Next we check whether the Don't Fragment bit is set */
  722.   AVs[1].attribute = "DF";
  723.   if(ntohs(ip->ip_off) & 0x4000) {
  724.     strcpy(AVs[1].value,"Y");
  725.   } else strcpy(AVs[1].value, "N");
  726.  
  727.   /* Now we do the TCP Window size */
  728.   AVs[2].attribute = "W";
  729.   sprintf(AVs[2].value, "%hX", ntohs(tcp->th_win));
  730.  
  731.   /* Time for the ACK, the codes are:
  732.      S   = same as syn
  733.      S++ = syn + 1
  734.      O   = other
  735.   */
  736.   AVs[3].attribute = "ACK";
  737.   if (ntohl(tcp->th_ack) == syn + 1)
  738.     strcpy(AVs[3].value, "S++");
  739.   else if (ntohl(tcp->th_ack) == syn) 
  740.     strcpy(AVs[3].value, "S");
  741.   else strcpy(AVs[3].value, "O");
  742.     
  743.   /* Now time for the flags ... they must be in this order:
  744.      B = Bogus (64, not a real TCP flag)
  745.      U = Urgent
  746.      A = Acknowledgement
  747.      P = Push
  748.      R = Reset
  749.      S = Synchronize
  750.      F = Final
  751.   */
  752.   AVs[4].attribute = "Flags";
  753.   p = AVs[4].value;
  754.   if (tcp->th_flags & TH_BOG) *p++ = 'B';
  755.   if (tcp->th_flags & TH_URG) *p++ = 'U';
  756.   if (tcp->th_flags & TH_ACK) *p++ = 'A';
  757.   if (tcp->th_flags & TH_PUSH) *p++ = 'P';
  758.   if (tcp->th_flags & TH_RST) *p++ = 'R';
  759.   if (tcp->th_flags & TH_SYN) *p++ = 'S';
  760.   if (tcp->th_flags & TH_FIN) *p++ = 'F';
  761.   *p++ = '\0';
  762.  
  763.   /* Now for the TCP options ... */
  764.   AVs[5].attribute = "Ops";
  765.   p = AVs[5].value;
  766.   /* Partly swiped from /usr/src/linux/net/ipv4/tcp_input.c in Linux kernel */
  767.   length = (tcp->th_off * 4) - sizeof(struct tcphdr);
  768.   q = ((char *)tcp) + sizeof(struct tcphdr);
  769.  
  770.   while(length > 0 &&
  771.     ((p - AVs[5].value) < (int) (sizeof(AVs[5].value) - 3))) {
  772.     opcode=*q++;
  773.     length--;
  774.     if (!opcode) {
  775.       *p++ = 'L'; /* End of List */
  776.       break;
  777.     } else if (opcode == 1) {
  778.       *p++ = 'N'; /* No Op */
  779.     } else if (opcode == 2) {
  780.       *p++ = 'M'; /* MSS */
  781.       q++;
  782.       memcpy(&tmpshort, q, 2);
  783.       if(ntohs(tmpshort) == mss)
  784.     *p++ = 'E'; /* Echoed */
  785.       q += 2;
  786.       length -= 3;
  787.     } else if (opcode == 3) { /* Window Scale */
  788.       *p++ = 'W';
  789.       q += 2;
  790.       length -= 2;
  791.     } else if (opcode == 8) { /* Timestamp */
  792.       *p++ = 'T';
  793.       q += 9;
  794.       length -= 9;
  795.     }
  796.   }
  797.   *p++ = '\0';
  798.   return AVs;
  799. }
  800.  
  801. /* Takes a fingerprint and returns the matches in FPR (which must
  802.    point to an allocated FingerPrintResults structure) -- results will
  803.    be reverse-sorted by accuracy.  No results below
  804.    accuracy_threshhold will be included.  The max matches returned is
  805.    the maximum that fits in a FingerPrintResults structure.  The
  806.    allocated FingerPrintResults does not have to be initialized --
  807.    that will be done in this function.  */
  808.  
  809. void match_fingerprint(FingerPrint *FP, struct FingerPrintResults *FPR, 
  810.               double accuracy_threshold) {
  811.  
  812.   int i;
  813.   double FPR_entrance_requirement = accuracy_threshold; /* accuracy must be 
  814.                                at least this big 
  815.                                to be added to the 
  816.                                list */
  817.   struct AVal *tst;
  818.   FingerPrint *current_os;
  819.   FingerPrint *current_test;
  820.   unsigned long num_subtests=0;
  821.   unsigned long num_subtests_succeeded=0;
  822.   double acc;
  823.   int state;
  824.   int skipfp;
  825.   int max_prints = sizeof(FPR->prints) / sizeof(FingerPrint *);
  826.   int idx;
  827.   double tmp_acc=0.0, tmp_acc2; /* These are temp buffers for list swaps */
  828.   FingerPrint *tmp_FP=NULL, *tmp_FP2;
  829.  
  830.   assert(FP);
  831.   assert(FPR);
  832.   assert(accuracy_threshold >= 0 && accuracy_threshold <= 1);
  833.  
  834.   bzero(FPR, sizeof(*FPR));
  835.   FPR->overall_results = OSSCAN_SUCCESS;
  836.   
  837.   for(i = 0; o.reference_FPs[i]; i++) {
  838.     current_os = o.reference_FPs[i];
  839.     skipfp = 0;
  840.     num_subtests = num_subtests_succeeded = 0;
  841.  
  842.     for(current_test = current_os; current_test; current_test = current_test->next) 
  843.       {
  844.     tst = gettestbyname(FP, current_test->name);
  845.     if (tst) {
  846.       AVal_match(current_test->results, tst, &num_subtests, &num_subtests_succeeded, 0);
  847.     }
  848.       }
  849.     assert(num_subtests_succeeded <= num_subtests);
  850.     acc = (num_subtests)? (num_subtests_succeeded / (double) num_subtests) : 0;
  851.     /*    error("Comp to %s: %li/%li=%f", o.reference_FPs[i]->OS_name, num_subtests_succeeded, num_subtests, acc); */
  852.     if (acc >= FPR_entrance_requirement || acc == 1.0) {
  853.  
  854.       state = 0;
  855.       for(idx=0; idx < FPR->num_matches; idx++) {    
  856.     if (strcmp(FPR->prints[idx]->OS_name, current_os->OS_name) == 0) {
  857.       if (FPR->accuracy[idx] >= acc) {
  858.         skipfp = 1; /* Skip it -- a higher version is already in list */
  859.       } else {      
  860.         /* We must shift the list left to delete this sucker */
  861.         memmove(FPR->prints + idx, FPR->prints + idx + 1,
  862.             (FPR->num_matches - 1 - idx) * sizeof(FingerPrint *));
  863.         memmove(FPR->accuracy + idx, FPR->accuracy + idx + 1,
  864.             (FPR->num_matches - 1 - idx) * sizeof(double));
  865.         FPR->num_matches--;
  866.         FPR->accuracy[FPR->num_matches] = 0;
  867.       }
  868.       break; /* There can only be 1 in the list with same name */
  869.     }
  870.       }
  871.  
  872.       if (!skipfp) {      
  873.     /* First we check whether we have overflowed with perfect matches */
  874.     if (acc == 1) {
  875.       /*      error("DEBUG: Perfect match #%d/%d", FPR->num_perfect_matches + 1, max_prints); */
  876.       if (FPR->num_perfect_matches == max_prints) {
  877.         FPR->overall_results = OSSCAN_TOOMANYMATCHES;
  878.         return;
  879.       }
  880.       FPR->num_perfect_matches++;
  881.     }
  882.     
  883.     /* Now we add the sucker to the list */
  884.     state = 0; /* Have not yet done the insertion */
  885.     for(idx=-1; idx < max_prints -1; idx++) {
  886.       if (state == 1) {
  887.         /* Push tmp_acc and tmp_FP onto the next idx */
  888.         tmp_acc2 = FPR->accuracy[idx+1];
  889.         tmp_FP2 = FPR->prints[idx+1];
  890.         
  891.         FPR->accuracy[idx+1] = tmp_acc;
  892.         FPR->prints[idx+1] = tmp_FP;
  893.         
  894.         tmp_acc = tmp_acc2;
  895.         tmp_FP = tmp_FP2;
  896.       } else if (FPR->accuracy[idx + 1] < acc) {
  897.         /* OK, I insert the sucker into the next slot ... */
  898.         tmp_acc = FPR->accuracy[idx+1];
  899.         tmp_FP = FPR->prints[idx+1];
  900.         FPR->prints[idx+1] = current_os;
  901.         FPR->accuracy[idx+1] = acc;
  902.         state = 1;
  903.       }
  904.     }
  905.     if (state != 1) {
  906.       fatal("Bogus list insertion state (%d) -- num_matches = %d num_perfect_matches=%d entrance_requirement=%f", state, FPR->num_matches, FPR->num_perfect_matches, FPR_entrance_requirement);
  907.     }
  908.     FPR->num_matches++;
  909.     /* If we are over max_prints, one was shoved off list */
  910.     if (FPR->num_matches > max_prints) FPR->num_matches = max_prints;
  911.  
  912.     /* Calculate the new min req. */
  913.     if (FPR->num_matches == max_prints) {
  914.       FPR_entrance_requirement = FPR->accuracy[max_prints - 1] + 0.00001;
  915.     }
  916.       }
  917.     }
  918.   }
  919.  
  920.   if (FPR->num_matches == 0 && FPR->overall_results == OSSCAN_SUCCESS)
  921.     FPR->overall_results = OSSCAN_NOMATCHES;
  922.  
  923.   return;
  924. }
  925.  
  926. struct AVal *gettestbyname(FingerPrint *FP, const char *name) {
  927.  
  928.   if (!FP) return NULL;
  929.   do {
  930.     if (!strcmp(FP->name, name))
  931.       return FP->results;
  932.     FP = FP->next;
  933.   } while(FP);
  934.   return NULL;
  935. }
  936.  
  937. struct AVal *getattrbyname(struct AVal *AV, const char *name) {
  938.  
  939.   if (!AV) return NULL;
  940.   do {
  941.     if (!strcmp(AV->attribute, name))
  942.       return AV;
  943.     AV = AV->next;
  944.   } while(AV);
  945.   return NULL;
  946. }
  947.  
  948.  
  949. /* Returns true if perfect match -- if num_subtests &
  950.    num_subtests_succeeded are non_null it ADDS THE NEW VALUES to what
  951.    is already there.  So initialize them to zero first if you only
  952.    want to see the results from this match.  if shortcircuit is zero,
  953.    it does all the tests, otherwise it returns when the first one
  954.    fails */
  955.  
  956. int AVal_match(struct AVal *reference, struct AVal *fprint, unsigned long *num_subtests, unsigned long *num_subtests_succeeded, int shortcut) {
  957.   struct AVal *current_ref;
  958.   struct AVal *current_fp;
  959.   unsigned int number;
  960.   unsigned int val;
  961.   char *p, *q;  /* OHHHH YEEEAAAAAHHHH!#!@#$!% */
  962.   char valcpy[512];
  963.   char *endptr;
  964.   int andexp, orexp, expchar, numtrue;
  965.   int testfailed;
  966.   int subtests = 0, subtests_succeeded=0;
  967.  
  968.   for(current_ref = reference; current_ref; current_ref = current_ref->next) {
  969.     current_fp = getattrbyname(fprint, current_ref->attribute);    
  970.     if (!current_fp) continue;
  971.     /* OK, we compare an attribute value in  current_fp->value to a 
  972.        potentially large expression in current_ref->value.  The syntax uses
  973.        < (less than), > (greather than), + (non-zero), | (or), and & (and) 
  974.        No parenthesis are allowed and an expression cannot have | AND & */
  975.     numtrue = andexp = orexp = 0; testfailed = 0;
  976.     Strncpy(valcpy, current_ref->value, sizeof(valcpy));
  977.     p = valcpy;
  978.     if (strchr(current_ref->value, '|')) {
  979.       orexp = 1; expchar = '|';
  980.     } else {
  981.       andexp = 1; expchar = '&';
  982.     }
  983.     do {
  984.       q = strchr(p, expchar);
  985.       if (q) *q = '\0';
  986.       if (strcmp(p, "+") == 0) {
  987.     if (!*current_fp->value) { if (andexp) { testfailed=1; break; } }
  988.     else {
  989.       val = strtol(current_fp->value, &endptr, 16);
  990.       if (val == 0 || *endptr) { if (andexp) { testfailed=1; break; } }
  991.       else { numtrue++; if (orexp) break; }
  992.     }
  993.       } else if (*p == '<' && isxdigit((int) p[1])) {
  994.     if (!*current_fp->value) { if (andexp) { testfailed=1; break; } }
  995.     number = strtol(p + 1, &endptr, 16);
  996.     val = strtol(current_fp->value, &endptr, 16);
  997.     if (val >= number || *endptr) { if (andexp)  { testfailed=1; break; } }
  998.     else { numtrue++; if (orexp) break; }
  999.       } else if (*p == '>' && isxdigit((int) p[1])) {
  1000.     if (!*current_fp->value) { if (andexp) { testfailed=1; break; } }
  1001.     number = strtol(p + 1, &endptr, 16);
  1002.     val = strtol(current_fp->value, &endptr, 16);
  1003.     if (val <= number || *endptr) { if (andexp) { testfailed=1; break; } }
  1004.     else { numtrue++; if (orexp) break; }
  1005.       }
  1006.       else {
  1007.     if (strcmp(p, current_fp->value))
  1008.       { if (andexp) { testfailed=1; break; } }
  1009.     else { numtrue++; if (orexp) break; }
  1010.       }
  1011.       if (q) p = q + 1;
  1012.     } while(q);
  1013.       if (numtrue == 0) testfailed=1;
  1014.       subtests++;
  1015.       if (testfailed) {
  1016.     if (shortcut) {
  1017.       if (num_subtests) *num_subtests += subtests;
  1018.       return 0;
  1019.     }
  1020.       } else subtests_succeeded++;
  1021.       /* Whew, we made it past one Attribute alive , on to the next! */
  1022.   }
  1023.   if (num_subtests) *num_subtests += subtests;
  1024.   if (num_subtests_succeeded) *num_subtests_succeeded += subtests_succeeded;
  1025.   return (subtests == subtests_succeeded)? 1 : 0;
  1026. }
  1027.  
  1028.  
  1029. void freeFingerPrint(FingerPrint *FP) {
  1030. FingerPrint *currentFP;
  1031. FingerPrint *nextFP;
  1032.  
  1033. if (!FP) return;
  1034.  
  1035.  for(currentFP = FP; currentFP; currentFP = nextFP) {
  1036.    nextFP = currentFP->next;
  1037.    if (currentFP->results)
  1038.      free(currentFP->results);
  1039.    free(currentFP);
  1040.  }
  1041. return;
  1042. }
  1043.  
  1044.  
  1045. int os_scan(struct hoststruct *target) {
  1046. struct FingerPrintResults FP_matches[3];
  1047. struct seq_info si[3];
  1048. int itry;
  1049. int i;
  1050. struct timeval now;
  1051. double bestacc;
  1052. int bestaccidx;
  1053.  
  1054.  if (target->timedout)
  1055.    return 1;
  1056.  
  1057.  bzero(FP_matches, sizeof(FP_matches));
  1058.  
  1059.  bzero(si, sizeof(si));
  1060.  if (target->ports.state_counts_tcp[PORT_OPEN] == 0 ||
  1061.      (target->ports.state_counts_tcp[PORT_CLOSED] == 0 &&
  1062.       target->ports.state_counts_tcp[PORT_UNFIREWALLED] == 0)) {
  1063.    if (o.osscan_limit) {
  1064.      if (o.verbose)
  1065.        log_write(LOG_STDOUT|LOG_NORMAL|LOG_SKID, "Skipping OS Scan due to absence of open (or perhaps closed) ports\n", target->host);
  1066.      return 1;
  1067.    } else {   
  1068.      log_write(LOG_STDOUT|LOG_NORMAL|LOG_SKID,"Warning:  OS detection will be MUCH less reliable because we did not find at least 1 open and 1 closed TCP port\n");
  1069.    }
  1070.  }
  1071.  
  1072.  for(itry=0; itry < 3; itry++) {
  1073.    if (o.host_timeout) {   
  1074.      gettimeofday(&now, NULL);
  1075.      if (target->timedout || TIMEVAL_MSEC_SUBTRACT(now, target->host_timeout) >= 0)
  1076.        {
  1077.      target->timedout = 1;
  1078.      return 1;
  1079.        }
  1080.    }
  1081.    target->FPs[itry] = get_fingerprint(target, &si[itry]); 
  1082.    if (target->timedout)
  1083.      return 1;
  1084.    match_fingerprint(target->FPs[itry], &FP_matches[itry], 
  1085.              OSSCAN_GUESS_THRESHOLD);
  1086.    if (FP_matches[itry].overall_results == OSSCAN_SUCCESS && 
  1087.        FP_matches[itry].num_perfect_matches > 0)
  1088.      break;
  1089.    if (itry < 2)
  1090.      sleep(2);
  1091.  }
  1092.  
  1093.  target->numFPs = (itry == 3)? 3 : itry + 1;
  1094.  memcpy(&(target->seq), &si[target->numFPs - 1], sizeof(struct seq_info));
  1095.  
  1096.  /* Now lets find the best match */
  1097.  bestacc = 0;
  1098.  bestaccidx = 0;
  1099.  for(itry=0; itry < target->numFPs; itry++) {
  1100.    if (FP_matches[itry].overall_results == OSSCAN_SUCCESS &&
  1101.        FP_matches[itry].num_matches > 0 &&
  1102.        FP_matches[itry].accuracy[0] > bestacc) {
  1103.      bestacc = FP_matches[itry].accuracy[0];
  1104.      bestaccidx = itry;
  1105.      if (FP_matches[itry].num_perfect_matches)
  1106.        break;
  1107.    }
  1108.  }
  1109.  
  1110.  memcpy(&(target->FPR), FP_matches + bestaccidx, sizeof(target->FPR));
  1111.  
  1112.  for(i=0; i < target->numFPs; i++) {
  1113.    if (i == bestaccidx)
  1114.      continue;
  1115.    if (o.debugging) {
  1116.      error("Failed exact match #%d (0-based):\n%s", i, fp2ascii(target->FPs[i]));
  1117.    }
  1118.  }
  1119.  
  1120.  if (target->numFPs > 1 && target->FPR.overall_results == OSSCAN_SUCCESS &&
  1121.      target->FPR.accuracy[0] == 1.0) {
  1122. if (o.verbose) error("WARNING:  OS didn't match until the try #%d", target->numFPs);
  1123.  } 
  1124.  
  1125.  target->goodFP = bestaccidx;
  1126.  
  1127.  return 1;
  1128. }
  1129.  
  1130. /* Writes an informational "Test" result suitable for including at the
  1131.    top of a fingerprint.  Gives info which might be useful when the
  1132.    FPrint is submitted (eg Nmap version, etc).  Result is written (up
  1133.    to ostrlen) to the ostr var passed in */
  1134. void WriteSInfo(char *ostr, int ostrlen, int openport, int closedport) {
  1135.   struct tm *ltime;
  1136.   time_t timep;
  1137.   
  1138.   timep = time(NULL);
  1139.   ltime = localtime(&timep);
  1140.  
  1141.   snprintf(ostr, ostrlen, "SInfo(V=%s%%P=%s%%D=%d/%d%%Time=%X%%O=%d%%C=%d)\n", 
  1142.        NMAP_VERSION, NMAP_PLATFORM, ltime->tm_mon + 1, ltime->tm_mday, 
  1143.        (int) timep, openport, closedport);
  1144. }
  1145.  
  1146. char *mergeFPs(FingerPrint *FPs[], int numFPs, int openport, int closedport) {
  1147. static char str[10240];
  1148. struct AVal *AV;
  1149. FingerPrint *currentFPs[32];
  1150. char *p = str;
  1151. int i;
  1152. int changed;
  1153.  
  1154. if (numFPs <=0) return "(None)";
  1155. if (numFPs > 32) return "(Too many)";
  1156.   
  1157. bzero(str, sizeof(str));
  1158. for(i=0; i < numFPs; i++) {
  1159.   if (FPs[i] == NULL) {
  1160.     fatal("mergeFPs was handed a pointer to null fingerprint");
  1161.   }
  1162.   currentFPs[i] = FPs[i];
  1163. }
  1164.  
  1165. /* Lets start by writing the fake "Info" test for submitting fingerprints */
  1166.  WriteSInfo(str, sizeof(str), openport, closedport); 
  1167.  p = p + strlen(str);
  1168.  
  1169. do {
  1170.   changed = 0;
  1171.   for(i = 0; i < numFPs; i++) {
  1172.     if (currentFPs[i]) {
  1173.       /* This junk means do not print this one if the next
  1174.      one is the same */
  1175.       if (i == numFPs - 1 || !currentFPs[i+1] ||
  1176.       strcmp(currentFPs[i]->name, currentFPs[i+1]->name) != 0 ||
  1177.       AVal_match(currentFPs[i]->results,currentFPs[i+1]->results, NULL,
  1178.              NULL, 1) ==0)
  1179.     {
  1180.       changed = 1;
  1181.       strcpy(p, currentFPs[i]->name);
  1182.       p += strlen(currentFPs[i]->name);
  1183.       *p++='(';
  1184.       for(AV = currentFPs[i]->results; AV; AV = AV->next) {
  1185.         strcpy(p, AV->attribute);
  1186.         p += strlen(AV->attribute);
  1187.         *p++='=';
  1188.         strcpy(p, AV->value);
  1189.         p += strlen(AV->value);
  1190.         *p++ = '%';
  1191.       }
  1192.       if(*(p-1) != '(')
  1193.         p--; /* Kill the final & */
  1194.       *p++ = ')';
  1195.       *p++ = '\n';
  1196.     }
  1197.       /* Now prepare for the next one */
  1198.       currentFPs[i] = currentFPs[i]->next;
  1199.     }
  1200.   }
  1201. } while(changed);
  1202.  
  1203. *p = '\0';
  1204. return str;
  1205. }
  1206.  
  1207.  
  1208. char *fp2ascii(FingerPrint *FP) {
  1209. static char str[2048];
  1210. FingerPrint *current;
  1211. struct AVal *AV;
  1212. char *p = str;
  1213. int len;
  1214. bzero(str, sizeof(str));
  1215.  
  1216. if (!FP) return "(None)";
  1217.  
  1218. if(*(FP->OS_name)) {
  1219.   len = snprintf(str, 128, "FingerPrint  %s\n", FP->OS_name);
  1220.   if (len < 0) fatal("OS name too long");
  1221.   p += len;
  1222. }
  1223.  
  1224. for(current = FP; current ; current = current->next) {
  1225.   Strncpy(p, current->name, sizeof(str) - (p-str));
  1226.   p += strlen(p);
  1227.   assert(p-str < sizeof(str) - 30);
  1228.   *p++='(';
  1229.   for(AV = current->results; AV; AV = AV->next) {
  1230.     Strncpy(p, AV->attribute, sizeof(str) - (p-str));
  1231.     p += strlen(p);
  1232.     assert(p-str < sizeof(str) - 30);
  1233.     *p++='=';
  1234.     Strncpy(p, AV->value, sizeof(str) - (p-str));
  1235.     p += strlen(p);
  1236.     assert(p-str < sizeof(str) - 30);
  1237.     *p++ = '%';
  1238.   }
  1239.   if(*(p-1) != '(')
  1240.     p--; /* Kill the final & */
  1241.   *p++ = ')';
  1242.   *p++ = '\n';
  1243. }
  1244. *p = '\0';
  1245. return str;
  1246. }
  1247.  
  1248. FingerPrint **parse_fingerprint_reference_file() {
  1249. FingerPrint **FPs;
  1250. FingerPrint *current;
  1251. FILE *fp;
  1252. char filename[256];
  1253. char line[512];
  1254. int numrecords = 0;
  1255. int lineno = 0;
  1256. char *p, *q; /* OH YEAH!!!! */
  1257.  
  1258. /* If you need more than 2048 fingerprints, tough */
  1259.  FPs = (FingerPrint **) safe_malloc(sizeof(FingerPrint *) * 2048); 
  1260.  bzero(FPs, sizeof(FingerPrint *) * 2048);
  1261.  
  1262. if (nmap_fetchfile(filename, sizeof(filename), "nmap-os-fingerprints") == -1){
  1263.   fatal("OS scan requested but I cannot find nmap-os-fingerprints file.  It should be in %s, ~/.nmap/ or .", NMAPDATADIR);
  1264. }
  1265.  
  1266. fp = fopen(filename, "r");
  1267.  
  1268.  top:
  1269. while(fgets(line, sizeof(line), fp)) {  
  1270.   lineno++;
  1271.   /* Read in a record */
  1272.   if (*line == '\n' || *line == '#')
  1273.     continue;
  1274.  
  1275.  fparse:
  1276.  
  1277.   if (strncasecmp(line, "FingerPrint", 11)) {
  1278.     fprintf(stderr, "Parse error on line %d of nmap-os-fingerprints file: %s\n", lineno, line);
  1279.     continue;
  1280.   }
  1281.   p = line + 12;
  1282.   while(*p && isspace((int) *p)) p++;
  1283.   if (!*p) {
  1284.     fprintf(stderr, "Parse error on line %d of nmap-os-fingerprints file: %s\n", lineno, line);    
  1285.     continue;
  1286.   }
  1287.   FPs[numrecords] = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  1288.   bzero(FPs[numrecords], sizeof(FingerPrint));
  1289.   q = FPs[numrecords]->OS_name;
  1290.   while(*p && *p != '\n' && *p != '#') {
  1291.     if (q - FPs[numrecords]->OS_name >= (sizeof(FPs[numrecords]->OS_name) -2))
  1292.       fatal("Ack!  0v3rf0w r3ad|ng fIng3rpRint FiLE!");
  1293.     *q++ = *p++;
  1294.   }
  1295.  
  1296.   q--;
  1297.  
  1298.   /* Now let us back up through any ending spaces */
  1299.   while(isspace((int)*q)) 
  1300.     q--;
  1301.  
  1302.   /* Terminate the sucker */
  1303.   q++; 
  1304.   *q = '\0';
  1305.  
  1306.   current = FPs[numrecords];
  1307.   /* Now we read the fingerprint itself */
  1308.   while(fgets(line, sizeof(line), fp)) {
  1309.     lineno++;
  1310.     if (*line == '#')
  1311.       continue;
  1312.     if (*line == '\n')
  1313.       break;
  1314.     if (!strncmp(line, "FingerPrint",11)) {
  1315.       goto fparse;
  1316.     }
  1317.     p = line;
  1318.     q = strchr(line, '(');
  1319.     if (!q) {
  1320.       fprintf(stderr, "Parse error on line %d of nmap-os-fingerprints file: %s\n", lineno, line);
  1321.       goto top;
  1322.     }
  1323.     *q = '\0';
  1324.     if(current->name) {
  1325.       current->next = (FingerPrint *) safe_malloc(sizeof(FingerPrint));
  1326.       current = current->next;
  1327.       bzero(current, sizeof(FingerPrint));
  1328.     }
  1329.     current->name = strdup(p);
  1330.     p = q+1;
  1331.     *q = '(';
  1332.     q = strchr(p, ')');
  1333.     if (!q) {
  1334.       fprintf(stderr, "Parse error on line %d of nmap-os-fingerprints file: %s\n", lineno, line);
  1335.       goto top;
  1336.     }
  1337.     *q = '\0';
  1338.     current->results = str2AVal(p);
  1339.   }
  1340.   /* printf("Read in fingerprint:\n%s\n", fp2ascii(FPs[numrecords])); */
  1341.   numrecords++;
  1342. }
  1343. fclose(fp);
  1344. FPs[numrecords] = NULL; 
  1345. return FPs;
  1346. }
  1347.  
  1348. struct AVal *str2AVal(char *str) {
  1349. int i = 1;
  1350. int count = 1;
  1351. char *q = str, *p=str;
  1352. struct AVal *AVs;
  1353. if (!*str) return NULL;
  1354.  
  1355. /* count the AVals */
  1356. while((q = strchr(q, '%'))) {
  1357.   count++;
  1358.   q++;
  1359. }
  1360.  
  1361. AVs = (struct AVal *) safe_malloc(count * sizeof(struct AVal));
  1362. bzero(AVs, sizeof(struct AVal) * count);
  1363. for(i=0; i < count; i++) {
  1364.   q = strchr(p, '=');
  1365.   if (!q) {
  1366.     fatal("Parse error with AVal string (%s) in nmap-os-fingerprints file", str);
  1367.   }
  1368.   *q = '\0';
  1369.   AVs[i].attribute = strdup(p);
  1370.   p = q+1;
  1371.   if (i != count - 1) {
  1372.     q = strchr(p, '%');
  1373.     if (!q) {
  1374.       fatal("Parse error with AVal string (%s) in nmap-os-fingerprints file", str);
  1375.     }
  1376.     *q = '\0';
  1377.     AVs[i].next = &AVs[i+1];
  1378.   }
  1379.   Strncpy(AVs[i].value, p, sizeof(AVs[i].value)); 
  1380.   p = q + 1;
  1381. }
  1382. return AVs;
  1383. }
  1384.  
  1385.  
  1386. struct udpprobeinfo *send_closedudp_probe(int sd, struct in_addr *victim,
  1387.                       u16 sport, u16 dport) {
  1388.  
  1389. static struct udpprobeinfo upi;
  1390. static int myttl = 0;
  1391. static u8 patternbyte = 0;
  1392. static u16 id = 0; 
  1393. u8 packet[328]; /* 20 IP hdr + 8 UDP hdr + 300 data */
  1394. struct ip *ip = (struct ip *) packet;
  1395. udphdr_bsd *udp = (udphdr_bsd *) (packet + sizeof(struct ip));
  1396. struct in_addr *source;
  1397. int datalen = 300;
  1398. unsigned char *data = packet + 28;
  1399. unsigned short realcheck; /* the REAL checksum */
  1400. int res;
  1401. struct sockaddr_in sock;
  1402. int decoy;
  1403. struct pseudo_udp_hdr {
  1404.   struct in_addr source;
  1405.   struct in_addr dest;        
  1406.   u8 zero;
  1407.   u8 proto;        
  1408.   u16 length;
  1409. } *pseudo = (struct pseudo_udp_hdr *) ((char *)udp - 12) ;
  1410.  
  1411. if (!patternbyte) patternbyte = (get_random_uint() % 60) + 65;
  1412. memset(data, patternbyte, datalen);
  1413.  
  1414. while(!id) id = get_random_uint();
  1415.  
  1416. /* check that required fields are there and not too silly */
  1417. if ( !victim || !sport || !dport || sd < 0) {
  1418.   fprintf(stderr, "send_udp_raw: One or more of your parameters suck!\n");
  1419.   return NULL;
  1420. }
  1421.  
  1422. if (!myttl)  myttl = (time(NULL) % 14) + 51;
  1423. /* It was a tough decision whether to do this here for every packet
  1424.    or let the calling function deal with it.  In the end I grudgingly decided
  1425.    to do it here and potentially waste a couple microseconds... */
  1426. sethdrinclude(sd); 
  1427.  
  1428.  for(decoy=0; decoy < o.numdecoys; decoy++) {
  1429.    source = &o.decoys[decoy];
  1430.  
  1431.    /*do we even have to fill out this damn thing?  This is a raw packet, 
  1432.      after all */
  1433.    sock.sin_family = AF_INET;
  1434.    sock.sin_port = htons(dport);
  1435.    sock.sin_addr.s_addr = victim->s_addr;
  1436.  
  1437.  
  1438.    bzero((char *) packet, sizeof(struct ip) + sizeof(udphdr_bsd));
  1439.  
  1440.    udp->uh_sport = htons(sport);
  1441.    udp->uh_dport = htons(dport);
  1442.    udp->uh_ulen = htons(8 + datalen);
  1443.  
  1444.    /* Now the psuedo header for checksuming */
  1445.    pseudo->source.s_addr = source->s_addr;
  1446.    pseudo->dest.s_addr = victim->s_addr;
  1447.    pseudo->proto = IPPROTO_UDP;
  1448.    pseudo->length = htons(sizeof(udphdr_bsd) + datalen);
  1449.  
  1450.    /* OK, now we should be able to compute a valid checksum */
  1451. realcheck = in_cksum((unsigned short *)pseudo, 20 /* pseudo + UDP headers */ +
  1452.  datalen);
  1453. #if STUPID_SOLARIS_CHECKSUM_BUG
  1454.  udp->uh_sum = sizeof(struct udphdr) + datalen;
  1455. #else
  1456. udp->uh_sum = realcheck;
  1457. #endif
  1458.  
  1459.    /* Goodbye, pseudo header! */
  1460.    bzero(pseudo, 12);
  1461.  
  1462.    /* Now for the ip header */
  1463.    ip->ip_v = 4;
  1464.    ip->ip_hl = 5;
  1465.    ip->ip_len = BSDFIX(sizeof(struct ip) + sizeof(udphdr_bsd) + datalen);
  1466.    ip->ip_id = id;
  1467.    ip->ip_ttl = myttl;
  1468.    ip->ip_p = IPPROTO_UDP;
  1469.    ip->ip_src.s_addr = source->s_addr;
  1470.    ip->ip_dst.s_addr= victim->s_addr;
  1471.  
  1472.    upi.ipck = in_cksum((unsigned short *)ip, sizeof(struct ip));
  1473. #if HAVE_IP_IP_SUM
  1474.    ip->ip_sum = upi.ipck;
  1475. #endif
  1476.  
  1477.    /* OK, now if this is the real she-bang (ie not a decoy) then
  1478.       we stick all the inph0 in our upi */
  1479.    if (decoy == o.decoyturn) {   
  1480.      upi.iptl = 28 + datalen;
  1481.      upi.ipid = id;
  1482.      upi.sport = sport;
  1483.      upi.dport = dport;
  1484.      upi.udpck = realcheck;
  1485.      upi.udplen = 8 + datalen;
  1486.      upi.patternbyte = patternbyte;
  1487.      upi.target.s_addr = ip->ip_dst.s_addr;
  1488.    }
  1489.    if (TCPIP_DEBUGGING > 1) {
  1490.      log_write(LOG_STDOUT, "Raw UDP packet creation completed!  Here it is:\n");
  1491.      readudppacket(packet,1);
  1492.    }
  1493.    if (TCPIP_DEBUGGING > 1)     
  1494.      log_write(LOG_STDOUT, "\nTrying sendto(%d , packet, %d, 0 , %s , %d)\n",
  1495.         sd, BSDUFIX(ip->ip_len), inet_ntoa(*victim),
  1496.         (int) sizeof(struct sockaddr_in));
  1497.  
  1498.    if ((res = sendto(sd, (const char *) packet, BSDUFIX(ip->ip_len), 0,
  1499.              (struct sockaddr *)&sock, (int) sizeof(struct sockaddr_in))) == -1)
  1500.      {
  1501.        perror("sendto in send_udp_raw_decoys");
  1502.        return NULL;
  1503.      }
  1504.  
  1505.    if (TCPIP_DEBUGGING > 1) log_write(LOG_STDOUT, "successfully sent %d bytes of raw_tcp!\n", res);
  1506.  }
  1507.  
  1508. return &upi;
  1509.  
  1510. }
  1511.  
  1512. struct AVal *fingerprint_portunreach(struct ip *ip, struct udpprobeinfo *upi) {
  1513. struct icmp *icmp;
  1514. struct ip *ip2;
  1515. int numtests = 10;
  1516. unsigned short checksum;
  1517. unsigned short *checksumptr;
  1518. udphdr_bsd *udp;
  1519. struct AVal *AVs;
  1520. int i;
  1521. int current_testno = 0;
  1522. unsigned char *datastart, *dataend;
  1523.  
  1524. /* The very first thing we do is make sure this is the correct
  1525.    response */
  1526. if (ip->ip_p != IPPROTO_ICMP) {
  1527.   error("fingerprint_portunreach handed a non-ICMP packet!");
  1528.   return NULL;
  1529. }
  1530.  
  1531. if (ip->ip_src.s_addr != upi->target.s_addr)
  1532.   return NULL;  /* Not the person we sent to */
  1533.  
  1534. icmp = ((struct icmp *)  (((char *) ip) + 4 * ip->ip_hl));
  1535. if (icmp->icmp_type != 3 || icmp->icmp_code != 3)
  1536.   return NULL; /* Not a port unreachable */
  1537.  
  1538. ip2 = (struct ip*) ((char *)icmp + 8);
  1539. udp = (udphdr_bsd *) ((char *)ip2 + 20);
  1540.  
  1541. /* The ports better match as well ... */
  1542. if (ntohs(udp->uh_sport) != upi->sport || ntohs(udp->uh_dport) != upi->dport) {
  1543.   return NULL;
  1544. }
  1545.  
  1546. /* Create the Avals */
  1547. AVs = (struct AVal *) safe_malloc(numtests * sizeof(struct AVal));
  1548. bzero(AVs, numtests * sizeof(struct AVal));
  1549.  
  1550. /* Link them together */
  1551. for(i=0; i < numtests - 1; i++)
  1552.   AVs[i].next = &AVs[i+1];
  1553.  
  1554. /* First of all, if we got this far the response was yes */
  1555. AVs[current_testno].attribute = "Resp";
  1556. strcpy(AVs[current_testno].value, "Y");
  1557.  
  1558. current_testno++;
  1559.  
  1560. /* Now let us do an easy one, Don't fragment */
  1561. AVs[current_testno].attribute = "DF";
  1562.   if(ntohs(ip->ip_off) & 0x4000) {
  1563.     strcpy(AVs[current_testno].value,"Y");
  1564.   } else strcpy(AVs[current_testno].value, "N");
  1565.  
  1566. current_testno++;
  1567.  
  1568. /* Now lets do TOS of the response (note, I've never seen this be
  1569.    useful */
  1570. AVs[current_testno].attribute = "TOS";
  1571. sprintf(AVs[current_testno].value, "%hX", ip->ip_tos);
  1572.  
  1573. current_testno++;
  1574.  
  1575. /* Now we look at the IP datagram length that was returned, some
  1576.    machines send more of the original packet back than others */
  1577. AVs[current_testno].attribute = "IPLEN";
  1578. sprintf(AVs[current_testno].value, "%hX", ntohs(ip->ip_len));
  1579.  
  1580. current_testno++;
  1581.  
  1582. /* OK, lets check the returned IP length, some systems @$@ this
  1583.    up */
  1584. AVs[current_testno].attribute = "RIPTL";
  1585. sprintf(AVs[current_testno].value, "%hX", ntohs(ip2->ip_len));
  1586.  
  1587. current_testno++;
  1588.  
  1589. /* This next test doesn't work on Solaris because the lamers
  1590.    overwrite our ip_id */
  1591. #if !defined(SOLARIS) && !defined(SUNOS) && !defined(IRIX)
  1592.  
  1593. #ifdef WIN32
  1594. if(!winip_corruption_possible()) {
  1595. #endif
  1596.  
  1597. /* Now lets see how they treated the ID we sent ... */
  1598. AVs[current_testno].attribute = "RID";
  1599. if (ntohs(ip2->ip_id) == 0)
  1600.   strcpy(AVs[current_testno].value, "0");
  1601. else if (ip2->ip_id == upi->ipid)
  1602.   strcpy(AVs[current_testno].value, "E"); /* The "expected" value */
  1603. else strcpy(AVs[current_testno].value, "F"); /* They fucked it up */
  1604.  
  1605. current_testno++;
  1606.  
  1607. #ifdef WIN32
  1608. }
  1609. #endif
  1610.  
  1611. #endif
  1612.  
  1613. /* Let us see if the IP checksum we got back computes */
  1614.  
  1615. AVs[current_testno].attribute = "RIPCK";
  1616. /* Thanks to some machines not having struct ip member ip_sum we
  1617.    have to go with this BS */
  1618. checksumptr = (unsigned short *)   ((char *) ip2 + 10);
  1619. checksum =   *checksumptr;
  1620.  
  1621. if (checksum == 0)
  1622.   strcpy(AVs[current_testno].value, "0");
  1623. else {
  1624.   *checksumptr = 0;
  1625.   if (in_cksum((unsigned short *)ip2, 20) == checksum) {
  1626.     strcpy(AVs[current_testno].value, "E"); /* The "expected" value */
  1627.   } else {
  1628.     strcpy(AVs[current_testno].value, "F"); /* They fucked it up */
  1629.   }
  1630.   *checksumptr = checksum;
  1631. }
  1632.  
  1633. current_testno++;
  1634.  
  1635. /* UDP checksum */
  1636. AVs[current_testno].attribute = "UCK";
  1637. if (udp->uh_sum == 0)
  1638.   strcpy(AVs[current_testno].value, "0");
  1639. else if (udp->uh_sum == upi->udpck)
  1640.   strcpy(AVs[current_testno].value, "E"); /* The "expected" value */
  1641. else strcpy(AVs[current_testno].value, "F"); /* They fucked it up */
  1642.  
  1643. current_testno++;
  1644.  
  1645. /* UDP length ... */
  1646. AVs[current_testno].attribute = "ULEN";
  1647. sprintf(AVs[current_testno].value, "%hX", ntohs(udp->uh_ulen));
  1648.  
  1649. current_testno++;
  1650.  
  1651. /* Finally we ensure the data is OK */
  1652. datastart = ((unsigned char *)udp) + 8;
  1653. dataend = (unsigned char *)  ip + ntohs(ip->ip_len);
  1654.  
  1655. while(datastart < dataend) {
  1656.   if (*datastart != upi->patternbyte) break;
  1657.   datastart++;
  1658. }
  1659. AVs[current_testno].attribute = "DAT";
  1660. if (datastart < dataend)
  1661.   strcpy(AVs[current_testno].value, "F"); /* They fucked it up */
  1662. else  
  1663.   strcpy(AVs[current_testno].value, "E");
  1664.  
  1665. AVs[current_testno].next = NULL;
  1666.  
  1667. return AVs;
  1668. }
  1669.  
  1670. /* This function takes an array of "numSamples" IP IDs and analyzes
  1671.  them to determine their sequenceability classification.  It returns
  1672.  one of the IPID_SEQ_* classifications defined in nmap.h .  If the
  1673.  function cannot determine the sequence, IPID_SEQ_UNKNOWN is returned.
  1674.  This islocalhost argument is a boolean specifying whether these
  1675.  numbers were generated by scanning localhost.  NOTE: the "ipids" argument
  1676.  may be modified if localhost is set to true. */
  1677.  
  1678. int ipid_sequence(int numSamples, u16 *ipids, int islocalhost) {
  1679.   u16 ipid_diffs[32];
  1680.   int i;
  1681.   int allipideqz = 1; /* Flag that means "All IP.IDs returned during
  1682.                  sequencing are zero.  This is unset if we
  1683.                  find a nonzero */
  1684.   int j,k;
  1685.  
  1686.   assert(numSamples < (sizeof(ipid_diffs) / 2));
  1687.   if (numSamples < 2) return IPID_SEQ_UNKNOWN;
  1688.  
  1689.   for(i = 1; i < numSamples; i++) {
  1690.  
  1691.     if (ipids[i-1] != 0 || ipids[i] != 0) 
  1692.       allipideqz = 0; /* All IP.ID values do *NOT* equal zero */
  1693.  
  1694.     ipid_diffs[i-1] = MOD_DIFF_USHORT(ipids[i], ipids[i-1]);
  1695.     if ((ipids[i] < ipids[i-1]) && (ipids[i] > 500 || ipids[i-1] < 65000))
  1696.       return IPID_SEQ_RD;
  1697.   }
  1698.  
  1699.   if (allipideqz) return IPID_SEQ_ZERO;
  1700.  
  1701.   /* Battle plan ... 
  1702.      ipid_diffs-- if scanning localhost and safe
  1703.      If any diff is > 1000, set to random, if 0, set to constant
  1704.      If any of the diffs are 1, or all are less than 9, set to incremental 
  1705.   */
  1706.   
  1707.   if (islocalhost) {
  1708.     int allgto = 1; /* ALL diffs greater than one */
  1709.     
  1710.     for(i=0; i < numSamples - 1; i++)
  1711.       if (ipid_diffs[i] < 2) {
  1712.     allgto = 0; break;
  1713.       }
  1714.     if (allgto) {
  1715.       for(i=0; i < numSamples - 1; i++) {
  1716.     if (ipid_diffs[i] % 256 == 0) /* Stupid MS */
  1717.       ipid_diffs[i] -= 256;
  1718.     else
  1719.       ipid_diffs[i]--; /* Because on localhost the RST sent back ues an IPID */
  1720.       }
  1721.     }
  1722.   }
  1723.  
  1724.   for(i=0; i < numSamples - 1; i++) {
  1725.     if (ipid_diffs[i] > 1000) {
  1726.       return IPID_SEQ_RPI;
  1727.       break;
  1728.     }
  1729.     if (ipid_diffs[i] == 0) {
  1730.       return IPID_SEQ_CONSTANT;
  1731.       break;
  1732.     }
  1733.   }
  1734.  
  1735.   j = 1; /* j is a flag meaning "all differences seen are < 9" */
  1736.   k = 1; /* k is a flag meaning "all difference seen are multiples of 256 */
  1737.   for(i=0; i < numSamples - 1; i++) {
  1738.     if (ipid_diffs[i] == 1) {
  1739.       return IPID_SEQ_INCR;
  1740.     }
  1741.  
  1742.     if (k && ipid_diffs[i] < 2560 && ipid_diffs[i] % 256 != 0) {
  1743.       k = 0;
  1744.     }
  1745.  
  1746.     if (ipid_diffs[i] > 9)
  1747.       j = 0;
  1748.   }
  1749.  
  1750.      if (k == 1) {
  1751.        /* Stupid Microsoft! */
  1752.        return IPID_SEQ_BROKEN_INCR;
  1753.      }
  1754.  
  1755.      if (j == 1)
  1756.        return IPID_SEQ_INCR;
  1757.  
  1758.      return IPID_SEQ_UNKNOWN;
  1759.  
  1760. }
  1761.