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

  1.                      [Netcat rules the net ----------]
  2.  
  3.                                Netcat 1.10
  4.  
  5.   Netcat is a simple Unix utility which reads
  6.   and writes data across network connections,
  7.   using TCP or UDP protocol. It is designed           /\_/\
  8.   to be a reliable "back-end" tool that can          / 0 0 \
  9.   be used directly or easily driven by other        ====v====
  10.   programs and scripts. At the same time, it         \  W  /
  11.   is a feature-rich network debugging and            |     |     _
  12.   exploration tool, since it can create              / ___ \    /
  13.   almost any kind of connection you would           / /   \ \  |
  14.   need and has several interesting built-in        (((-----)))-'
  15.   capabilities. Netcat, or "nc" as the actual       /
  16.   program is named, should have been supplied      (      ___
  17.   long ago as another one of those cryptic          \__.=|___E
  18.   but standard Unix tools.                                 /
  19.  
  20.   In the simplest usage, "nc host port" creates a TCP connection to the
  21.   given port on the given target host. Your standard input is then sent
  22.   to the host, and anything that comes back across the connection is
  23.   sent to your standard output. This continues indefinitely, until the
  24.   network side of the connection shuts down. Note that this behavior is
  25.   different from most other applications which shut everything down and
  26.   exit after an end-of-file on the standard input.
  27.  
  28.   Netcat can also function as a server, by listening for inbound
  29.   connections on arbitrary ports and then doing the same reading and
  30.   writing. With minor limitations, netcat doesn't really care if it runs
  31.   in "client" or "server" mode -- it still shovels data back and forth
  32.   until there isn't any more left. In either mode, shutdown can be
  33.   forced after a configurable time of inactivity on the network side.
  34.  
  35.   And it can do this via UDP too, so netcat is possibly the "udp
  36.   telnet-like" application you always wanted for testing your UDP-mode
  37.   servers. UDP, as the "U" implies, gives less reliable data
  38.   transmission than TCP connections and some systems may have trouble
  39.   sending large amounts of data that way, but it's still a useful
  40.   capability to have.
  41.  
  42.   You may be asking "why not just use telnet to connect to arbitrary
  43.   ports?" Valid question, and here are some reasons. Telnet has the
  44.   "standard input EOF" problem, so one must introduce calculated delays
  45.   in driving scripts to allow network output to finish. This is the main
  46.   reason netcat stays running until the *network* side closes. Telnet
  47.   also will not transfer arbitrary binary data, because certain
  48.   characters are interpreted as telnet options and are thus removed from
  49.   the data stream. Telnet also emits some of its diagnostic messages to
  50.   standard output, where netcat keeps such things religiously separated
  51.   from its *output* and will never modify any of the real data in
  52.   transit unless you *really* want it to. And of course telnet is
  53.   incapable of listening for inbound connections, or using UDP instead.
  54.   Netcat doesn't have any of these limitations, is much smaller and
  55.   faster than telnet, and has many other advantages.
  56.  
  57.   Some of netcat's major features are:
  58.  
  59.      * Outbound or inbound connections, TCP or UDP, to or from any ports
  60.      * Full DNS forward/reverse checking, with appropriate warnings
  61.      * Ability to use any local source port
  62.      * Ability to use any locally-configured network source address
  63.      * Built-in port-scanning capabilities, with randomizer
  64.      * Built-in loose source-routing capability
  65.      * Can read command line arguments from standard input
  66.      * Slow-send mode, one line every N seconds
  67.      * Hex dump of transmitted and received data
  68.      * Optional ability to let another program service established
  69.        connections
  70.      * Optional telnet-options responder
  71.  
  72.   Efforts have been made to have netcat "do the right thing" in all its
  73.   various modes. If you believe that it is doing the wrong thing under
  74.   whatever circumstances, please notify me and tell me how you think it
  75.   should behave. If netcat is not able to do some task you think up,
  76.   minor tweaks to the code will probably fix that. It provides a basic
  77.   and easily-modified template for writing other network applications,
  78.   and I certainly encourage people to make custom mods and send in any
  79.   improvements they make to it. This is the second release; the overall
  80.   differences from 1.00 are relatively minor and have mostly to do with
  81.   portability and bugfixes. Many people provided greatly appreciated
  82.   fixes and comments on the 1.00 release. Continued feedback from the
  83.   Internet community is always welcome!
  84.  
  85.   Netcat is entirely my own creation, although plenty of other code was
  86.   used as examples. It is freely given away to the Internet community in
  87.   the hope that it will be useful, with no restrictions except giving
  88.   credit where it is due. No GPLs, Berkeley copyrights or any of that
  89.   nonsense. The author assumes NO responsibility for how anyone uses it.
  90.   If netcat makes you rich somehow and you're feeling generous, mail me
  91.   a check. If you are affiliated in any way with Microsoft Network, get
  92.   a life. Always ski in control. Comments, questions, and patches to
  93.   hobbit@avian.org.
  94.  
  95.   Building
  96.  
  97.   Compiling is fairly straightforward. Examine the Makefile for a
  98.   SYSTYPE that matches yours, and do "make ". The executable "nc" should
  99.   appear. If there is no relevant SYSTYPE section, try "generic". If you
  100.   create new sections for generic.h and Makefile to support another
  101.   platform, please follow the given format and mail back the diffs.
  102.  
  103.   There are a couple of other settable #defines in netcat.c, which you
  104.   can include as DFLAGS="-DTHIS -DTHAT" to your "make" invocation
  105.   without having to edit the Makefile. See the following discussions for
  106.   what they are and do.
  107.  
  108.   If you want to link against the resolver library on SunOS
  109.   [recommended] and you have BIND 4.9.x, you may need to change
  110.   XLIBS=-lresolv in the Makefile to XLIBS="-lresolv -l44bsd".
  111.  
  112.   Linux sys/time.h does not really support presetting of FD_SETSIZE; a
  113.   harmless warning is issued.
  114.  
  115.   Some systems may warn about pointer types for signal(). No problem,
  116.   though.
  117.  
  118.   Exploration of features
  119.  
  120.   Where to begin? Netcat is at the same time so simple and versatile,
  121.   it's like trying to describe everything you can do with your Swiss
  122.   Army knife. This will go over the basics; you should also read the
  123.   usage examples and notes later on which may give you even more ideas
  124.   about what this sort of tool is good for.
  125.  
  126.   If no command arguments are given at all, netcat asks for them, reads
  127.   a line from standard input, and breaks it up into arguments
  128.   internally. This can be useful when driving netcat from certain types
  129.   of scripts, with the side effect of hiding your command line arguments
  130.   from "ps" displays.
  131.  
  132.   The host argument can be a name or IP address. If -n is specified,
  133.   netcat will only accept numeric IP addresses and do no DNS lookups for
  134.   anything. If -n is not given and -v is turned on, netcat will do a
  135.   full forward and reverse name and address lookup for the host, and
  136.   warn you about the all-too-common problem of mismatched names in the
  137.   DNS. This often takes a little longer for connection setup, but is
  138.   useful to know about. There are circumstances under which this can
  139.   *save* time, such as when you want to know the name for some IP
  140.   address and also connect there. Netcat will just tell you all about
  141.   it, saving the manual steps of looking up the hostname yourself.
  142.   Normally mismatch- checking is case-insensitive per the DNS spec, but
  143.   you can define ANAL at compile time to make it case-sensitive --
  144.   sometimes useful for uncovering minor errors in your own DNS files
  145.   while poking around your networks.
  146.  
  147.   A port argument is required for outbound connections, and can be
  148.   numeric or a name as listed in /etc/services. If -n is specified, only
  149.   numeric arguments are valid. Special syntax and/or more than one port
  150.   argument cause different behavior -- see details below about
  151.   port-scanning.
  152.  
  153.   The -v switch controls the verbosity level of messages sent to
  154.   standard error. You will probably want to run netcat most of the time
  155.   with -v turned on, so you can see info about the connections it is
  156.   trying to make. You will probably also want to give a smallish -w
  157.   argument, which limits the time spent trying to make a connection. I
  158.   usually alias "nc" to "nc -v -w 3", which makes it function just about
  159.   the same for things I would otherwise use telnet to do. The timeout is
  160.   easily changed by a subsequent -w argument which overrides the earlier
  161.   one. Specifying -v more than once makes diagnostic output MORE
  162.   verbose. If -v is not specified at all, netcat silently does its work
  163.   unless some error happens, whereupon it describes the error and exits
  164.   with a nonzero status. Refused network connections are generally NOT
  165.   considered to be errors, unless you only asked for a single TCP port
  166.   and it was refused.
  167.  
  168.   Note that -w also sets the network inactivity timeout. This does not
  169.   have any effect until standard input closes, but then if nothing
  170.   further arrives from the network in the next seconds, netcat tries to
  171.   read the net once more for good measure, and then closes and exits.
  172.   There are a lot of network services now that accept a small amount of
  173.   input and return a large amount of output, such as Gopher and Web
  174.   servers, which is the main reason netcat was written to "block" on the
  175.   network staying open rather than standard input. Handling the timeout
  176.   this way gives uniform behavior with network servers that *don't*
  177.   close by themselves until told to.
  178.  
  179.   UDP connections are opened instead of TCP when -u is specified. These
  180.   aren't really "connections" per se since UDP is a connectionless
  181.   protocol, although netcat does internally use the "connected UDP
  182.   socket" mechanism that most kernels support. Although netcat claims
  183.   that an outgoing UDP connection is "open" immediately, no data is sent
  184.   until something is read from standard input. Only thereafter is it
  185.   possible to determine whether there really is a UDP server on the
  186.   other end, and often you just can't tell. Most UDP protocols use
  187.   timeouts and retries to do their thing and in many cases won't bother
  188.   answering at all, so you should specify a timeout and hope for the
  189.   best. You will get more out of UDP connections if standard input is
  190.   fed from a source of data that looks like various kinds of server
  191.   requests.
  192.  
  193.   To obtain a hex dump file of the data sent either way, use "-o
  194.   logfile". The dump lines begin with "<" or ">" to respectively
  195.   indicate "from the net" or "to the net", and contain the total count
  196.   per direction, and hex and ascii representations of the traffic.
  197.   Capturing a hex dump naturally slows netcat down a bit, so don't use
  198.   it where speed is critical.
  199.  
  200.   Netcat can bind to any local port, subject to privilege restrictions
  201.   and ports that are already in use. It is also possible to use a
  202.   specific local network source address if it is that of a network
  203.   interface on your machine. [Note: this does not work correctly on all
  204.   platforms.] Use "-p portarg" to grab a specific local port, and "-s
  205.   ip-addr" or "-s name" to have that be your source IP address. This is
  206.   often referred to as "anchoring the socket". Root users can grab any
  207.   unused source port including the "reserved" ones less than 1024.
  208.   Absence of -p will bind to whatever unused port the system gives you,
  209.   just like any other normal client connection, unless you use -r [see
  210.   below].
  211.  
  212.   Listen mode will cause netcat to wait for an inbound connection, and
  213.   then the same data transfer happens. Thus, you can do "nc -l -p 1234 <
  214.   filename" and when someone else connects to your port 1234, the file
  215.   is sent to them whether they wanted it or not. Listen mode is
  216.   generally used along with a local port argument -- this is required
  217.   for UDP mode, while TCP mode can have the system assign one and tell
  218.   you what it is if -v is turned on. If you specify a target host and
  219.   optional port in listen mode, netcat will accept an inbound connection
  220.   only from that host and if you specify one, only from that foreign
  221.   source port. In verbose mode you'll be informed about the inbound
  222.   connection, including what address and port it came from, and since
  223.   listening on "any" applies to several possibilities, which address it
  224.   came *to* on your end. If the system supports IP socket options,
  225.   netcat will attempt to retrieve any such options from an inbound
  226.   connection and print them out in hex.
  227.  
  228.   If netcat is compiled with -DGAPING_SECURITY_HOLE, the -e argument
  229.   specifies a program to exec after making or receiving a successful
  230.   connection. In the listening mode, this works similarly to "inetd" but
  231.   only for a single instance. Use with GREAT CARE. This piece of the
  232.   code is normally not enabled; if you know what you're doing, have fun.
  233.   This hack also works in UDP mode. Note that you can only supply -e
  234.   with the name of the program, but no arguments. If you want to launch
  235.   something with an argument list, write a two-line wrapper script or
  236.   just use inetd like always.
  237.  
  238.   If netcat is compiled with -DTELNET, the -t argument enables it to
  239.   respond to telnet option negotiation [always in the negative, i.e.
  240.   DONT or WONT]. This allows it to connect to a telnetd and get past the
  241.   initial negotiation far enough to get a login prompt from the server.
  242.   Since this feature has the potential to modify the data stream, it is
  243.   not enabled by default. You have to understand why you might need this
  244.   and turn on the #define yourself.
  245.  
  246.   Data from the network connection is always delivered to standard
  247.   output as efficiently as possible, using large 8K reads and writes.
  248.   Standard input is normally sent to the net the same way, but the -i
  249.   switch specifies an "interval time" which slows this down
  250.   considerably. Standard input is still read in large batches, but
  251.   netcat then tries to find where line breaks exist and sends one line
  252.   every interval time. Note that if standard input is a terminal, data
  253.   is already read line by line, so unless you make the -i interval
  254.   rather long, what you type will go out at a fairly normal rate. -i is
  255.   really designed for use when you want to "measure out" what is read
  256.   from files or pipes.
  257.  
  258.   Port-scanning is a popular method for exploring what's out there.
  259.   Netcat accepts its commands with options first, then the target host,
  260.   and everything thereafter is interpreted as port names or numbers, or
  261.   ranges of ports in M-N syntax. CAVEAT: some port names in
  262.   /etc/services contain hyphens -- netcat currently will not correctly
  263.   parse those, so specify ranges using numbers if you can. If more than
  264.   one port is thus specified, netcat connects to *all* of them, sending
  265.   the same batch of data from standard input [up to 8K worth] to each
  266.   one that is successfully connected to. Specifying multiple ports also
  267.   suppresses diagnostic messages about refused connections, unless -v is
  268.   specified twice for "more verbosity". This way you normally get
  269.   notified only about genuinely open connections. Example: "nc -v -w 2
  270.   -z target 20-30" will try connecting to every port between 20 and 30
  271.   [inclusive] at the target, and will likely inform you about an FTP
  272.   server, telnet server, and mailer along the way. The -z switch
  273.   prevents sending any data to a TCP connection and very limited probe
  274.   data to a UDP connection, and is thus useful as a fast scanning mode
  275.   just to see what ports the target is listening on. To limit scanning
  276.   speed if desired, -i will insert a delay between each port probe.
  277.   There are some pitfalls with regard to UDP scanning, described later,
  278.   but in general it works well.
  279.  
  280.   For each range of ports specified, scanning is normally done downward
  281.   within that range. If the -r switch is used, scanning hops randomly
  282.   around within that range and reports open ports as it finds them. [If
  283.   you want them listed in order regardless, pipe standard error through
  284.   "sort"...] In addition, if random mode is in effect, the local source
  285.   ports are also randomized. This prevents netcat from exhibiting any
  286.   kind of regular pattern in its scanning. You can exert fairly fine
  287.   control over your scan by judicious use of -r and selected port ranges
  288.   to cover. If you use -r for a single connection, the source port will
  289.   have a random value above 8192, rather than the next one the kernel
  290.   would have assigned you. Note that selecting a specific local port
  291.   with -p overrides any local-port randomization.
  292.  
  293.   Many people are interested in testing network connectivity using IP
  294.   source routing, even if it's only to make sure their own firewalls are
  295.   blocking source-routed packets. On systems that support it, the -g
  296.   switch can be used multiple times [up to 8] to construct a
  297.   loose-source-routed path for your connection, and the -G argument
  298.   positions the "hop pointer" within the list. If your network allows
  299.   source-routed traffic in and out, you can test connectivity to your
  300.   own services via remote points in the internet. Note that although
  301.   newer BSD-flavor telnets also have source-routing capability, it isn't
  302.   clearly documented and the command syntax is somewhat clumsy. Netcat's
  303.   handling of "-g" is modeled after "traceroute".
  304.  
  305.   Netcat tries its best to behave just like "cat". It currently does
  306.   nothing to terminal input modes, and does no end-of-line conversion.
  307.   Standard input from a terminal is read line by line with normal
  308.   editing characters in effect. You can freely suspend out of an
  309.   interactive connection and resume. ^C or whatever your interrupt
  310.   character is will make netcat close the network connection and exit. A
  311.   switch to place the terminal in raw mode has been considered, but so
  312.   far has not been necessary. You can send raw binary data by reading it
  313.   out of a file or piping from another program, so more meaningful
  314.   effort would be spent writing an appropriate front-end driver.
  315.  
  316.   Netcat is not an "arbitrary packet generator", but the ability to talk
  317.   to raw sockets and/or nit/bpf/dlpi may appear at some point. Such
  318.   things are clearly useful; I refer you to Darren Reed's excellent
  319.   ip_filter package, which now includes a tool to construct and send raw
  320.   packets with any contents you want.
  321.  
  322.   Example uses -- the light side
  323.  
  324.   Again, this is a very partial list of possibilities, but it may get
  325.   you to think up more applications for netcat. Driving netcat with
  326.   simple shell or expect scripts is an easy and flexible way to do
  327.   fairly complex tasks, especially if you're not into coding network
  328.   tools in C. My coding isn't particularly strong either [although
  329.   undoubtedly better after writing this thing!], so I tend to construct
  330.   bare-metal tools like this that I can trivially plug into other
  331.   applications. Netcat doubles as a teaching tool -- one can learn a
  332.   great deal about more complex network protocols by trying to simulate
  333.   them through raw connections!
  334.  
  335.   An example of netcat as a backend for something else is the
  336.   shell-script Web browser, which simply asks for the relevant parts of
  337.   a URL and pipes "GET /what/ever" into a netcat connection to the
  338.   server. I used to do this with telnet, and had to use calculated sleep
  339.   times and other stupidity to kludge around telnet's limitations.
  340.   Netcat guarantees that I get the whole page, and since it transfers
  341.   all the data unmodified, I can even pull down binary image files and
  342.   display them elsewhere later. Some folks may find the idea of a
  343.   shell-script web browser silly and strange, but it starts up and gets
  344.   me my info a hell of a lot faster than a GUI browser and doesn't hide
  345.   any contents of links and forms and such. This is included, as
  346.   scripts/web, along with several other web-related examples.
  347.  
  348.   Netcat is an obvious replacement for telnet as a tool for talking to
  349.   daemons. For example, it is easier to type "nc host 25", talk to
  350.   someone's mailer, and just ^C out than having to type ^]c or QUIT as
  351.   telnet would require you to do. You can quickly catalog the services
  352.   on your network by telling netcat to connect to well-known services
  353.   and collect greetings, or at least scan for open ports. You'll
  354.   probably want to collect netcat's diagnostic messages in your output
  355.   files, so be sure to include standard error in the output using `>&
  356.   file' in *csh or `> file 2>&1' in bourne shell.
  357.  
  358.   A scanning example: "echo QUIT | nc -v -w 5 target 20-250 500-600
  359.   5990-7000" will inform you about a target's various well-known TCP
  360.   servers, including r-services, X, IRC, and maybe a few you didn't
  361.   expect. Sending in QUIT and using the timeout will almost guarantee
  362.   that you see some kind of greeting or error from each service, which
  363.   usually indicates what it is and what version. [Beware of the
  364.   "chargen" port, though...] SATAN uses exactly this technique to
  365.   collect host information, and indeed some of the ideas herein were
  366.   taken from the SATAN backend tools. If you script this up to try every
  367.   host in your subnet space and just let it run, you will not only see
  368.   all the services, you'll find out about hosts that aren't correctly
  369.   listed in your DNS. Then you can compare new snapshots against old
  370.   snapshots to see changes. For going after particular services, a more
  371.   intrusive example is in scripts/probe.
  372.  
  373.   Netcat can be used as a simple data transfer agent, and it doesn't
  374.   really matter which end is the listener and which end is the client --
  375.   input at one side arrives at the other side as output. It is helpful
  376.   to start the listener at the receiving side with no timeout specified,
  377.   and then give the sending side a small timeout. That way the listener
  378.   stays listening until you contact it, and after data stops flowing the
  379.   client will time out, shut down, and take the listener with it. Unless
  380.   the intervening network is fraught with problems, this should be
  381.   completely reliable, and you can always increase the timeout. A
  382.   typical example of something "rsh" is often used for: on one side,
  383.  
  384.           nc -l -p 1234 | uncompress -c | tar xvfp -
  385.  
  386.   and then on the other side
  387.  
  388.           tar cfp - /some/dir | compress -c | nc -w 3 othermachine 1234
  389.  
  390.   will transfer the contents of a directory from one machine to another,
  391.   without having to worry about .rhosts files, user accounts, or inetd
  392.   configurations at either end. Again, it matters not which is the
  393.   listener or receiver; the "tarring" machine could just as easily be
  394.   running the listener instead. One could conceivably use a scheme like
  395.   this for backups, by having cron-jobs fire up listeners and backup
  396.   handlers [which can be restricted to specific addresses and ports
  397.   between each other] and pipe "dump" or "tar" on one machine to "dd
  398.   of=/dev/tapedrive" on another as usual. Since netcat returns a nonzero
  399.   exit status for a denied listener connection, scripts to handle such
  400.   tasks could easily log and reject connect attempts from third parties,
  401.   and then retry.
  402.  
  403.   Another simple data-transfer example: shipping things to a PC that
  404.   doesn't have any network applications yet except a TCP stack and a web
  405.   browser. Point the browser at an arbitrary port on a Unix server by
  406.   telling it to download something like http://unixbox:4444/foo, and
  407.   have a listener on the Unix side ready to ship out a file when the
  408.   connect comes in. The browser may pervert binary data when told to
  409.   save the URL, but you can dig the raw data out of the on-disk cache.
  410.  
  411.   If you build netcat with GAPING_SECURITY_HOLE defined, you can use it
  412.   as an "inetd" substitute to test experimental network servers that
  413.   would otherwise run under "inetd". A script or program will have its
  414.   input and output hooked to the network the same way, perhaps sans some
  415.   fancier signal handling. Given that most network services do not bind
  416.   to a particular local address, whether they are under "inetd" or not,
  417.   it is possible for netcat avoid the "address already in use" error by
  418.   binding to a specific address. This lets you [as root, for low ports]
  419.   place netcat "in the way" of a standard service, since inbound
  420.   connections are generally sent to such specifically-bound listeners
  421.   first and fall back to the ones bound to "any". This allows for a
  422.   one-off experimental simulation of some service, without having to
  423.   screw around with inetd.conf. Running with -v turned on and collecting
  424.   a connection log from standard error is recommended.
  425.  
  426.   Netcat as well can make an outbound connection and then run a program
  427.   or script on the originating end, with input and output connected to
  428.   the same network port. This "inverse inetd" capability could enhance
  429.   the backup-server concept described above or help facilitate things
  430.   such as a "network dialback" concept. The possibilities are many and
  431.   varied here; if such things are intended as security mechanisms, it
  432.   may be best to modify netcat specifically for the purpose instead of
  433.   wrapping such functions in scripts. Speaking of inetd, netcat will
  434.   function perfectly well *under* inetd as a TCP connection redirector
  435.   for inbound services, like a "plug-gw" without the authentication
  436.   step. This is very useful for doing stuff like redirecting traffic
  437.   through your firewall out to other places like web servers and mail
  438.   hubs, while posing no risk to the firewall machine itself. Put netcat
  439.   behind inetd and tcp_wrappers, perhaps thusly:
  440.  
  441.           www stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80
  442.  
  443.   and you have a simple and effective "application relay" with access
  444.   control and logging. Note use of the wait time as a "safety" in case
  445.   realwww isn't reachable or the calling user aborts the connection --
  446.   otherwise the relay may hang there forever.
  447.  
  448.   You can use netcat to generate huge amounts of useless network data
  449.   for various performance testing. For example, doing
  450.  
  451.           yes AAAAAAAAAAAAAAAAAAAAAA | nc -v -v -l -p 2222 > /dev/null
  452.  
  453.   on one side and then hitting it with
  454.  
  455.           yes BBBBBBBBBBBBBBBBBBBBBB | nc othermachine 2222 > /dev/null
  456.  
  457.   from another host will saturate your wires with A's and B's. The "very
  458.   verbose" switch usage will tell you how many of each were sent and
  459.   received after you interrupt either side. Using UDP mode produces
  460.   tremendously MORE trash per unit time in the form of fragmented 8
  461.   Kbyte mobygrams -- enough to stress-test kernels and network
  462.   interfaces. Firing random binary data into various network servers may
  463.   help expose bugs in their input handling, which nowadays is a popular
  464.   thing to explore. A simple example data-generator is given in
  465.   data/data.c included in this package, along with a small collection of
  466.   canned input files to generate various packet contents. This program
  467.   is documented in its beginning comments, but of interest here is using
  468.   "%r" to generate random bytes at well-chosen points in a data stream.
  469.   If you can crash your daemon, you likely have a security problem.
  470.  
  471.   The hex dump feature may be useful for debugging odd network
  472.   protocols, especially if you don't have any network monitoring
  473.   equipment handy or aren't root where you'd need to run "tcpdump" or
  474.   something. Bind a listening netcat to a local port, and have it run a
  475.   script which in turn runs another netcat to the real service and
  476.   captures the hex dump to a log file. This sets up a transparent relay
  477.   between your local port and wherever the real service is. Be sure that
  478.   the script-run netcat does *not* use -v, or the extra info it sends to
  479.   standard error may confuse the protocol. Note also that you cannot
  480.   have the "listen/exec" netcat do the data capture, since once the
  481.   connection arrives it is no longer netcat that is running.
  482.  
  483.   Binding to an arbitrary local port allows you to simulate things like
  484.   r-service clients, if you are root locally. For example, feeding
  485.   "^@root^@joe^@pwd^@" [where ^@ is a null, and root/joe could be any
  486.   other local/remote username pair] into a "rsh" or "rlogin" server,
  487.   FROM your port 1023 for example, duplicates what the server expects to
  488.   receive. Thus, you can test for insecure .rhosts files around your
  489.   network without having to create new user accounts on your client
  490.   machine. The program data/rservice.c can aid this process by
  491.   constructing the "rcmd" protocol bytes. Doing this also prevents
  492.   "rshd" from trying to create that separate standard-error socket and
  493.   still gives you an input path, as opposed to the usual action of "rsh
  494.   -n". Using netcat for things like this can be really useful sometimes,
  495.   because rsh and rlogin generally want a host *name* as an argument and
  496.   won't accept IP addresses. If your client-end DNS is hosed, as may be
  497.   true when you're trying to extract backup sets on to a dumb client,
  498.   "netcat -n" wins where normal rsh/rlogin is useless.
  499.  
  500.   If you are unsure that a remote syslogger is working, test it with
  501.   netcat. Make a UDP connection to port 514 and type in "<0>message",
  502.   which should correspond to "kern.emerg" and cause syslogd to scream
  503.   into every file it has open [and possibly all over users' terminals].
  504.   You can tame this down by using a different number and use netcat
  505.   inside routine scripts to send syslog messages to places that aren't
  506.   configured in syslog.conf. For example, "echo '<38>message' | nc -w 1
  507.   -u loggerhost 514" should send to auth.notice on loggerhost. The exact
  508.   number may vary; check against your syslog.h first.
  509.  
  510.   Netcat provides several ways for you to test your own packet filters.
  511.   If you bind to a port normally protected against outside access and
  512.   make a connection to somewhere outside your own network, the return
  513.   traffic will be coming to your chosen port from the "outside" and
  514.   should be blocked. TCP may get through if your filter passes all "ack
  515.   syn", but it shouldn't be even doing that to low ports on your
  516.   network. Remember to test with UDP traffic as well! If your filter
  517.   passes at least outbound source-routed IP packets, bouncing a
  518.   connection back to yourself via some gateway outside your network will
  519.   create "incoming" traffic with your source address, which should get
  520.   dropped by a correctly configured anti-spoofing filter. This is a
  521.   "non-test" if you're also dropping source-routing, but it's good to be
  522.   able to test for that too. Any packet filter worth its salt will be
  523.   blocking source-routed packets in both directions, but you never know
  524.   what interesting quirks you might turn up by playing around with
  525.   source ports and addresses and watching the wires with a network
  526.   monitor.
  527.  
  528.   You can use netcat to protect your own workstation's X server against
  529.   outside access. X is stupid enough to listen for connections on "any"
  530.   and never tell you when new connections arrive, which is one reason it
  531.   is so vulnerable. Once you have all your various X windows up and
  532.   running you can use netcat to bind just to your ethernet address and
  533.   listen to port 6000. Any new connections from outside the machine will
  534.   hit netcat instead your X server, and you get a log of who's trying.
  535.   You can either tell netcat to drop the connection, or perhaps run
  536.   another copy of itself to relay to your actual X server on
  537.   "localhost". This may not work for dedicated X terminals, but it may
  538.   be possible to authorize your X terminal only for its boot server, and
  539.   run a relay netcat over on the server that will in turn talk to your X
  540.   terminal. Since netcat only handles one listening connection per run,
  541.   make sure that whatever way you rig it causes another one to run and
  542.   listen on 6000 soon afterward, or your real X server will be reachable
  543.   once again. A very minimal script just to protect yourself could be
  544.  
  545.           while true ; do
  546.             nc -v -l -s  -p 6000 localhost 2
  547.           done
  548.  
  549.   which causes netcat to accept and then close any inbound connection to
  550.   your workstation's normal ethernet address, and another copy is
  551.   immediately run by the script. Send standard error to a file for a log
  552.   of connection attempts. If your system can't do the "specific bind"
  553.   thing all is not lost; run your X server on display ":1" or port 6001,
  554.   and netcat can still function as a probe alarm by listening on 6000.
  555.  
  556.   Does your shell-account provider allow personal Web pages, but not CGI
  557.   scripts? You can have netcat listen on a particular port to execute a
  558.   program or script of your choosing, and then just point to the port
  559.   with a URL in your homepage. The listener could even exist on a
  560.   completely different machine, avoiding the potential ire of the
  561.   homepage-host administrators. Since the script will get the raw
  562.   browser query as input it won't look like a typical CGI script, and
  563.   since it's running under your UID you need to write it carefully. You
  564.   may want to write a netcat-based script as a wrapper that reads a
  565.   query and sets up environment variables for a regular CGI script. The
  566.   possibilities for using netcat and scripts to handle Web stuff are
  567.   almost endless. Again, see the examples under scripts/.
  568.  
  569.   Example uses -- the dark side
  570.  
  571.   Equal time is deserved here, since a versatile tool like this can be
  572.   useful to any Shade of Hat. I could use my Victorinox to either fix
  573.   your car or disassemble it, right? You can clearly use something like
  574.   netcat to attack or defend -- I don't try to govern anyone's social
  575.   outlook, I just build tools. Regardless of your intentions, you should
  576.   still be aware of these threats to your own systems.
  577.  
  578.   The first obvious thing is scanning someone *else's* network for
  579.   vulnerable services. Files containing preconstructed data, be it
  580.   exploratory or exploitive, can be fed in as standard input, including
  581.   command-line arguments to netcat itself to keep "ps" ignorant of your
  582.   doings. The more random the scanning, the less likelihood of detection
  583.   by humans, scan-detectors, or dynamic filtering, and with -i you'll
  584.   wait longer but avoid loading down the target's network. Some examples
  585.   for crafting various standard UDP probes are given in data/*.d.
  586.  
  587.   Some configurations of packet filters attempt to solve the FTP-data
  588.   problem by just allowing such connections from the outside. These come
  589.   FROM port 20, TO high TCP ports inside -- if you locally bind to port
  590.   20, you may find yourself able to bypass filtering in some cases.
  591.   Maybe not to low ports "inside", but perhaps to TCP NFS servers, X
  592.   servers, Prospero, ciscos that listen on 200x and 400x... Similar
  593.   bypassing may be possible for UDP [and maybe TCP too] if a connection
  594.   comes from port 53; a filter may assume it's a nameserver response.
  595.  
  596.   Using -e in conjunction with binding to a specific address can enable
  597.   "server takeover" by getting in ahead of the real ones, whereupon you
  598.   can snarf data sent in and feed your own back out. At the very least
  599.   you can log a hex dump of someone else's session. If you are root, you
  600.   can certainly use -s and -e to run various hacked daemons without
  601.   having to touch inetd.conf or the real daemons themselves. You may not
  602.   always have the root access to deal with low ports, but what if you
  603.   are on a machine that also happens to be an NFS server? You might be
  604.   able to collect some interesting things from port 2049, including
  605.   local file handles. There are several other servers that run on high
  606.   ports that are likely candidates for takeover, including many of the
  607.   RPC services on some platforms [yppasswdd, anyone?]. Kerberos tickets,
  608.   X cookies, and IRC traffic also come to mind. RADIUS-based terminal
  609.   servers connect incoming users to shell-account machines on a high
  610.   port, usually 1642 or thereabouts. SOCKS servers run on 1080. Do
  611.   "netstat -a" and get creative.
  612.  
  613.   There are some daemons that are well-written enough to bind separately
  614.   to all the local interfaces, possibly with an eye toward heading off
  615.   this sort of problem. Named from recent BIND releases, and NTP, are
  616.   two that come to mind. Netstat will show these listening on address.53
  617.   instead of *.53. You won't be able to get in front of these on any of
  618.   the real interface addresses, which of course is especially
  619.   interesting in the case of named, but these servers sometimes forget
  620.   about things like "alias" interface addresses or interfaces that
  621.   appear later on such as dynamic PPP links. There are some hacked web
  622.   servers and versions of "inetd" floating around that specifically bind
  623.   as well, based on a configuration file -- these generally *are* bound
  624.   to alias addresses to offer several different address-based services
  625.   from one machine.
  626.  
  627.   Using -e to start a remote backdoor shell is another obvious sort of
  628.   thing, easier than constructing a file for inetd to listen on
  629.   "ingreslock" or something, and you can access-control it against other
  630.   people by specifying a client host and port. Experience with this
  631.   truly demonstrates how fragile the barrier between being "logged in"
  632.   or not really is, and is further expressed by scripts/bsh. If you're
  633.   already behind a firewall, it may be easier to make an *outbound*
  634.   connection and then run a shell; a small wrapper script can
  635.   periodically try connecting to a known place and port, you can later
  636.   listen there until the inbound connection arrives, and there's your
  637.   shell. Running a shell via UDP has several interesting features,
  638.   although be aware that once "connected", the UDP stub sockets tend to
  639.   show up in "netstat" just like TCP connections and may not be quite as
  640.   subtle as you wanted. Packets may also be lost, so use TCP if you need
  641.   reliable connections. But since UDP is connectionless, a hookup of
  642.   this sort will stick around almost forever, even if you ^C out of
  643.   netcat or do a reboot on your side, and you only need to remember the
  644.   ports you used on both ends to reestablish. And outbound UDP-plus-exec
  645.   connection creates the connected socket and starts the program
  646.   immediately. On a listening UDP connection, the socket is created once
  647.   a first packet is received. In either case, though, such a
  648.   "connection" has the interesting side effect that only your
  649.   client-side IP address and [chosen?] source port will thereafter be
  650.   able to talk to it. Instant access control! A non-local third party
  651.   would have to do ALL of the following to take over such a session:
  652.  
  653.      * forge UDP with your source address [trivial to do; see below]
  654.      * guess the port numbers of BOTH ends, or sniff the wire for them
  655.      * arrange to block ICMP or UDP return traffic between it and your
  656.        real
  657.      * source, so the session doesn't die with a network write error.
  658.  
  659.   The companion program data/rservice.c is helpful in scripting up any
  660.   sort of r-service username or password guessing attack. The arguments
  661.   to "rservice" are simply the strings that get null-terminated and
  662.   passed over an "rcmd"-style connection, with the assumption that the
  663.   client does not need a separate standard-error port. Brute-force
  664.   password banging is best done via "rexec" if it is available since it
  665.   is less likely to log failed attempts. Thus, doing "rservice joe
  666.   joespass pwd | nc target exec" should return joe's home dir if the
  667.   password is right, or "Permission denied." Plug in a dictionary and go
  668.   to town. If you're attacking rsh/rlogin, remember to be root and bind
  669.   to a port between 512 and 1023 on your end, and pipe in "rservice joe
  670.   joe pwd" and such.
  671.  
  672.   Netcat can prevent inadvertently sending extra information over a
  673.   telnet connection. Use "nc -t" in place of telnet, and daemons that
  674.   try to ask for things like USER and TERM environment variables will
  675.   get no useful answers, as they otherwise would from a more recent
  676.   telnet program. Some telnetds actually try to collect this stuff and
  677.   then plug the USER variable into "login" so that the caller is then
  678.   just asked for a password! This mechanism could cause a login attempt
  679.   as YOUR real username to be logged over there if you use a
  680.   Borman-based telnet instead of "nc -t".
  681.  
  682.   Got an unused network interface configured in your kernel [e.g. SLIP],
  683.   or support for alias addresses? Ifconfig one to be any address you
  684.   like, and bind to it with -s to enable all sorts of shenanigans with
  685.   bogus source addresses. The interface probably has to be UP before
  686.   this works; some SLIP versions need a far-end address before this is
  687.   true. Hammering on UDP services is then a no-brainer. What you can do
  688.   to an unfiltered syslog daemon should be fairly obvious; trimming the
  689.   conf file can help protect against it. Many routers out there still
  690.   blindly believe what they receive via RIP and other routing protocols.
  691.   Although most UDP echo and chargen servers check if an incoming packet
  692.   was sent from *another* "internal" UDP server, there are many that
  693.   still do not, any two of which [or many, for that matter] could keep
  694.   each other entertained for hours at the expense of bandwidth. And you
  695.   can always make someone wonder why she's being probed by nsa.gov.
  696.  
  697.   Your TCP spoofing possibilities are mostly limited to destinations you
  698.   can source-route to while locally bound to your phony address. Many
  699.   sites block source-routed packets these days for precisely this
  700.   reason. If your kernel does oddball things when sending source-routed
  701.   packets, try moving the pointer around with -G. You may also have to
  702.   fiddle with the routing on your own machine before you start receiving
  703.   packets back. Warning: some machines still send out traffic using the
  704.   source address of the outbound interface, regardless of your binding,
  705.   especially in the case of localhost. Check first. If you can open a
  706.   connection but then get no data back from it, the target host is
  707.   probably killing the IP options on its end [this is an option inside
  708.   TCP wrappers and several other packages], which happens after the
  709.   3-way handshake is completed. If you send some data and observe the
  710.   "send-q" side of "netstat" for that connection increasing but never
  711.   getting sent, that's another symptom. Beware: if Sendmail 8.7.x
  712.   detects a source-routed SMTP connection, it extracts the hop list and
  713.   sticks it in the Received: header!
  714.  
  715.   SYN bombing [sometimes called "hosing"] can disable many TCP servers,
  716.   and if you hit one often enough, you can keep it unreachable for days.
  717.   As is true of many other denial-of-service attacks, there is currently
  718.   no defense against it except maybe at the human level. Making kernel
  719.   SOMAXCONN considerably larger than the default and the half-open
  720.   timeout smaller can help, and indeed some people running large
  721.   high-performance web servers have *had* to do that just to handle
  722.   normal traffic. Taking out mailers and web servers is sociopathic, but
  723.   on the other hand it is sometimes useful to be able to, say, disable a
  724.   site's identd daemon for a few minutes. If someone realizes what is
  725.   going on, backtracing will still be difficult since the packets have a
  726.   phony source address, but calls to enough ISP NOCs might eventually
  727.   pinpoint the source. It is also trivial for a clueful ISP to watch for
  728.   or even block outgoing packets with obviously fake source addresses,
  729.   but as we know many of them are not clueful or willing to get involved
  730.   in such hassles. Besides, outbound packets with an [otherwise
  731.   unreachable] source address in one of their net blocks would look
  732.   fairly legitimate.
  733.  
  734.   Notes
  735.  
  736.   A discussion of various caveats, subtleties, and the design of the
  737.   innards.
  738.  
  739.   As of version 1.07 you can construct a single file containing command
  740.   arguments and then some data to transfer. Netcat is now smart enough
  741.   to pick out the first line and build the argument list, and send any
  742.   remaining data across the net to one or multiple ports. The first
  743.   release of netcat had trouble with this -- it called fgets() for the
  744.   command line argument, which behind the scenes does a large read()
  745.   from standard input, perhaps 4096 bytes or so, and feeds that out to
  746.   the fgets() library routine. By the time netcat 1.00 started directly
  747.   read()ing stdin for more data, 4096 bytes of it were gone. It now uses
  748.   raw read() everywhere and does the right thing whether reading from
  749.   files, pipes, or ttys. If you use this for multiple-port connections,
  750.   the single block of data will now be a maximum of 8K minus the first
  751.   line. Improvements have been made to the logic in sending the saved
  752.   chunk to each new port. Note that any command-line arguments hidden
  753.   using this mechanism could still be extracted from a core dump.
  754.  
  755.   When netcat receives an inbound UDP connection, it creates a
  756.   "connected socket" back to the source of the connection so that it can
  757.   also send out data using normal write(). Using this mechanism instead
  758.   of recvfrom/sendto has several advantages -- the read/write select
  759.   loop is simplified, and ICMP errors can in effect be received by
  760.   non-root users. However, it has the subtle side effect that if further
  761.   UDP packets arrive from the caller but from different source ports,
  762.   the listener will not receive them. UDP listen mode on a multihomed
  763.   machine may have similar quirks unless you specifically bind to one of
  764.   its addresses. It is not clear that kernel support for UDP connected
  765.   sockets and/or my understanding of it is entirely complete here, so
  766.   experiment...
  767.  
  768.   You should be aware of some subtleties concerning UDP scanning. If -z
  769.   is on, netcat attempts to send a single null byte to the target port,
  770.   twice, with a small time in between. You can either use the -w
  771.   timeout, or netcat will try to make a "sideline" TCP connection to the
  772.   target to introduce a small time delay equal to the round-trip time
  773.   between you and the target. Note that if you have a -w timeout and -i
  774.   timeout set, BOTH take effect and you wait twice as long. The TCP
  775.   connection is to a normally refused port to minimize traffic, but if
  776.   you notice a UDP fast-scan taking somewhat longer than it should, it
  777.   could be that the target is actually listening on the TCP port. Either
  778.   way, any ICMP port-unreachable messages from the target should have
  779.   arrived in the meantime. The second single-byte UDP probe is then
  780.   sent. Under BSD kernels, the ICMP error is delivered to the "connected
  781.   socket" and the second write returns an error, which tells netcat that
  782.   there is NOT a UDP service there. While Linux seems to be a fortunate
  783.   exception, under many SYSV derived kernels the ICMP is not delivered,
  784.   and netcat starts reporting that *all* the ports are "open" -- clearly
  785.   wrong. [Some systems may not even *have* the "udp connected socket"
  786.   concept, and netcat in its current form will not work for UDP at all.]
  787.   If -z is specified and only one UDP port is probed, netcat's exit
  788.   status reflects whether the connection was "open" or "refused" as with
  789.   TCP.
  790.  
  791.   It may also be that UDP packets are being blocked by filters with no
  792.   ICMP error returns, in which case everything will time out and return
  793.   "open". This all sounds backwards, but that's how UDP works. If you're
  794.   not sure, try "echo w00gumz | nc -u -w 2 target 7" to see if you can
  795.   reach its UDP echo port at all. You should have no trouble using a
  796.   BSD-flavor system to scan for UDP around your own network, although
  797.   flooding a target with the high activity that -z generates will cause
  798.   it to occasionally drop packets and indicate false "opens". A more
  799.   "correct" way to do this is collect and analyze the ICMP errors, as
  800.   does SATAN's "udp_scan" backend, but then again there's no guarantee
  801.   that the ICMP gets back to you either. Udp_scan also does the
  802.   zero-byte probes but is excruciatingly careful to calculate its own
  803.   round-trip timing average and dynamically set its own response
  804.   timeouts along with decoding any ICMP received. Netcat uses a much
  805.   sleazier method which is nonetheless quite effective. Cisco routers
  806.   are known to have a "dead time" in between ICMP responses about
  807.   unreachable UDP ports, so a fast scan of a cisco will show almost
  808.   everything "open". If you are looking for a specific UDP service, you
  809.   can construct a file containing the right bytes to trigger a response
  810.   from the other end and send that as standard input. Netcat will read
  811.   up to 8K of the file and send the same data to every UDP port given.
  812.   Note that you must use a timeout in this case [as would any other UDP
  813.   client application] since the two-write probe only happens if -z is
  814.   specified.
  815.  
  816.   Many telnet servers insist on a specific set of option negotiations
  817.   before presenting a login banner. On a raw connection you will see
  818.   this as small amount of binary gook. My attempts to create fixed input
  819.   bytes to make a telnetd happy worked some places but failed against
  820.   newer BSD-flavor ones, possibly due to timing problems, but there are
  821.   a couple of much better workarounds. First, compile with -DTELNET and
  822.   use -t if you just want to get past the option negotiation and talk to
  823.   something on a telnet port. You will still see the binary gook -- in
  824.   fact you'll see a lot more of it as the options are responded to
  825.   behind the scenes. The telnet responder does NOT update the total byte
  826.   count, or show up in the hex dump -- it just responds negatively to
  827.   any options read from the incoming data stream. If you want to use a
  828.   normal full-blown telnet to get to something but also want some of
  829.   netcat's features involved like settable ports or timeouts, construct
  830.   a tiny "foo" script:
  831.  
  832.           #! /bin/sh
  833.           exec nc -otheroptions targethost 23
  834.  
  835.   and then do
  836.  
  837.  
  838.           nc -l -p someport -e foo localhost &
  839.           telnet localhost someport
  840.  
  841.   and your telnet should connect transparently through the exec'ed
  842.   netcat to the target, using whatever options you supplied in the "foo"
  843.   script. Don't use -t inside the script, or you'll wind up sending
  844.   *two* option responses.
  845.  
  846.   I've observed inconsistent behavior under some Linuxes [perhaps just
  847.   older ones?] when binding in listen mode. Sometimes netcat binds only
  848.   to "localhost" if invoked with no address or port arguments, and
  849.   sometimes it is unable to bind to a specific address for listening if
  850.   something else is already listening on "any". The former problem can
  851.   be worked around by specifying "-s 0.0.0.0", which will do the right
  852.   thing despite netcat claiming that it's listening on [127.0.0.1]. This
  853.   is a known problem -- for example, there's a mention of it in the
  854.   makefile for SOCKS. On the flip side, binding to localhost and sending
  855.   packets to some other machine doesn't work as you'd expect -- they go
  856.   out with the source address of the sending interface instead. The
  857.   Linux kernel contains a specific check to ensure that packets from
  858.   127.0.0.1 are never sent to the wire; other kernels may contain
  859.   similar code. Linux, of course, *still* doesn't support
  860.   source-routing, but they claim that it and many other network
  861.   improvements are at least breathing hard.
  862.  
  863.   There are several possible errors associated with making TCP
  864.   connections, but to specifically see anything other than "refused",
  865.   one must wait the full kernel-defined timeout for a connection to
  866.   fail. Netcat's mechanism of wrapping an alarm timer around the connect
  867.   prevents the *real* network error from being returned -- "errno" at
  868.   that point indicates "interrupted system call" since the connect
  869.   attempt was interrupted. Some old 4.3 BSD kernels would actually
  870.   return things like "host unreachable" immediately if that was the
  871.   case, but most newer kernels seem to wait the full timeout and *then*
  872.   pass back the real error. Go figure. In this case, I'd argue that the
  873.   old way was better, despite those same kernels generally being the
  874.   ones that tear down *established* TCP connections when ICMP-bombed.
  875.  
  876.   Incoming socket options are passed to applications by the kernel in
  877.   the kernel's own internal format. The socket-options structure for
  878.   source-routing contains the "first-hop" IP address first, followed by
  879.   the rest of the real options list. The kernel uses this as is when
  880.   sending reply packets -- the structure is therefore designed to be
  881.   more useful to the kernel than to humans, but the hex dump of it that
  882.   netcat produces is still useful to have.
  883.  
  884.   Kernels treat source-routing options somewhat oddly, but it sort of
  885.   makes sense once one understands what's going on internally. The
  886.   options list of addresses must contain hop1, hop2, ..., destination.
  887.   When a source-routed packet is sent by the kernel [at least BSD], the
  888.   actual destination address becomes irrelevant because it is replaced
  889.   with "hop1", "hop1" is removed from the options list, and all the
  890.   other addresses in the list are shifted up to fill the hole. Thus the
  891.   outbound packet is sent from your chosen source address to the first
  892.   *gateway*, and the options list now contains hop2, ..., destination.
  893.   During all this address shuffling, the kernel does NOT change the
  894.   pointer value, which is why it is useful to be able to set the pointer
  895.   yourself -- you can construct some really bizarre return paths, and
  896.   send your traffic fairly directly to the target but around some larger
  897.   loop on the way back. Some Sun kernels seem to never flip the
  898.   source-route around if it contains less than three hops, never reset
  899.   the pointer anyway, and tries to send the packet [with options
  900.   containing a "completed" source route!!] directly back to the source.
  901.   This is way broken, of course. [Maybe ipforwarding has to be on? I
  902.   haven't had an opportunity to beat on it thoroughly yet.]
  903.  
  904.   "Credits" section: The original idea for netcat fell out of a
  905.   long-standing desire and fruitless search for a tool resembling it and
  906.   having the same features. After reading some other network code and
  907.   realizing just how many cool things about sockets could be controlled
  908.   by the calling user, I started on the basics and the rest fell
  909.   together pretty quickly. Some port-scanning ideas were taken from
  910.   Venema/Farmer's SATAN tool kit, and Pluvius' "pscan" utility. Healthy
  911.   amounts of BSD kernel source were perused in an attempt to dope out
  912.   socket options and source-route handling; additional help was obtained
  913.   from Dave Borman's telnet sources. The select loop is loosely based on
  914.   fairly well-known code from "rsh" and Richard Stevens' "sock" program
  915.   [which itself is sort of a "netcat" with more obscure features], with
  916.   some more paranoid sanity-checking thrown in to guard against the
  917.   distinct likelihood that there are subtleties about such things I
  918.   still don't understand. I found the argument-hiding method cleanly
  919.   implemented in Barrett's "deslogin"; reading the line as input allows
  920.   greater versatility and is much less prone to cause bizarre problems
  921.   than the more common trick of overwriting the argv array. After the
  922.   first release, several people contributed portability fixes; they are
  923.   credited in generic.h and the Makefile. Lauren Burka inspired the
  924.   ascii art for this revised document. Dean Gaudet at Wired supplied a
  925.   precursor to the hex-dump code, and mudge@l0pht.com originally
  926.   experimented with and supplied code for the telnet-options responder.
  927.   Outbound "-e " resulted from a need to quietly bypass a firewall
  928.   installation. Other suggestions and patches have rolled in for which I
  929.   am always grateful, but there are only 26 hours per day and a
  930.   discussion of feature creep near the end of this document.
  931.  
  932.   Netcat was written with the Russian railroad in mind -- conservatively
  933.   built and solid, but it *will* get you there. While the coding style
  934.   is fairly "tight", I have attempted to present it cleanly [keeping
  935.   *my* lines under 80 characters, dammit] and put in plenty of comments
  936.   as to why certain things are done. Items I know to be questionable are
  937.   clearly marked with "XXX". Source code was made to be modified, but
  938.   determining where to start is difficult with some of the tangles of
  939.   spaghetti code that are out there. Here are some of the major points I
  940.   feel are worth mentioning about netcat's internal design, whether or
  941.   not you agree with my approach.
  942.  
  943.   Except for generic.h, which changes to adapt more platforms, netcat is
  944.   a single source file. This has the distinct advantage of only having
  945.   to include headers once and not having to re-declare all my functions
  946.   in a billion different places. I have attempted to contain all the
  947.   gross who's-got-what-.h-file things in one small dumping ground.
  948.   Functions are placed "dependencies-first", such that when the compiler
  949.   runs into the calls later, it already knows the type and arguments and
  950.   won't complain. No function prototyping -- not even the __P(()) crock
  951.   -- is used, since it is more portable and a file of this size is easy
  952.   enough to check manually. Each function has a standard-format comment
  953.   ahead of it, which is easily found using the regexp " :$". I freely
  954.   use gotos. Loops and if-clauses are made as small and non-nested as
  955.   possible, and the ends of same *marked* for clarity [I wish everyone
  956.   would do this!!].
  957.  
  958.   Large structures and buffers are all malloc()ed up on the fly,
  959.   slightly larger than the size asked for and zeroed out. This reduces
  960.   the chances of damage from those "end of the buffer" fencepost errors
  961.   or runaway pointers escaping off the end. These things are permanent
  962.   per run, so nothing needs to be freed until the program exits.
  963.  
  964.   File descriptor zero is always expected to be standard input, even if
  965.   it is closed. If a new network descriptor winds up being zero, a
  966.   different one is asked for which will be nonzero, and fd zero is
  967.   simply left kicking around for the rest of the run. Why? Because
  968.   everything else assumes that stdin is always zero and "netfd" is
  969.   always positive. This may seem silly, but it was a lot easier to code.
  970.   The new fd is obtained directly as a new socket, because trying to
  971.   simply dup() a new fd broke subsequent socket-style use of the new fd
  972.   under Solaris' stupid streams handling in the socket library.
  973.  
  974.   The catch-all message and error handlers are implemented with an ample
  975.   list of phoney arguments to get around various problems with varargs.
  976.   Varargs seems like deliberate obfuscation in the first place, and
  977.   using it would also require use of vfprintf() which not all platforms
  978.   support. The trailing sleep in bail() is to allow output to flush,
  979.   which is sometimes needed if netcat is already on the other end of a
  980.   network connection.
  981.  
  982.   The reader may notice that the section that does DNS lookups seems
  983.   much gnarlier and more confusing than other parts. This is NOT MY
  984.   FAULT. The sockaddr and hostent abstractions are an abortion that
  985.   forces the coder to deal with it. Then again, a lot of BSD kernel code
  986.   looks like similar struct-pointer hell. I try to straighten it out
  987.   somewhat by defining my own HINF structure, containing names,
  988.   ascii-format IP addresses, and binary IP addresses. I fill this
  989.   structure exactly once per host argument, and squirrel everything
  990.   safely away and handy for whatever wants to reference it later.
  991.  
  992.   Where many other network apps use the FIONBIO ioctl to set
  993.   non-blocking I/O on network sockets, netcat uses straightforward
  994.   blocking I/O everywhere. This makes everything very lock-step, relying
  995.   on the network and filesystem layers to feed in data when needed. Data
  996.   read in is completely written out before any more is fetched. This may
  997.   not be quite the right thing to do under some OSes that don't do timed
  998.   select() right, but this remains to be seen.
  999.  
  1000.   The hexdump routine is written to be as fast as possible, which is why
  1001.   it does so much work itself instead of just sprintf()ing everything
  1002.   together. Each dump line is built into a single buffer and atomically
  1003.   written out using the lowest level I/O calls. Further improvements
  1004.   could undoubtedly be made by using writev() and eliminating all
  1005.   sprintf()s, but it seems to fly right along as is. If both exec-a-prog
  1006.   mode and a hexdump file is asked for, the hexdump flag is deliberately
  1007.   turned off to avoid creating random zero-length files. Files are
  1008.   opened in "truncate" mode; if you want "append" mode instead, change
  1009.   the open flags in main().
  1010.  
  1011.   main() may look a bit hairy, but that's only because it has to go down
  1012.   the argv list and handle multiple ports, random mode, and exit status.
  1013.   Efforts have been made to place a minimum of code inside the getopt()
  1014.   loop. Any real work is sent off to functions in what is hopefully a
  1015.   straightforward way.
  1016.  
  1017.   Obligatory vendor-bash: If "nc" had become a standard utility years
  1018.   ago, the commercial vendors would have likely packaged it setuid root
  1019.   and with -DGAPING_SECURITY_HOLE turned on but not documented. It is
  1020.   hoped that netcat will aid people in finding and fixing the no-brainer
  1021.   holes of this sort that keep appearing, by allowing easier
  1022.   experimentation with the "bare metal" of the network layer.
  1023.  
  1024.   It could be argued that netcat already has too many features. I have
  1025.   tried to avoid "feature creep" by limiting netcat's base functionality
  1026.   only to those things which are truly relevant to making network
  1027.   connections and the everyday associated DNS lossage we're used to.
  1028.   Option switches already have slightly overloaded functionality. Random
  1029.   port mode is sort of pushing it. The hex-dump feature went in later
  1030.   because it *is* genuinely useful. The telnet-responder code *almost*
  1031.   verges on the gratuitous, especially since it mucks with the data
  1032.   stream, and is left as an optional piece. Many people have asked for
  1033.   example "how 'bout adding encryption?" and my response is that such
  1034.   things should be separate entities that could pipe their data
  1035.   *through* netcat instead of having their own networking code. I am
  1036.   therefore not completely enthusiastic about adding any more features
  1037.   to this thing, although you are still free to send along any mods you
  1038.   think are useful.
  1039.  
  1040.   Nonetheless, at this point I think of netcat as my tcp/ip swiss army
  1041.   knife, and the numerous companion programs and scripts to go with it
  1042.   as duct tape. Duct tape of course has a light side and a dark side and
  1043.   binds the universe together, and if I wrap enough of it around what
  1044.   I'm trying to accomplish, it *will* work. Alternatively, if netcat is
  1045.   a large hammer, there are many network protocols that are increasingly
  1046.   looking like nails by now...
  1047.  
  1048.   _H* 960320 v1.10 RELEASE -- happy spring!
  1049.  
  1050.                      [Netcat rules the net ----------]
  1051.