home *** CD-ROM | disk | FTP | other *** search
/ Hacks & Cracks / Hacks_and_Cracks.iso / hackersclub / km / library / hack / ss.txt < prev    next >
Text File  |  1998-03-25  |  33KB  |  1,094 lines

  1.                               == Phrack 49 ==
  2.                       Volume Seven, Issue Forty-Nine
  3.                                File 15 of 16
  4.                    --------------------------------------
  5.                               by Uriel Maimon
  6.  
  7. Introduction
  8.  
  9. During the course of time, there has risen a demand to know the services a
  10. certain host offers. The field of portscanning rose to offer a solution to
  11. this need. At first, implementations such as SATAN, connected to each tcp
  12. port using the full three-way-handshake (opening a full tcp connection).
  13. The upside to this method is that the user who is scanning does not need to
  14. custom build the ip packet he is scanning with, because he uses standard
  15. system calls, and does not need root access (generally a uid of 0 is needed
  16. to use SOCK_RAW, /dev/bpf,/dev/nit and so forth) the major down side to
  17. this method is that it is easily detectable and also easily detered, using
  18. any number of methods, most notably the TCP Wrappers made by Wietse Venema.
  19.  
  20. The next step was of course SYN-scanning or 'half open scanning' which
  21. implies that a full tcp connection is never established. The process of
  22. establishing a tcp connection is three phased: the originating party first
  23. sends a TCP packet with the SYN flag on, then the target party sends a TCP
  24. packet with the flags SYN and ACK on if the port is open, or, if the port
  25. is closed, the target party resets the connection with the RST flag. The
  26. third phase of the negotiation is when the originating party sends a final
  27. TCP packet with the ACK flag on (all these packets, of course, have the
  28. corresponding sequence numbers, ack numbers, etc). The connection is now
  29. open. A SYN-scanner only sends the first packet in the three-way-handshake,
  30. the SYN packet, and waits for the SYN|ACK or a RST. When it receives one of
  31. the two it knows whether or not the port is listening. The major advantage
  32. to this method is that it is not detected by normal logs such as "SATAN
  33. detectors" or Wiestse's tcp_wrappers. The main disadvantages are:
  34.  
  35.   1. This method can still be detected by certian loggers that log SYN
  36.      connection attempts ('tcplog' for example), and can still be detected
  37.      by netstat(1).
  38.  
  39.   2. The sender, under most operating systems, needs to custom build the
  40.      entire IP packet for this kind of scanning (I don't know of any
  41.      operating system under which this is not true, if you know of one,
  42.      please let me know). This requires access to SOCK_RAW
  43.      (getprotbyname('raw'); under most systems) or /dev/bpf (Berkeley
  44.      packet filter), /dev/nit (Sun 'Network Interface Tap') etc. This
  45.      usually requires root or privileged group access.
  46.  
  47.   3. A great deal of firewalls who would filter out this scan, will not
  48.      filter out the StealthScan(TM) (all rights reserved to vicious little
  49.      red blow ficiouz deliciouz (kosher) chicken surpass INC PLC LTD).
  50.  
  51. A note about UDP portscanning
  52.  
  53. In this article I will ignore UDP portscanning for the simple reason that
  54. it lacks the complexity of tcp; it is not a connection oriented stream
  55. protocol but rather a connectionless datagram protocol. To scan a UDP port
  56. to see if it is listening, simply send any UDP packet to the port. You will
  57. receive an ICMP 'Destination Port Unreachable' packet if the port is not
  58. listening.
  59.  
  60. To the best of my knowledge this is the only way to scan UDP ports. I will
  61. be glad to be corrected -- if anyone knows of a different method please
  62. E-mail me.
  63.  
  64. The Stealth Scan
  65.  
  66. This method relies on bad net code in the BSD code. Since most of the
  67. networking code in most any operating system today is BSD netcode or a
  68. derivative thereof it works on most systems. (A most obvious exception to
  69. this is Cisco routers... Gosh! GOOD networking code ?!?@$! HERESY! Alan Cox
  70. will have a heart attack when he hears of this!)
  71.  
  72. Disadvantages of this technique:
  73.  
  74.   1. The IP packet must still be custom built. I see no solution for this
  75.      problem, unless some really insecure system calls will be put in. I
  76.      see no real need for this because SLIP/PPP services are so common
  77.      these days, getting super user access on a machine is not a problem
  78.      any more.
  79.  
  80.   2. This method relies on bugs in net code. This can and probably will be
  81.      fixed in the near future. (Shhhhhh. Don't tell Alan Cox. He hates good
  82.      efficient networking code.) OpenBSD, for example, has already fixed
  83.      this bug.
  84.  
  85.   3. The outcome of a scan is never known, and the outcome is not similar
  86.      over different architectures and operating systems. It is not
  87.      reliable.
  88.  
  89. Main advantages of this method over the other methods:
  90.  
  91.   1. Very difficult to log. Even once the method is known, devising a
  92.      logging method without fixing the actual bug itself is problematic.
  93.  
  94.   2. Can circumvent some firewalls.
  95.  
  96.   3. Will not show up on netstat(1).
  97.  
  98.   4. Does not consist of any part of the standard TCP three-way-handshake.
  99.  
  100.   5. Several different methods consisting of the same principle.
  101.  
  102. The actual algorithm:
  103.  
  104. I use TCP packets with the ACK, and FIN flags turned on. I use these simply
  105. because they are packets that should always return RST on an unopened
  106. connection sent to a port. From now on I refer to such packets as 'RST' ,
  107. 'FIN', or 'ACK' packets.
  108.  
  109. method #1:
  110.  
  111. Send a FIN packet. If the destination host returns a RST then the port is
  112. closed, if there is no return RST then the port is listening. The fact that
  113. this method works on so many hosts is a sad testimonial to the state of the
  114. networking code in most operating system kernels.
  115.  
  116. method #2
  117.  
  118. Send an ACK packet. If the returning packets ttl is lower than in the rest
  119. of the RST packets received, or if the window size is greater than zero,
  120. the port is probably listening.
  121.  
  122. (Note on the ttl: This bug is almost understandable. Every function in IP
  123. is a routing function. With every interface change, the packets ttl is
  124. subtracted by one. In the case of an open port, the ttl was decremented
  125. when it was received and examined, but when it was 'noticed' the flag was
  126. not a SYN, a RST was sent, with a ttl one lower then if the port had simply
  127. been closed. This might not be the case. I have not checked this theory
  128. against the BSD networking code. Feel free to correct me.
  129.  
  130. Uriel
  131.  
  132. /*
  133.  * scantcp.c
  134.  *
  135.  * version 1.32
  136.  *
  137.  * Scans for listening TCP ports by sending packets to them and waiting for
  138.  * replies. Relys upon the TCP specs and some TCP implementation bugs found
  139.  * when viewing tcpdump logs.
  140.  *
  141.  * As always, portions recycled (eventually, with some stops) from n00k.c
  142.  * (Wow, that little piece of code I wrote long ago still serves as the base
  143.  *  interface for newer tools)
  144.  *
  145.  * Technique:
  146.  * 1. Active scanning: not supported - why bother.
  147.  *
  148.  * 2. Half-open scanning:
  149.  *      a. send SYN
  150.  *      b. if reply is SYN|ACK send RST, port is listening
  151.  *      c. if reply is RST, port is not listening
  152.  *
  153.  * 3. Stealth scanning: (works on nearly all systems tested)
  154.  *      a. sends FIN
  155.  *      b. if RST is returned, not listening.
  156.  *      c. otherwise, port is probably listening.
  157.  *
  158.  * (This bug in many TCP implementations is not limited to FIN only; in fact
  159.  *  many other flag combinations will have similar effects. FIN alone was
  160.  *  selected because always returns a plain RST when not listening, and the
  161.  *  code here was fit to handle RSTs already so it took me like 2 minutes
  162.  *  to add this scanning method)
  163.  *
  164.  * 4. Stealth scanning: (may not work on all systems)
  165.  *      a. sends ACK
  166.  *      b. waits for RST
  167.  *      c. if TTL is low or window is not 0, port is probably listening.
  168.  *
  169.  * (stealth scanning was created after I watched some tcpdump logs with
  170.  *  these symptoms. The low-TTL implementation bug is currently believed
  171.  *  to appear on Linux only, the non-zero window on ACK seems to exists on
  172.  *  all BSDs.)
  173.  *
  174.  * CHANGES:
  175.  * --------
  176.  * 0. (v1.0)
  177.  *    - First code, worked but was put aside since I didn't have time nor
  178.  *      need to continue developing it.
  179.  * 1. (v1.1)
  180.  *    - BASE CODE MOSTLY REWRITTEN (the old code wasn't that maintainable)
  181.  *    - Added code to actually enforce the usecond-delay without usleep()
  182.  *      (replies might be lost if usleep()ing)
  183.  * 2. (v1.2)
  184.  *    - Added another stealth scanning method (FIN).
  185.  *      Tested and passed on:
  186.  *      AIX 3
  187.  *      AIX 4
  188.  *      IRIX 5.3
  189.  *      SunOS 4.1.3
  190.  *      System V 4.0
  191.  *      Linux
  192.  *      FreeBSD
  193.  *      Solaris
  194.  *
  195.  *      Tested and failed on:
  196.  *      Cisco router with services on ( IOS 11.0)
  197.  *
  198.  * 3. (v1.21)
  199.  *    - Code commented since I intend on abandoning this for a while.
  200.  *
  201.  * 4. (v1.3)
  202.  *    - Resending for ports that weren't replied for.
  203.  *      (took some modifications in the internal structures. this also
  204.  *       makes it possible to use non-linear port ranges
  205.  *       (say 1-1024 and 6000))
  206.  *
  207.  * 5. (v1.31)
  208.  *    - Flood detection - will slow up the sending rate if not replies are
  209.  *      recieved for STCP_THRESHOLD consecutive sends. Saves alot of resends
  210.  *      on easily-flooded networks.
  211.  *
  212.  * 6. (v1.32)
  213.  *      - Multiple port ranges support.
  214.  *        The format is: |[,|,...]
  215.  *
  216.  *        Examples: 20-26,113
  217.  *                  20-100,113-150,6000,6660-6669
  218.  *
  219.  * PLANNED: (when I have time for this)
  220.  * ------------------------------------
  221.  * (v2.x) - Multiple flag combination selections, smart algorithm to point
  222.  *          out uncommon replies and cross-check them with another flag
  223.  *
  224.  */
  225.  
  226. #define RESOLVE_QUIET
  227.  
  228. #include <stdio.h>
  229. #include <netinet/in.h>
  230. #include <netinet/ip.h>
  231. #include <netinet/ip_tcp.h>
  232. #include <sys/time.h>
  233. #include <sys/types.h>
  234. #include <sys/socket.h>
  235. #include <unistd.h>
  236. #include <stdlib.h>
  237. #include <string.h>
  238. #include <signal.h>
  239. #include <errno.h>
  240.  
  241. #include "resolve.c"
  242. #include "tcppkt03.c"
  243.  
  244. #define STCP_VERSION "1.32"
  245. #define STCP_PORT  1234                /* Our local port. */
  246. #define STCP_SENDS 3
  247. #define STCP_THRESHOLD 8
  248. #define STCP_SLOWFACTOR 10
  249.  
  250. /* GENERAL ROUTINES ------------------------------------------- */
  251.  
  252. void banner(void)
  253.      {
  254.         printf("\nscantcp\n");
  255.         printf("version %s\n",STCP_VERSION);
  256.      }
  257.  
  258. void usage(const char *progname)
  259.      {
  260.         printf("\nusage: \n");
  261.         printf("%s <method> <source> <dest> <ports> <udelay> <delay> [sf]\n\n",progname);
  262.         printf("\t : 0: half-open scanning (type 0, SYN)\n");
  263.         printf("\t           1: stealth scanning (type 1, FIN)\n");
  264.         printf("\t           2: stealth scanning (type 2, ACK)\n");
  265.         printf("\t<source> : source address (this host)\n");
  266.         printf("\t<dest>   : target to scan\n");
  267.         printf("\t<ports>  : ports/and or ranges to scan - eg: 21-30,113,6000\n");
  268.         printf("\t<udelay> : microseconds to wait between TCP sends\n");
  269.         printf("\t<delay>  : seconds to wait for TCP replies\n");
  270.         printf("\t[sf]     : slow-factor in case sends are dectected to be too fast\n\n");
  271.      }
  272.  
  273. /* OPTION PARSING etc ---------------------------------------- */
  274.  
  275. unsigned char *dest_name;
  276. unsigned char *spoof_name;
  277. struct sockaddr_in destaddr;
  278.  
  279. unsigned long dest_addr;
  280. unsigned long spoof_addr;
  281. unsigned long usecdelay;
  282. unsigned      waitdelay;
  283.  
  284. int slowfactor = STCP_SLOWFACTOR;
  285.  
  286. struct portrec                         /* the port-data structure */
  287. {
  288.    unsigned           n;
  289.    int                state;
  290.    unsigned char      ttl;
  291.    unsigned short int window;
  292.    unsigned long int  seq;
  293.    char               sends;
  294.  
  295. } *ports;
  296.  
  297. char *portstr;
  298.  
  299. unsigned char scanflags;
  300.  
  301. int done;
  302.  
  303. int rawsock;                           /* socket descriptors */
  304. int tcpsock;
  305.  
  306. int lastidx = 0;                       /* last sent index */
  307. int maxports;                          /* total number of ports */
  308.  
  309. void timeout(int signum)               /* timeout handler           */
  310.      {                                 /* this is actually the data */
  311.         int someopen = 0;              /* analyzer function. werd.  */
  312.         unsigned lastsent;
  313.         int checklowttl = 0;
  314.  
  315.         struct portrec *p;
  316.  
  317.         printf("* SCANNING IS OVER\n\n");
  318.         fflush(stdout);
  319.  
  320.         done = 1;
  321.  
  322.  
  323.         for (lastsent = 0;lastsentstate == -1)
  324.                if (p->ttl > 64)
  325.                {
  326.                   checklowttl = 1;
  327.                   break;
  328.                }
  329.           }
  330.  
  331. /* the above loop checks whether there's need to report low-ttl packets */
  332.  
  333.         for (lastsent = 0;lastsentn);
  334.  
  335.              tcpip_send(rawsock,&destaddr,
  336.                         spoof_addr,destaddr.sin_addr.s_addr,
  337.                         STCP_PORT,ntohs(destaddr.sin_port),
  338.                         TH_RST,
  339.                         p->seq++, 0,
  340.                         512,
  341.                         NULL,
  342.                         0);
  343.           }                            /* just RST -everything- sent   */
  344.                                        /* this inclued packets a reply */
  345.                                        /* (even RST) was recieved for  */
  346.  
  347.  
  348.  
  349.  
  350.         for (lastsent = 0;lastsentstate)
  351.                     {
  352.                      case -1: break;
  353.                      case 1 : printf("# port %d is listening.\n",p->n);
  354.                        someopen++;
  355.                        break;
  356.                      case 2 : printf("# port %d maybe listening (unknown response).\n",
  357.                                      p->n);
  358.                        someopen++;
  359.                        break;
  360.                      default: printf("# port %d needs to be rescanned.\n",p->n);
  361.                     }
  362.                   break;
  363.                 case TH_ACK:
  364.                   switch (p->state)
  365.                     {
  366.                      case -1:
  367.                        if (((p->ttl < 65) && checklowttl) || (p->window >0))
  368.                          {
  369.                             printf("# port %d maybe listening",p->n);
  370.                             if (p->ttl < 65) printf(" (low ttl)");
  371.                             if (p->window >0) printf(" (big window)");
  372.                             printf(".\n");
  373.                             someopen++;
  374.                          }
  375.                        break;
  376.                      case 1:
  377.                      case 2:
  378.                        printf("# port %d has an unexpected response.\n",
  379.                               p->n);
  380.                        break;
  381.                      default:
  382.                        printf("# port %d needs to be rescanned.\n",p->n);
  383.                     }
  384.                   break;
  385.                 case TH_FIN:
  386.                   switch (p->state)
  387.                     {
  388.                      case -1:
  389.                        break;
  390.                      case 0 :
  391.                        printf("# port %d maybe open.\n",p->n);
  392.                        someopen++;
  393.                        break;
  394.                      default:
  395.                        printf("# port %d has an unexpected response.\n",p->n);
  396.                     }
  397.                }
  398.           }
  399.  
  400.         printf("-----------------------------------------------\n");
  401.         printf("# total ports open or maybe open: %d\n\n",someopen);
  402.         free(ports);
  403.  
  404.         exit(0);                       /* heh. */
  405.  
  406.      }
  407.  
  408. int resolve_one(const char *name, unsigned long *addr, const char *desc)
  409.      {
  410.         struct sockaddr_in tempaddr;
  411.         if (resolve(name, &tempaddr,0) == -1) {
  412.            printf("error: can't resolve the %s.\n",desc);
  413.            return -1;
  414.         }
  415.  
  416.         *addr = tempaddr.sin_addr.s_addr;
  417.         return 0;
  418.      }
  419.  
  420. void give_info(void)
  421.      {
  422.         printf("# response address           : %s (%s)\n",spoof_name,inet_ntoa(spoof_addr));
  423.         printf("# target address             : %s (%s)\n",dest_name,inet_ntoa(dest_addr));
  424.         printf("# ports                      : %s\n",portstr);
  425.         printf("# (total number of ports)    : %d\n",maxports);
  426.         printf("# delay between sends        : %lu microseconds\n",usecdelay);
  427.         printf("# delay                      : %u seconds\n",waitdelay);
  428.         printf("# flood dectection threshold : %d unanswered sends\n",STCP_THRESHOLD);
  429.         printf("# slow factor                : %d\n",slowfactor);
  430.         printf("# max sends per port         : %d\n\n",STCP_SENDS);
  431.      }
  432.  
  433. int parse_args(int argc, char *argv[])
  434. {
  435.  
  436.    if (strrchr(argv[0],'/') != NULL)
  437.      argv[0] = strrchr(argv[0],'/') + 1;
  438.  
  439.    if (argc < 7)  {
  440.       printf("%s: not enough arguments\n",argv[0]);
  441.       return -1;
  442.    }
  443.  
  444.    switch (atoi(argv[1]))
  445.      {
  446.       case 0  : scanflags = TH_SYN;
  447.                 break;
  448.       case 1  : scanflags = TH_FIN;
  449.                 break;
  450.       case 2  : scanflags = TH_ACK;
  451.                 break;
  452.       default : printf("%s: unknown scanning method\n",argv[0]);
  453.                 return -1;
  454.      }
  455.  
  456.    spoof_name = argv[2];
  457.    dest_name = argv[3];
  458.  
  459.    portstr = argv[4];
  460.  
  461.    usecdelay = atol(argv[5]);
  462.    waitdelay = atoi(argv[6]);
  463.  
  464.    if (argc > 7) slowfactor = atoi(argv[7]);
  465.  
  466.    if ((usecdelay == 0) && (slowfactor > 0))
  467.      {
  468.         printf("%s: adjusting microsecond-delay to 1usec.\n");
  469.         usecdelay++;
  470.      }
  471.    return 0;
  472. }
  473.  
  474. /* MAIN ------------------------------------------------------ */
  475.  
  476. int build_ports(char *str)       /* build the initial port-database */
  477. {
  478.    int i;
  479.    int n;
  480.    struct portrec *p;
  481.    int sport;
  482.  
  483.    char *s;
  484.  
  485.  
  486.    s        = str;
  487.    maxports = 0;
  488.    n        = 0;
  489.  
  490.    while (*s != '\0')
  491.      {
  492.         switch (*s)
  493.           {
  494.            case '0':
  495.            case '1':
  496.            case '2':
  497.            case '3':
  498.            case '4':
  499.            case '5':
  500.            case '6':
  501.            case '7':
  502.            case '8':
  503.            case '9':
  504.              n *= 10;
  505.              n += (*s - '0');
  506.              break;
  507.            case '-':
  508.              if (n == 0) return -1;
  509.              sport = n;
  510.              n = 0;
  511.              break;
  512.            case ',':
  513.              if (n == 0) return -1;
  514.              if (sport != 0)
  515.                {
  516.                   if (sport >= n) return -1;
  517.                   maxports += n-sport;
  518.                   sport = 0;
  519.                } else
  520.                maxports++;
  521.              n = 0;
  522.              break;
  523.           }
  524.         s++;
  525.      }
  526.    if (n == 0) return -1;
  527.    if (sport != 0)
  528.      {
  529.         if (sport >= n) return -1;
  530.         maxports += n-sport;
  531.         sport = 0;
  532.      }
  533.    else
  534.      maxports++;
  535.  
  536.    maxports+=2;
  537.  
  538.    if ((ports = (struct portrec *)malloc((maxports)*sizeof(struct portrec))) == NULL)
  539.      {
  540.         fprintf(stderr,"\nerror: not enough memory for port database\n\n");
  541.         exit(1);
  542.      }
  543.  
  544.    s        = str;
  545.    maxports = 0;
  546.    n        = 0;
  547.  
  548.    while (*s != '\0')
  549.      {
  550.         switch (*s)
  551.           {
  552.            case '0':
  553.            case '1':
  554.            case '2':
  555.            case '3':
  556.            case '4':
  557.            case '5':
  558.            case '6':
  559.            case '7':
  560.            case '8':
  561.            case '9':
  562.              n *= 10;
  563.              n += (*s - '0');
  564.              break;
  565.            case '-':
  566.              if (n == 0) return -1;
  567.              sport = n;
  568.              n = 0;
  569.              break;
  570.            case ',':
  571.              if (n == 0) return -1;
  572.              if (sport != 0)
  573.                {
  574.                   if (sport >= n) return -1;
  575.                   while (sport <= n)
  576.                     {
  577.                        for (i=0;in == sport) break;
  578.  
  579.                        if (i < maxports-1 )
  580.                          printf("notice: duplicate port - %d\n",sport);
  581.                        else
  582.                          {
  583.                             (ports+maxports)->n = sport;
  584.                             maxports++;
  585.                          }
  586.                        sport++;
  587.                     }
  588.                   sport = 0;
  589.                } else
  590.                {
  591.                   for (i=0;in == n) break;
  592.  
  593.                   if (i < maxports-1 )
  594.                     printf("notice: duplicate port - %d\n",n);
  595.                   else
  596.                     {
  597.                        (ports+maxports)->n = n;
  598.                        maxports++;
  599.                     }
  600.                }
  601.              n = 0;
  602.              break;
  603.           }
  604.         s++;
  605.      }
  606.  
  607.    if (n == 0) return -1;
  608.    if (sport != 0)
  609.      {
  610.         if (sport >= n) return -1;
  611.         while (sport <= n)
  612.           {
  613.              for (i=0;in == sport) break;
  614.  
  615.              if (i < maxports-1 )
  616.                printf("notice: duplicate port - %d\n",sport);
  617.              else
  618.                {
  619.                   (ports+maxports)->n = sport;
  620.                   maxports++;
  621.                }
  622.              sport++;
  623.           }
  624.         sport = 0;
  625.      } else
  626.      {
  627.         for (i=0;in == n) break;
  628.  
  629.         if (i < maxports-1 )
  630.           printf("notice: duplicate port - %d\n",n);
  631.         else
  632.           {
  633.              (ports+maxports)->n = n;
  634.              maxports++;
  635.           }
  636.      }
  637.  
  638.    printf("\n");
  639.  
  640.    for (i=0;istate = 0;
  641.         p->sends = 0;
  642.      }
  643.  
  644.    return 0;
  645.  
  646. }
  647.  
  648. struct portrec *portbynum(int num)
  649. {
  650.    int i = 0;
  651.  
  652.    while ( ((ports+i)->n != num) && (istate != 0) || (p->sends == STCP_SENDS))
  653.           {
  654.              doneports++;
  655.              lastidx++;
  656.              lastidx %= maxports;
  657.           }
  658.         else
  659.           break;
  660.      }
  661.  
  662.    if (save)
  663.      lastidx = oldlastidx;
  664.    else
  665.      lastidx = (lastidx + 1) % maxports;
  666.  
  667.    if (doneports == maxports) return NULL;
  668.  
  669.    return p;
  670. }
  671.  
  672.  
  673.  
  674.  
  675. inline unsigned long usecdiff(struct timeval *a, struct timeval *b)
  676. {
  677.    unsigned long s;
  678.  
  679.    s = b->tv_sec - a->tv_sec;
  680.    s *= 1000000;
  681.    s += b->tv_usec - a->tv_usec;
  682.  
  683.    return s;                           /* return the stupid microsecond diff */
  684. }
  685.  
  686. void main(int argc, char *argv[])
  687. {
  688.    int lastsent = 0;
  689.  
  690.    char buf[3000];
  691.  
  692.    struct iphdr  *ip   = (struct iphdr *)(buf);
  693.    struct tcphdr *tcp  = (struct tcphdr *)(buf+sizeof(struct iphdr));
  694.  
  695.    struct sockaddr_in from;
  696.    int fromlen;
  697.  
  698.    struct portrec *readport;
  699.  
  700.    fd_set rset, wset;
  701.  
  702.    struct timeval waitsend, now, del;
  703.  
  704.    unsigned long udiff;
  705.  
  706.    int sendthreshold = 0;
  707.  
  708.  
  709.    banner();
  710.  
  711.    if (parse_args(argc,argv))
  712.      {
  713.         usage(argv[0]);
  714.         return;
  715.      }
  716.  
  717.    if (resolve_one(dest_name,
  718.                     &dest_addr,
  719.                     "destination host")) exit(1);
  720.  
  721.    destaddr.sin_addr.s_addr = dest_addr;
  722.    destaddr.sin_family = AF_INET;
  723.  
  724.    if (resolve_one(spoof_name,
  725.                     &spoof_addr,
  726.                     "source host")) exit(1);
  727.  
  728.    if ( build_ports(portstr) == -1)
  729.      {
  730.         printf("\n%s: bad port string\n",argv[0]);
  731.         usage(argv[0]);
  732.         return;
  733.      }
  734.  
  735.    give_info();
  736.  
  737.    if ((tcpsock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1)
  738.      {
  739.         printf("\nerror: couldn't get TCP raw socket\n\n");
  740.         exit(1);
  741.      }
  742.    if ((rawsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1)
  743.      {
  744.         printf("\nerror: couldn't get raw socket\n\n");
  745.         exit(1);
  746.      }
  747.  
  748.    /* well, let's get to it. */
  749.  
  750.    done = 0;
  751.  
  752.    printf("* BEGINNING SCAN\n");
  753.    fflush(stdout);
  754.  
  755.    gettimeofday(&waitsend,NULL);
  756.  
  757.    while (!done)
  758.      {
  759.  
  760.         if (nextport(1) == NULL)
  761.           {
  762.              alarm(0);             /* no more sends, now we just  */
  763.              signal(SIGALRM,timeout); /* to wait  seconds */
  764.              alarm(waitdelay);        /* before resetting and giving */
  765.           }                           /* results.                    */
  766.  
  767.         FD_ZERO(&rset);
  768.  
  769.         FD_SET(tcpsock,&rset);
  770.  
  771.         gettimeofday(&now,NULL);
  772.  
  773.         udiff = usecdiff(&waitsend,&now);
  774.  
  775.         /* here comes the multiple choice select().
  776.          * well, there are 3 states:
  777.          * 1. already sent all the packets.
  778.          * 2. didn't send all the packets, but it's not time for another send
  779.          * 3. didn't send all the packets and it is time for another send.
  780.          */
  781.  
  782.         if (nextport(1) != NULL)
  783.           if (udiff > usecdelay)
  784.           {
  785.              FD_ZERO(&wset);
  786.              FD_SET(rawsock,&wset);
  787.              select(FD_SETSIZE,&rset,&wset,NULL,NULL);
  788.           } else
  789.           {
  790.              del.tv_sec = 0;
  791.              del.tv_usec = usecdelay;
  792.              select(FD_SETSIZE,&rset,NULL,NULL,&del);
  793.           }
  794.         else
  795.           select(FD_SETSIZE,&rset,NULL,NULL,NULL);
  796.  
  797.         if (FD_ISSET(tcpsock,&rset))   /* process the reply */
  798.           {
  799.              fromlen = sizeof(from);
  800.  
  801.              recvfrom(tcpsock,&buf,3000,0,
  802.                       (struct sockaddr *)&from,&fromlen);
  803.  
  804.              if (from.sin_addr.s_addr == destaddr.sin_addr.s_addr)
  805.                if (ntohs(tcp->th_dport) == STCP_PORT)
  806.                {
  807.                   printf("* got reply");
  808.  
  809.                   readport = portbynum(ntohs(tcp->th_sport));
  810.  
  811.                   if (readport == NULL)
  812.                     printf(" -- bad port");
  813.                   else
  814.                     {
  815.                        sendthreshold = 0;
  816.                        if (!readport->state)
  817.                          {
  818.                             readport->ttl    = ip->ttl;
  819.                             readport->window = tcp->th_win;
  820.  
  821.                             if (tcp->th_flags & TH_RST)
  822.                               {
  823.                                  readport->state = -1;
  824.                                  printf(" (RST)");
  825.                                  if (readport->ttl    < 65) printf(" (short ttl)");
  826.                                  if (readport->window > 0) printf(" (big window)");
  827.                               }
  828.                             else
  829.                               if (tcp->th_flags & (TH_ACK | TH_SYN))
  830.                               {
  831.                                  readport->state = 1;
  832.                                  printf(" (SYN+ACK)");
  833.                                  tcpip_send(rawsock,&destaddr,
  834.                                             spoof_addr,destaddr.sin_addr.s_addr,
  835.                                             STCP_PORT,readport->n,
  836.                                             TH_RST,
  837.                                             readport->seq++, 0,
  838.                                             512,
  839.                                             NULL,
  840.                                             0);
  841.                               }
  842.                             else
  843.                               {
  844.                                  readport->state = 2;
  845.                                  printf(" (UNEXPECTED)");
  846.                                  tcpip_send(rawsock,&destaddr,
  847.                                             spoof_addr,destaddr.sin_addr.s_addr,
  848.                                             STCP_PORT,readport->n,
  849.                                             TH_RST,
  850.                                             readport->seq++, 0,
  851.                                             512,
  852.                                             NULL,
  853.                                             0);
  854.                               }
  855.                          }
  856.                        else
  857.                          printf(" (duplicate)");
  858.                     }
  859.                   printf("\n");
  860.                   fflush(stdout);
  861.                }
  862.           }
  863.  
  864.         if (nextport(1) != NULL)
  865.           if (FD_ISSET(rawsock,&wset)) /* process the sends */
  866.           {
  867.              readport = nextport(0);
  868.  
  869.              destaddr.sin_port = htons(readport->n);
  870.  
  871.              printf("* sending to port %d ",ntohs(destaddr.sin_port));
  872.  
  873.              readport->seq = lrand48();
  874.              readport->sends++;
  875.  
  876.              tcpip_send(rawsock,&destaddr,
  877.                         spoof_addr,destaddr.sin_addr.s_addr,
  878.                         STCP_PORT,ntohs(destaddr.sin_port),
  879.                         scanflags,
  880.                         readport->seq++, lrand48(),
  881.                         512,
  882.                         NULL,
  883.                         0);
  884.  
  885.              gettimeofday(&waitsend,NULL);
  886.  
  887.              FD_ZERO(&wset);
  888.  
  889.              printf("\n");
  890.  
  891.              if ((++sendthreshold > STCP_THRESHOLD) && (slowfactor))
  892.                {
  893.                   printf("\n\n -- THRESHOLD CROSSED - SLOWING UP SENDS\n\n");
  894.                   usecdelay *= slowfactor;
  895.                   sendthreshold = 0;
  896.                }
  897.           }
  898.      }
  899. }
  900.  
  901.  
  902.  
  903. /*
  904.  * tcp_pkt.c
  905.  *
  906.  * routines for creating TCP packets, and sending them into sockets.
  907.  *
  908.  * (version 0.3)
  909.  *
  910.  *
  911.  * BUGFIX: - it seems like the TCP pseudo header checksum was
  912.  *           acting up in serveral cases.
  913.  * ADDED : - HEXDUMP macro.
  914.  *         - packet dump handling
  915.  */
  916.  
  917. /* remove inlines for smaller size but lower speed */
  918.  
  919. #include <netinet/in.h>
  920. #include <string.h>
  921. #include <sys/types.h>
  922. #include <netinet/ip.h>
  923. #include <netinet/tcp.h>
  924.  
  925. #define IPHDRSIZE sizeof(struct iphdr)
  926. #define TCPHDRSIZE sizeof(struct tcphdr)
  927. #define PSEUDOHDRSIZE sizeof(struct pseudohdr)
  928.  
  929. /* ********** RIPPED CODE START ******************************** */
  930.  
  931. /*
  932.  * in_cksum --
  933.  *  Checksum routine for Internet Protocol family headers (C Version)
  934.  */
  935. unsigned short in_cksum(addr, len)
  936.     u_short *addr;
  937.     int len;
  938. {
  939.     register int nleft = len;
  940.     register u_short *w = addr;
  941.     register int sum = 0;
  942.     u_short answer = 0;
  943.  
  944.     /*
  945.      * Our algorithm is simple, using a 32 bit accumulator (sum), we add
  946.      * sequential 16 bit words to it, and at the end, fold back all the
  947.      * carry bits from the top 16 bits into the lower 16 bits.
  948.      */
  949.     while (nleft > 1)  {
  950.         sum += *w++;
  951.         nleft -= 2;
  952.     }
  953.  
  954.     /* mop up an odd byte, if necessary */
  955.     if (nleft == 1) {
  956.         *(u_char *)(&answer) = *(u_char *)w ;
  957.         sum += answer;
  958.     }
  959.  
  960.     /* add back carry outs from top 16 bits to low 16 bits */
  961.     sum = (sum >> 16) + (sum & 0xffff);   /* add hi 16 to low 16 */
  962.     sum += (sum >> 16);                   /* add carry */
  963.     answer = ~sum;                        /* truncate to 16 bits */
  964.     return(answer);
  965. }
  966.  
  967. /* ********** RIPPED CODE END ******************************** */
  968.  
  969. /*
  970.  * HEXDUMP()
  971.  *
  972.  * not too much to explain
  973.  */
  974. inline void HEXDUMP(unsigned len, unsigned char *data)
  975. {
  976.    unsigned i;
  977.    for (i=0;isaddr = s_addr;
  978.         pseudo->daddr = t_addr;
  979.         pseudo->protocol = IPPROTO_TCP;
  980.         pseudo->tcplength = htons(TCPHDRSIZE+datasize);
  981.  
  982.         /* The TCP pseudo-header was created. */
  983.  
  984.         tcp->th_sport   = htons(s_port);
  985.         tcp->th_dport   = htons(t_port);
  986.         tcp->th_off     = 5;          /* 20 bytes, (no options) */
  987.         tcp->th_flags   = tcpflags;
  988.         tcp->th_seq     = htonl(seq);
  989.         tcp->th_ack     = htonl(ack);
  990.         tcp->th_win     = htons(win); /* we don't need any bigger, I guess. */
  991.  
  992.         /* The necessary TCP header fields are set. */
  993.  
  994.         tcp->th_sum = in_cksum(pseudo,PSEUDOHDRSIZE+TCPHDRSIZE+datasize);
  995.  
  996.         memset(packet,0,IPHDRSIZE);
  997.         /* The pseudo-header is wiped to clear the IP header fields */
  998.  
  999.         ip->saddr    = s_addr;
  1000.         ip->daddr    = t_addr;
  1001.         ip->version  = 4;
  1002.         ip->ihl      = 5;
  1003.         ip->ttl      = 255;
  1004.         ip->id       = random()%1996;
  1005.         ip->protocol = IPPROTO_TCP; /* should be 6 */
  1006.         ip->tot_len  = htons(IPHDRSIZE + TCPHDRSIZE + datasize);
  1007.         ip->check    = in_cksum((char *)packet,IPHDRSIZE);
  1008.  
  1009.         /* The IP header is intact. The packet is ready. */
  1010.  
  1011. #ifdef TCP_PKT_DEBUG
  1012.         printf("Packet ready. Dump: \n");
  1013. #ifdef TCP_PKT_DEBUG_DATA
  1014.         HEXDUMP(IPHDRSIZE+TCPHDRSIZE+datasize,packet);
  1015. #else
  1016.         HEXDUMP(IPHDRSIZE+TCPHDRSIZE,packet);
  1017. #endif
  1018.         printf("\n");
  1019. #endif
  1020.  
  1021.         return sendto(socket, packet, IPHDRSIZE+TCPHDRSIZE+datasize, 0, (struct sockaddr *)address, sizeof(struct sockaddr));
  1022.  
  1023.         /* And off into the raw socket it goes. */
  1024.      }
  1025.  
  1026.  
  1027.  
  1028. /*
  1029.  * resolve.c
  1030.  *
  1031.  * resolves an internet text address into (struct sockaddr_in).
  1032.  *
  1033.  * CHANGES: 1. added the RESOLVE_QUIET preprocessor conditions. Jan 1996
  1034.  *          2. added resolve_rns() to always provide both name/ip. March 1996
  1035.  */
  1036.  
  1037. #include <sys/types.h>
  1038. #include <string.h>
  1039. #include <netdb.h>
  1040. #include <stdio.h>
  1041. #include <netinet/in.h>
  1042.  
  1043. int resolve( const char *name, struct sockaddr_in *addr, int port )
  1044.      {
  1045.         struct hostent *host;
  1046.  
  1047.         /* clear everything in case I forget something */
  1048.         bzero(addr,sizeof(struct sockaddr_in));
  1049.  
  1050.         if (( host = gethostbyname(name) ) == NULL )  {
  1051. #ifndef RESOLVE_QUIET
  1052.            fprintf(stderr,"unable to resolve host \"%s\" -- ",name);
  1053.            perror("");
  1054. #endif
  1055.            return -1;
  1056.         }
  1057.  
  1058.         addr->sin_family = host->h_addrtype;
  1059.         memcpy((caddr_t)&addr->sin_addr,host->h_addr,host->h_length);
  1060.         addr->sin_port = htons(port);
  1061.  
  1062.         return 0;
  1063.      }
  1064.  
  1065. int resolve_rns( char *name , unsigned long addr )
  1066.      {
  1067.         struct hostent *host;
  1068.         unsigned long address;
  1069.  
  1070.         address = addr;
  1071.         host = gethostbyaddr((char *)&address,4,AF_INET);
  1072.  
  1073.         if (!host)  {
  1074. #ifndef RESOLVE_QUIET
  1075.            fprintf(stderr,"unable to resolve host \"%s\" -- ",inet_ntoa(addr));
  1076.            perror("");
  1077. #endif
  1078.  
  1079.            return -1;
  1080.         }
  1081.  
  1082.         strcpy(name,host->h_name);
  1083.  
  1084.         return 0;
  1085.      }
  1086.  
  1087.  
  1088. unsigned long addr_to_ulong(struct sockaddr_in *addr)
  1089.      {
  1090.         return addr->sin_addr.s_addr;
  1091.      }
  1092.  
  1093.                          Back to the Security-Page
  1094.