{"id":13774877,"url":"https://github.com/mainframed/nc110-omvs","last_synced_at":"2025-05-11T07:30:49.734Z","repository":{"id":7543577,"uuid":"8896077","full_name":"mainframed/NC110-OMVS","owner":"mainframed","description":"NetCat 110 with changes to support OMVS on z/OS","archived":false,"fork":false,"pushed_at":"2013-04-16T05:33:58.000Z","size":224,"stargazers_count":10,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-11-17T09:39:49.844Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mainframed.png","metadata":{"files":{"readme":"README","changelog":"Changelog","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-03-20T04:22:44.000Z","updated_at":"2024-09-26T12:08:16.000Z","dependencies_parsed_at":"2022-08-29T21:20:58.350Z","dependency_job_id":null,"html_url":"https://github.com/mainframed/NC110-OMVS","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mainframed%2FNC110-OMVS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mainframed%2FNC110-OMVS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mainframed%2FNC110-OMVS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mainframed%2FNC110-OMVS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mainframed","download_url":"https://codeload.github.com/mainframed/NC110-OMVS/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253533105,"owners_count":21923363,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T17:01:31.229Z","updated_at":"2025-05-11T07:30:49.406Z","avatar_url":"https://github.com/mainframed.png","language":"C","funding_links":[],"categories":["\u003ca id=\"b35965810463fb97b1ca26d94a8b62f0\"\u003e\u003c/a\u003eNetcat"],"sub_categories":[],"readme":"Netcat 1.10\n===========\t\t\t\t\t\t\t   /\\_/\\\n\t\t\t\t\t\t\t\t  / 0 0 \\\nNetcat is a simple Unix utility which reads and writes data\t ====v====\nacross network connections, using TCP or UDP protocol.\t\t  \\  W  /\nIt is designed to be a reliable \"back-end\" tool that can\t  |     |     _\nbe used directly or easily driven by other programs and\t\t  / ___ \\    /\nscripts.  At the same time, it is a feature-rich network\t / /   \\ \\  |\ndebugging and exploration tool, since it can create almost\t(((-----)))-'\nany kind of connection you would need and has several\t\t /\ninteresting built-in capabilities.  Netcat, or \"nc\" as the\t(      ___\nactual program is named, should have been supplied long ago\t \\__.=|___E\nas another one of those cryptic but standard Unix tools.\t        /\n\nIn the simplest usage, \"nc host port\" creates a TCP connection to the given\nport on the given target host.  Your standard input is then sent to the host,\nand anything that comes back across the connection is sent to your standard\noutput.  This continues indefinitely, until the network side of the connection\nshuts down.  Note that this behavior is different from most other applications\nwhich shut everything down and exit after an end-of-file on the standard input.\n\nNetcat can also function as a server, by listening for inbound connections\non arbitrary ports and then doing the same reading and writing.  With minor\nlimitations, netcat doesn't really care if it runs in \"client\" or \"server\"\nmode -- it still shovels data back and forth until there isn't any more left.\nIn either mode, shutdown can be forced after a configurable time of inactivity\non the network side.\n\nAnd it can do this via UDP too, so netcat is possibly the \"udp telnet-like\"\napplication you always wanted for testing your UDP-mode servers.  UDP, as the\n\"U\" implies, gives less reliable data transmission than TCP connections and\nsome systems may have trouble sending large amounts of data that way, but it's\nstill a useful capability to have.\n\nYou may be asking \"why not just use telnet to connect to arbitrary ports?\"\nValid question, and here are some reasons.  Telnet has the \"standard input\nEOF\" problem, so one must introduce calculated delays in driving scripts to\nallow network output to finish.  This is the main reason netcat stays running\nuntil the *network* side closes.  Telnet also will not transfer arbitrary\nbinary data, because certain characters are interpreted as telnet options and\nare thus removed from the data stream.  Telnet also emits some of its\ndiagnostic messages to standard output, where netcat keeps such things\nreligiously separated from its *output* and will never modify any of the real\ndata in transit unless you *really* want it to.  And of course telnet is\nincapable of listening for inbound connections, or using UDP instead.  Netcat\ndoesn't have any of these limitations, is much smaller and faster than telnet,\nand has many other advantages.\n\nSome of netcat's major features are:\n\n\tOutbound or inbound connections, TCP or UDP, to or from any ports\n\tFull DNS forward/reverse checking, with appropriate warnings\n\tAbility to use any local source port\n\tAbility to use any locally-configured network source address\n\tBuilt-in port-scanning capabilities, with randomizer\n\tBuilt-in loose source-routing capability\n\tCan read command line arguments from standard input\n\tSlow-send mode, one line every N seconds\n\tHex dump of transmitted and received data\n\tOptional ability to let another program service established connections\n\tOptional telnet-options responder\n\nEfforts have been made to have netcat \"do the right thing\" in all its various\nmodes.  If you believe that it is doing the wrong thing under whatever\ncircumstances, please notify me and tell me how you think it should behave.\nIf netcat is not able to do some task you think up, minor tweaks to the code\nwill probably fix that.  It provides a basic and easily-modified template for\nwriting other network applications, and I certainly encourage people to make\ncustom mods and send in any improvements they make to it.  This is the second\nrelease; the overall differences from 1.00 are relatively minor and have mostly\nto do with portability and bugfixes.  Many people provided greatly appreciated\nfixes and comments on the 1.00 release.  Continued feedback from the Internet\ncommunity is always welcome!\n\nNetcat is entirely my own creation, although plenty of other code was used as\nexamples.  It is freely given away to the Internet community in the hope that\nit will be useful, with no restrictions except giving credit where it is due.\nNo GPLs, Berkeley copyrights or any of that nonsense.  The author assumes NO\nresponsibility for how anyone uses it.  If netcat makes you rich somehow and\nyou're feeling generous, mail me a check.  If you are affiliated in any way\nwith Microsoft Network, get a life.  Always ski in control.  Comments,\nquestions, and patches to hobbit@avian.org.\n\nBuilding\n========\n\nCompiling is fairly straightforward.  Examine the Makefile for a SYSTYPE that\nmatches yours, and do \"make \u003csystype\u003e\".  The executable \"nc\" should appear.\nIf there is no relevant SYSTYPE section, try \"generic\".  If you create new\nsections for generic.h and Makefile to support another platform, please follow\nthe given format and mail back the diffs.\n\nThere are a couple of other settable #defines in netcat.c, which you can\ninclude as DFLAGS=\"-DTHIS -DTHAT\" to your \"make\" invocation without having to\nedit the Makefile.  See the following discussions for what they are and do.\n\nIf you want to link against the resolver library on SunOS [recommended] and\nyou have BIND 4.9.x, you may need to change XLIBS=-lresolv in the Makefile to\nXLIBS=\"-lresolv -l44bsd\".\n\nLinux sys/time.h does not really support presetting of FD_SETSIZE; a harmless\nwarning is issued.\n\nSome systems may warn about pointer types for signal().  No problem, though.\n\nExploration of features\n=======================\n\nWhere to begin?  Netcat is at the same time so simple and versatile, it's like\ntrying to describe everything you can do with your Swiss Army knife.  This will\ngo over the basics; you should also read the usage examples and notes later on\nwhich may give you even more ideas about what this sort of tool is good for.\n\nIf no command arguments are given at all, netcat asks for them, reads a line\nfrom standard input, and breaks it up into arguments internally.  This can be\nuseful when driving netcat from certain types of scripts, with the side effect\nof hiding your command line arguments from \"ps\" displays.\n\nThe host argument can be a name or IP address.  If -n is specified, netcat\nwill only accept numeric IP addresses and do no DNS lookups for anything.  If\n-n is not given and -v is turned on, netcat will do a full forward and reverse\nname and address lookup for the host, and warn you about the all-too-common\nproblem of mismatched names in the DNS.  This often takes a little longer for\nconnection setup, but is useful to know about.  There are circumstances under\nwhich this can *save* time, such as when you want to know the name for some IP\naddress and also connect there.  Netcat will just tell you all about it, saving\nthe manual steps of looking up the hostname yourself.  Normally mismatch-\nchecking is case-insensitive per the DNS spec, but you can define ANAL at\ncompile time to make it case-sensitive -- sometimes useful for uncovering minor\nerrors in your own DNS files while poking around your networks.\n\nA port argument is required for outbound connections, and can be numeric or a\nname as listed in /etc/services.  If -n is specified, only numeric arguments\nare valid.  Special syntax and/or more than one port argument cause different\nbehavior -- see details below about port-scanning.\n\nThe -v switch controls the verbosity level of messages sent to standard error.\nYou will probably want to run netcat most of the time with -v turned on, so you\ncan see info about the connections it is trying to make.  You will probably\nalso want to give a smallish -w argument, which limits the time spent trying to\nmake a connection.  I usually alias \"nc\" to \"nc -v -w 3\", which makes it\nfunction just about the same for things I would otherwise use telnet to do.\nThe timeout is easily changed by a subsequent -w argument which overrides the\nearlier one.  Specifying -v more than once makes diagnostic output MORE\nverbose.  If -v is not specified at all, netcat silently does its work unless\nsome error happens, whereupon it describes the error and exits with a nonzero\nstatus.  Refused network connections are generally NOT considered to be errors,\nunless you only asked for a single TCP port and it was refused.\n\nNote that -w also sets the network inactivity timeout.  This does not have any\neffect until standard input closes, but then if nothing further arrives from\nthe network in the next \u003ctimeout\u003e seconds, netcat tries to read the net once\nmore for good measure, and then closes and exits.  There are a lot of network\nservices now that accept a small amount of input and return a large amount of\noutput, such as Gopher and Web servers, which is the main reason netcat was\nwritten to \"block\" on the network staying open rather than standard input.\nHandling the timeout this way gives uniform behavior with network servers that\n*don't* close by themselves until told to.\n\nUDP connections are opened instead of TCP when -u is specified.  These aren't\nreally \"connections\" per se since UDP is a connectionless protocol, although\nnetcat does internally use the \"connected UDP socket\" mechanism that most\nkernels support.  Although netcat claims that an outgoing UDP connection is\n\"open\" immediately, no data is sent until something is read from standard\ninput.  Only thereafter is it possible to determine whether there really is a\nUDP server on the other end, and often you just can't tell.  Most UDP protocols\nuse timeouts and retries to do their thing and in many cases won't bother\nanswering at all, so you should specify a timeout and hope for the best.  You\nwill get more out of UDP connections if standard input is fed from a source\nof data that looks like various kinds of server requests.\n\nTo obtain a hex dump file of the data sent either way, use \"-o logfile\".  The\ndump lines begin with \"\u003c\" or \"\u003e\" to respectively indicate \"from the net\" or\n\"to the net\", and contain the total count per direction, and hex and ascii\nrepresentations of the traffic.  Capturing a hex dump naturally slows netcat\ndown a bit, so don't use it where speed is critical.\n\nNetcat can bind to any local port, subject to privilege restrictions and ports\nthat are already in use.  It is also possible to use a specific local network\nsource address if it is that of a network interface on your machine.  [Note:\nthis does not work correctly on all platforms.]  Use \"-p portarg\" to grab a\nspecific local port, and \"-s ip-addr\" or \"-s name\" to have that be your source\nIP address.  This is often referred to as \"anchoring the socket\".  Root users\ncan grab any unused source port including the \"reserved\" ones less than 1024.\nAbsence of -p will bind to whatever unused port the system gives you, just like\nany other normal client connection, unless you use -r [see below].\n\nListen mode will cause netcat to wait for an inbound connection, and then the\nsame data transfer happens.  Thus, you can do \"nc -l -p 1234 \u003c filename\" and\nwhen someone else connects to your port 1234, the file is sent to them whether\nthey wanted it or not.  Listen mode is generally used along with a local port\nargument -- this is required for UDP mode, while TCP mode can have the system\nassign one and tell you what it is if -v is turned on.  If you specify a target\nhost and optional port in listen mode, netcat will accept an inbound connection\nonly from that host and if you specify one, only from that foreign source port.\nIn verbose mode you'll be informed about the inbound connection, including what\naddress and port it came from, and since listening on \"any\" applies to several\npossibilities, which address it came *to* on your end.  If the system supports\nIP socket options, netcat will attempt to retrieve any such options from an\ninbound connection and print them out in hex.\n\nIf netcat is compiled with -DGAPING_SECURITY_HOLE, the -e argument specifies\na program to exec after making or receiving a successful connection.  In the\nlistening mode, this works similarly to \"inetd\" but only for a single instance.\nUse with GREAT CARE.  This piece of the code is normally not enabled; if you\nknow what you're doing, have fun.  This hack also works in UDP mode.  Note that\nyou can only supply -e with the name of the program, but no arguments.  If you\nwant to launch something with an argument list, write a two-line wrapper script\nor just use inetd like always.\n\nIf netcat is compiled with -DTELNET, the -t argument enables it to respond\nto telnet option negotiation [always in the negative, i.e. DONT or WONT].\nThis allows it to connect to a telnetd and get past the initial negotiation\nfar enough to get a login prompt from the server.  Since this feature has\nthe potential to modify the data stream, it is not enabled by default.  You\nhave to understand why you might need this and turn on the #define yourself.\n\nData from the network connection is always delivered to standard output as\nefficiently as possible, using large 8K reads and writes.  Standard input is\nnormally sent to the net the same way, but the -i switch specifies an \"interval\ntime\" which slows this down considerably.  Standard input is still read in\nlarge batches, but netcat then tries to find where line breaks exist and sends\none line every interval time.  Note that if standard input is a terminal, data\nis already read line by line, so unless you make the -i interval rather long,\nwhat you type will go out at a fairly normal rate.  -i is really designed\nfor use when you want to \"measure out\" what is read from files or pipes.\n\nPort-scanning is a popular method for exploring what's out there.  Netcat\naccepts its commands with options first, then the target host, and everything\nthereafter is interpreted as port names or numbers, or ranges of ports in M-N\nsyntax.  CAVEAT: some port names in /etc/services contain hyphens -- netcat\ncurrently will not correctly parse those, so specify ranges using numbers if\nyou can.  If more than one port is thus specified, netcat connects to *all* of\nthem, sending the same batch of data from standard input [up to 8K worth] to\neach one that is successfully connected to.  Specifying multiple ports also\nsuppresses diagnostic messages about refused connections, unless -v is\nspecified twice for \"more verbosity\".  This way you normally get notified only\nabout genuinely open connections.  Example: \"nc -v -w 2 -z target 20-30\" will\ntry connecting to every port between 20 and 30 [inclusive] at the target, and\nwill likely inform you about an FTP server, telnet server, and mailer along the\nway.  The -z switch prevents sending any data to a TCP connection and very\nlimited probe data to a UDP connection, and is thus useful as a fast scanning\nmode just to see what ports the target is listening on.  To limit scanning\nspeed if desired, -i will insert a delay between each port probe.  There are\nsome pitfalls with regard to UDP scanning, described later, but in general it\nworks well.\n\nFor each range of ports specified, scanning is normally done downward within\nthat range.  If the -r switch is used, scanning hops randomly around within\nthat range and reports open ports as it finds them.  [If you want them listed\nin order regardless, pipe standard error through \"sort\"...]  In addition, if\nrandom mode is in effect, the local source ports are also randomized.  This\nprevents netcat from exhibiting any kind of regular pattern in its scanning.\nYou can exert fairly fine control over your scan by judicious use of -r and\nselected port ranges to cover.  If you use -r for a single connection, the\nsource port will have a random value above 8192, rather than the next one the\nkernel would have assigned you.  Note that selecting a specific local port\nwith -p overrides any local-port randomization.\n\nMany people are interested in testing network connectivity using IP source\nrouting, even if it's only to make sure their own firewalls are blocking\nsource-routed packets.  On systems that support it, the -g switch can be used\nmultiple times [up to 8] to construct a loose-source-routed path for your\nconnection, and the -G argument positions the \"hop pointer\" within the list.\nIf your network allows source-routed traffic in and out, you can test\nconnectivity to your own services via remote points in the internet.  Note that\nalthough newer BSD-flavor telnets also have source-routing capability, it isn't\nclearly documented and the command syntax is somewhat clumsy.  Netcat's\nhandling of \"-g\" is modeled after \"traceroute\".\n\nNetcat tries its best to behave just like \"cat\".  It currently does nothing to\nterminal input modes, and does no end-of-line conversion.  Standard input from\na terminal is read line by line with normal editing characters in effect.  You\ncan freely suspend out of an interactive connection and resume.  ^C or whatever\nyour interrupt character is will make netcat close the network connection and\nexit.  A switch to place the terminal in raw mode has been considered, but so\nfar has not been necessary.  You can send raw binary data by reading it out of\na file or piping from another program, so more meaningful effort would be spent\nwriting an appropriate front-end driver.\n\nNetcat is not an \"arbitrary packet generator\", but the ability to talk to raw\nsockets and/or nit/bpf/dlpi may appear at some point.  Such things are clearly\nuseful; I refer you to Darren Reed's excellent ip_filter package, which now\nincludes a tool to construct and send raw packets with any contents you want.\n\nExample uses -- the light side\n==============================\n\nAgain, this is a very partial list of possibilities, but it may get you to\nthink up more applications for netcat.  Driving netcat with simple shell or\nexpect scripts is an easy and flexible way to do fairly complex tasks,\nespecially if you're not into coding network tools in C.  My coding isn't\nparticularly strong either [although undoubtedly better after writing this\nthing!], so I tend to construct bare-metal tools like this that I can trivially\nplug into other applications.  Netcat doubles as a teaching tool -- one can\nlearn a great deal about more complex network protocols by trying to simulate\nthem through raw connections!\n\nAn example of netcat as a backend for something else is the shell-script\nWeb browser, which simply asks for the relevant parts of a URL and pipes\n\"GET /what/ever\" into a netcat connection to the server.  I used to do this\nwith telnet, and had to use calculated sleep times and other stupidity to\nkludge around telnet's limitations.  Netcat guarantees that I get the whole\npage, and since it transfers all the data unmodified, I can even pull down\nbinary image files and display them elsewhere later.  Some folks may find the\nidea of a shell-script web browser silly and strange, but it starts up and\ngets me my info a hell of a lot faster than a GUI browser and doesn't hide\nany contents of links and forms and such.  This is included, as scripts/web,\nalong with several other web-related examples.\n\nNetcat is an obvious replacement for telnet as a tool for talking to daemons.\nFor example, it is easier to type \"nc host 25\", talk to someone's mailer, and\njust ^C out than having to type ^]c or QUIT as telnet would require you to do.\nYou can quickly catalog the services on your network by telling netcat to\nconnect to well-known services and collect greetings, or at least scan for open\nports.  You'll probably want to collect netcat's diagnostic messages in your\noutput files, so be sure to include standard error in the output using\n`\u003e\u0026 file' in *csh or `\u003e file 2\u003e\u00261' in bourne shell.\n\nA scanning example: \"echo QUIT | nc -v -w 5 target 20-250 500-600 5990-7000\"\nwill inform you about a target's various well-known TCP servers, including\nr-services, X, IRC, and maybe a few you didn't expect.  Sending in QUIT and\nusing the timeout will almost guarantee that you see some kind of greeting or\nerror from each service, which usually indicates what it is and what version.\n[Beware of the \"chargen\" port, though...]  SATAN uses exactly this technique to\ncollect host information, and indeed some of the ideas herein were taken from\nthe SATAN backend tools.  If you script this up to try every host in your\nsubnet space and just let it run, you will not only see all the services,\nyou'll find out about hosts that aren't correctly listed in your DNS.  Then you\ncan compare new snapshots against old snapshots to see changes.  For going\nafter particular services, a more intrusive example is in scripts/probe.\n\nNetcat can be used as a simple data transfer agent, and it doesn't really\nmatter which end is the listener and which end is the client -- input at one\nside arrives at the other side as output.  It is helpful to start the listener\nat the receiving side with no timeout specified, and then give the sending side\na small timeout.  That way the listener stays listening until you contact it,\nand after data stops flowing the client will time out, shut down, and take the\nlistener with it.  Unless the intervening network is fraught with problems,\nthis should be completely reliable, and you can always increase the timeout.  A\ntypical example of something \"rsh\" is often used for: on one side,\n\n\tnc -l -p 1234 | uncompress -c | tar xvfp -\n\nand then on the other side\n\n\ttar cfp - /some/dir | compress -c | nc -w 3 othermachine 1234\n\nwill transfer the contents of a directory from one machine to another, without\nhaving to worry about .rhosts files, user accounts, or inetd configurations\nat either end.  Again, it matters not which is the listener or receiver; the\n\"tarring\" machine could just as easily be running the listener instead.  One\ncould conceivably use a scheme like this for backups, by having cron-jobs fire\nup listeners and backup handlers [which can be restricted to specific addresses\nand ports between each other] and pipe \"dump\" or \"tar\" on one machine to \"dd\nof=/dev/tapedrive\" on another as usual.  Since netcat returns a nonzero exit\nstatus for a denied listener connection, scripts to handle such tasks could\neasily log and reject connect attempts from third parties, and then retry.\n\nAnother simple data-transfer example: shipping things to a PC that doesn't have\nany network applications yet except a TCP stack and a web browser.  Point the\nbrowser at an arbitrary port on a Unix server by telling it to download\nsomething like http://unixbox:4444/foo, and have a listener on the Unix side\nready to ship out a file when the connect comes in.  The browser may pervert\nbinary data when told to save the URL, but you can dig the raw data out of\nthe on-disk cache.\n\nIf you build netcat with GAPING_SECURITY_HOLE defined, you can use it as an\n\"inetd\" substitute to test experimental network servers that would otherwise\nrun under \"inetd\".  A script or program will have its input and output hooked\nto the network the same way, perhaps sans some fancier signal handling.  Given\nthat most network services do not bind to a particular local address, whether\nthey are under \"inetd\" or not, it is possible for netcat avoid the \"address\nalready in use\" error by binding to a specific address.  This lets you [as\nroot, for low ports] place netcat \"in the way\" of a standard service, since\ninbound connections are generally sent to such specifically-bound listeners\nfirst and fall back to the ones bound to \"any\".  This allows for a one-off\nexperimental simulation of some service, without having to screw around with\ninetd.conf.  Running with -v turned on and collecting a connection log from\nstandard error is recommended.\n\nNetcat as well can make an outbound connection and then run a program or script\non the originating end, with input and output connected to the same network\nport.  This \"inverse inetd\" capability could enhance the backup-server concept\ndescribed above or help facilitate things such as a \"network dialback\" concept.\nThe possibilities are many and varied here; if such things are intended as\nsecurity mechanisms, it may be best to modify netcat specifically for the\npurpose instead of wrapping such functions in scripts.\n\nSpeaking of inetd, netcat will function perfectly well *under* inetd as a TCP\nconnection redirector for inbound services, like a \"plug-gw\" without the\nauthentication step.  This is very useful for doing stuff like redirecting\ntraffic through your firewall out to other places like web servers and mail\nhubs, while posing no risk to the firewall machine itself.  Put netcat behind\ninetd and tcp_wrappers, perhaps thusly:\n\n\twww stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80\n\nand you have a simple and effective \"application relay\" with access control\nand logging.  Note use of the wait time as a \"safety\" in case realwww isn't\nreachable or the calling user aborts the connection -- otherwise the relay may\nhang there forever.\n\nYou can use netcat to generate huge amounts of useless network data for\nvarious performance testing.  For example, doing\n\n\tyes AAAAAAAAAAAAAAAAAAAAAA | nc -v -v -l -p 2222 \u003e /dev/null\n\non one side and then hitting it with\n\n\tyes BBBBBBBBBBBBBBBBBBBBBB | nc othermachine 2222 \u003e /dev/null\n\nfrom another host will saturate your wires with A's and B's.  The \"very\nverbose\" switch usage will tell you how many of each were sent and received\nafter you interrupt either side.  Using UDP mode produces tremendously MORE\ntrash per unit time in the form of fragmented 8 Kbyte mobygrams -- enough to\nstress-test kernels and network interfaces.  Firing random binary data into\nvarious network servers may help expose bugs in their input handling, which\nnowadays is a popular thing to explore.  A simple example data-generator is\ngiven in data/data.c included in this package, along with a small collection\nof canned input files to generate various packet contents.  This program is\ndocumented in its beginning comments, but of interest here is using \"%r\" to\ngenerate random bytes at well-chosen points in a data stream.  If you can\ncrash your daemon, you likely have a security problem.\n\nThe hex dump feature may be useful for debugging odd network protocols,\nespecially if you don't have any network monitoring equipment handy or aren't\nroot where you'd need to run \"tcpdump\" or something.  Bind a listening netcat\nto a local port, and have it run a script which in turn runs another netcat\nto the real service and captures the hex dump to a log file.  This sets up a\ntransparent relay between your local port and wherever the real service is.\nBe sure that the script-run netcat does *not* use -v, or the extra info it\nsends to standard error may confuse the protocol.  Note also that you cannot\nhave the \"listen/exec\" netcat do the data capture, since once the connection\narrives it is no longer netcat that is running.\n\nBinding to an arbitrary local port allows you to simulate things like r-service\nclients, if you are root locally.  For example, feeding \"^@root^@joe^@pwd^@\"\n[where ^@ is a null, and root/joe could be any other local/remote username\npair] into a \"rsh\" or \"rlogin\" server, FROM your port 1023 for example,\nduplicates what the server expects to receive.  Thus, you can test for insecure\n.rhosts files around your network without having to create new user accounts on\nyour client machine.  The program data/rservice.c can aid this process by\nconstructing the \"rcmd\" protocol bytes.  Doing this also prevents \"rshd\" from\ntrying to create that separate standard-error socket and still gives you an\ninput path, as opposed to the usual action of \"rsh -n\".  Using netcat for\nthings like this can be really useful sometimes, because rsh and rlogin\ngenerally want a host *name* as an argument and won't accept IP addresses.  If\nyour client-end DNS is hosed, as may be true when you're trying to extract\nbackup sets on to a dumb client, \"netcat -n\" wins where normal rsh/rlogin is\nuseless.\n\nIf you are unsure that a remote syslogger is working, test it with netcat.\nMake a UDP connection to port 514 and type in \"\u003c0\u003emessage\", which should\ncorrespond to \"kern.emerg\" and cause syslogd to scream into every file it has\nopen [and possibly all over users' terminals].  You can tame this down by\nusing a different number and use netcat inside routine scripts to send syslog\nmessages to places that aren't configured in syslog.conf.  For example,\n\"echo '\u003c38\u003emessage' | nc -w 1 -u loggerhost 514\" should send to auth.notice\non loggerhost.  The exact number may vary; check against your syslog.h first.\n\nNetcat provides several ways for you to test your own packet filters.  If you\nbind to a port normally protected against outside access and make a connection\nto somewhere outside your own network, the return traffic will be coming to\nyour chosen port from the \"outside\" and should be blocked.  TCP may get through\nif your filter passes all \"ack syn\", but it shouldn't be even doing that to low\nports on your network.  Remember to test with UDP traffic as well!  If your\nfilter passes at least outbound source-routed IP packets, bouncing a connection\nback to yourself via some gateway outside your network will create \"incoming\"\ntraffic with your source address, which should get dropped by a correctly\nconfigured anti-spoofing filter.  This is a \"non-test\" if you're also dropping\nsource-routing, but it's good to be able to test for that too.  Any packet\nfilter worth its salt will be blocking source-routed packets in both\ndirections, but you never know what interesting quirks you might turn up by\nplaying around with source ports and addresses and watching the wires with a\nnetwork monitor.\n\nYou can use netcat to protect your own workstation's X server against outside\naccess.  X is stupid enough to listen for connections on \"any\" and never tell\nyou when new connections arrive, which is one reason it is so vulnerable.  Once\nyou have all your various X windows up and running you can use netcat to bind\njust to your ethernet address and listen to port 6000.  Any new connections\nfrom outside the machine will hit netcat instead your X server, and you get a\nlog of who's trying.  You can either tell netcat to drop the connection, or\nperhaps run another copy of itself to relay to your actual X server on\n\"localhost\".  This may not work for dedicated X terminals, but it may be\npossible to authorize your X terminal only for its boot server, and run a relay\nnetcat over on the server that will in turn talk to your X terminal.  Since\nnetcat only handles one listening connection per run, make sure that whatever\nway you rig it causes another one to run and listen on 6000 soon afterward, or\nyour real X server will be reachable once again.  A very minimal script just\nto protect yourself could be\n\n\twhile true ; do\n\t  nc -v -l -s \u003cyour-addr\u003e -p 6000 localhost 2\n\tdone\n\nwhich causes netcat to accept and then close any inbound connection to your\nworkstation's normal ethernet address, and another copy is immediately run by\nthe script.  Send standard error to a file for a log of connection attempts.\nIf your system can't do the \"specific bind\" thing all is not lost; run your\nX server on display \":1\" or port 6001, and netcat can still function as a probe\nalarm by listening on 6000.\n\nDoes your shell-account provider allow personal Web pages, but not CGI scripts?\nYou can have netcat listen on a particular port to execute a program or script\nof your choosing, and then just point to the port with a URL in your homepage.\nThe listener could even exist on a completely different machine, avoiding the\npotential ire of the homepage-host administrators.  Since the script will get\nthe raw browser query as input it won't look like a typical CGI script, and\nsince it's running under your UID you need to write it carefully.  You may want\nto write a netcat-based script as a wrapper that reads a query and sets up\nenvironment variables for a regular CGI script.  The possibilities for using\nnetcat and scripts to handle Web stuff are almost endless.  Again, see the\nexamples under scripts/.\n\nExample uses -- the dark side\n=============================\n\nEqual time is deserved here, since a versatile tool like this can be useful\nto any Shade of Hat.  I could use my Victorinox to either fix your car or\ndisassemble it, right?  You can clearly use something like netcat to attack\nor defend -- I don't try to govern anyone's social outlook, I just build tools.\nRegardless of your intentions, you should still be aware of these threats to\nyour own systems.\n\nThe first obvious thing is scanning someone *else's* network for vulnerable\nservices.  Files containing preconstructed data, be it exploratory or\nexploitive, can be fed in as standard input, including command-line arguments\nto netcat itself to keep \"ps\" ignorant of your doings.  The more random the\nscanning, the less likelihood of detection by humans, scan-detectors, or\ndynamic filtering, and with -i you'll wait longer but avoid loading down the\ntarget's network.  Some examples for crafting various standard UDP probes are\ngiven in data/*.d.\n\nSome configurations of packet filters attempt to solve the FTP-data problem by\njust allowing such connections from the outside.  These come FROM port 20, TO\nhigh TCP ports inside -- if you locally bind to port 20, you may find yourself\nable to bypass filtering in some cases.  Maybe not to low ports \"inside\", but\nperhaps to TCP NFS servers, X servers, Prospero, ciscos that listen on 200x\nand 400x...  Similar bypassing may be possible for UDP [and maybe TCP too] if a\nconnection comes from port 53; a filter may assume it's a nameserver response.\n\nUsing -e in conjunction with binding to a specific address can enable \"server\ntakeover\" by getting in ahead of the real ones, whereupon you can snarf data\nsent in and feed your own back out.  At the very least you can log a hex dump\nof someone else's session.  If you are root, you can certainly use -s and -e to\nrun various hacked daemons without having to touch inetd.conf or the real\ndaemons themselves.  You may not always have the root access to deal with low\nports, but what if you are on a machine that also happens to be an NFS server?\nYou might be able to collect some interesting things from port 2049, including\nlocal file handles.  There are several other servers that run on high ports\nthat are likely candidates for takeover, including many of the RPC services on\nsome platforms [yppasswdd, anyone?].  Kerberos tickets, X cookies, and IRC\ntraffic also come to mind.  RADIUS-based terminal servers connect incoming\nusers to shell-account machines on a high port, usually 1642 or thereabouts.\nSOCKS servers run on 1080.  Do \"netstat -a\" and get creative.\n\nThere are some daemons that are well-written enough to bind separately to all\nthe local interfaces, possibly with an eye toward heading off this sort of\nproblem.  Named from recent BIND releases, and NTP, are two that come to mind.\nNetstat will show these listening on address.53 instead of *.53.  You won't\nbe able to get in front of these on any of the real interface addresses, which\nof course is especially interesting in the case of named, but these servers\nsometimes forget about things like \"alias\" interface addresses or interfaces\nthat appear later on such as dynamic PPP links.  There are some hacked web\nservers and versions of \"inetd\" floating around that specifically bind as well,\nbased on a configuration file -- these generally *are* bound to alias addresses\nto offer several different address-based services from one machine.\n\nUsing -e to start a remote backdoor shell is another obvious sort of thing,\neasier than constructing a file for inetd to listen on \"ingreslock\" or\nsomething, and you can access-control it against other people by specifying a\nclient host and port.  Experience with this truly demonstrates how fragile the\nbarrier between being \"logged in\" or not really is, and is further expressed by\nscripts/bsh.  If you're already behind a firewall, it may be easier to make an\n*outbound* connection and then run a shell; a small wrapper script can\nperiodically try connecting to a known place and port, you can later listen\nthere until the inbound connection arrives, and there's your shell.  Running\na shell via UDP has several interesting features, although be aware that once\n\"connected\", the UDP stub sockets tend to show up in \"netstat\" just like TCP\nconnections and may not be quite as subtle as you wanted.  Packets may also be\nlost, so use TCP if you need reliable connections.  But since UDP is\nconnectionless, a hookup of this sort will stick around almost forever, even if\nyou ^C out of netcat or do a reboot on your side, and you only need to remember\nthe ports you used on both ends to reestablish.  And outbound UDP-plus-exec\nconnection creates the connected socket and starts the program immediately.  On\na listening UDP connection, the socket is created once a first packet is\nreceived.  In either case, though, such a \"connection\" has the interesting side\neffect that only your client-side IP address and [chosen?] source port will\nthereafter be able to talk to it.  Instant access control!  A non-local third\nparty would have to do ALL of the following to take over such a session:\n\n\tforge UDP with your source address [trivial to do; see below]\n\tguess the port numbers of BOTH ends, or sniff the wire for them\n\tarrange to block ICMP or UDP return traffic between it and your real\n\t  source, so the session doesn't die with a network write error.\n\nThe companion program data/rservice.c is helpful in scripting up any sort of\nr-service username or password guessing attack.  The arguments to \"rservice\"\nare simply the strings that get null-terminated and passed over an \"rcmd\"-style\nconnection, with the assumption that the client does not need a separate\nstandard-error port.  Brute-force password banging is best done via \"rexec\" if\nit is available since it is less likely to log failed attempts.  Thus, doing\n\"rservice joe joespass pwd | nc target exec\" should return joe's home dir if\nthe password is right, or \"Permission denied.\"  Plug in a dictionary and go to\ntown.  If you're attacking rsh/rlogin, remember to be root and bind to a port\nbetween 512 and 1023 on your end, and pipe in \"rservice joe joe pwd\" and such.\n\nNetcat can prevent inadvertently sending extra information over a telnet\nconnection.  Use \"nc -t\" in place of telnet, and daemons that try to ask for\nthings like USER and TERM environment variables will get no useful answers, as\nthey otherwise would from a more recent telnet program.  Some telnetds actually\ntry to collect this stuff and then plug the USER variable into \"login\" so that\nthe caller is then just asked for a password!  This mechanism could cause a\nlogin attempt as YOUR real username to be logged over there if you use a\nBorman-based telnet instead of \"nc -t\".\n\nGot an unused network interface configured in your kernel [e.g. SLIP], or\nsupport for alias addresses?  Ifconfig one to be any address you like, and bind\nto it with -s to enable all sorts of shenanigans with bogus source addresses.\nThe interface probably has to be UP before this works; some SLIP versions\nneed a far-end address before this is true.  Hammering on UDP services is then\na no-brainer.  What you can do to an unfiltered syslog daemon should be fairly\nobvious; trimming the conf file can help protect against it.  Many routers out\nthere still blindly believe what they receive via RIP and other routing\nprotocols.  Although most UDP echo and chargen servers check if an incoming\npacket was sent from *another* \"internal\" UDP server, there are many that still\ndo not, any two of which [or many, for that matter] could keep each other\nentertained for hours at the expense of bandwidth.  And you can always make\nsomeone wonder why she's being probed by nsa.gov.\n\nYour TCP spoofing possibilities are mostly limited to destinations you can\nsource-route to while locally bound to your phony address.  Many sites block\nsource-routed packets these days for precisely this reason.  If your kernel\ndoes oddball things when sending source-routed packets, try moving the pointer\naround with -G.  You may also have to fiddle with the routing on your own\nmachine before you start receiving packets back.  Warning: some machines still\nsend out traffic using the source address of the outbound interface, regardless\nof your binding, especially in the case of localhost.  Check first.  If you can\nopen a connection but then get no data back from it, the target host is\nprobably killing the IP options on its end [this is an option inside TCP\nwrappers and several other packages], which happens after the 3-way handshake\nis completed.  If you send some data and observe the \"send-q\" side of \"netstat\"\nfor that connection increasing but never getting sent, that's another symptom.\nBeware: if Sendmail 8.7.x detects a source-routed SMTP connection, it extracts\nthe hop list and sticks it in the Received: header!\n\nSYN bombing [sometimes called \"hosing\"] can disable many TCP servers, and if\nyou hit one often enough, you can keep it unreachable for days.  As is true of\nmany other denial-of-service attacks, there is currently no defense against it\nexcept maybe at the human level.  Making kernel SOMAXCONN considerably larger\nthan the default and the half-open timeout smaller can help, and indeed some\npeople running large high-performance web servers have *had* to do that just to\nhandle normal traffic.  Taking out mailers and web servers is sociopathic, but\non the other hand it is sometimes useful to be able to, say, disable a site's\nidentd daemon for a few minutes.  If someone realizes what is going on,\nbacktracing will still be difficult since the packets have a phony source\naddress, but calls to enough ISP NOCs might eventually pinpoint the source.\nIt is also trivial for a clueful ISP to watch for or even block outgoing\npackets with obviously fake source addresses, but as we know many of them are\nnot clueful or willing to get involved in such hassles.  Besides, outbound\npackets with an [otherwise unreachable] source address in one of their net\nblocks would look fairly legitimate.\n\nNotes\n=====\n\nA discussion of various caveats, subtleties, and the design of the innards.\n\nAs of version 1.07 you can construct a single file containing command arguments\nand then some data to transfer.  Netcat is now smart enough to pick out the\nfirst line and build the argument list, and send any remaining data across the\nnet to one or multiple ports.  The first release of netcat had trouble with\nthis -- it called fgets() for the command line argument, which behind the\nscenes does a large read() from standard input, perhaps 4096 bytes or so, and\nfeeds that out to the fgets() library routine.  By the time netcat 1.00 started\ndirectly read()ing stdin for more data, 4096 bytes of it were gone.  It now\nuses raw read() everywhere and does the right thing whether reading from files,\npipes, or ttys.  If you use this for multiple-port connections, the single\nblock of data will now be a maximum of 8K minus the first line.  Improvements\nhave been made to the logic in sending the saved chunk to each new port.  Note\nthat any command-line arguments hidden using this mechanism could still be\nextracted from a core dump.\n\nWhen netcat receives an inbound UDP connection, it creates a \"connected socket\"\nback to the source of the connection so that it can also send out data using\nnormal write().  Using this mechanism instead of recvfrom/sendto has several\nadvantages -- the read/write select loop is simplified, and ICMP errors can in\neffect be received by non-root users.  However, it has the subtle side effect\nthat if further UDP packets arrive from the caller but from different source\nports, the listener will not receive them.  UDP listen mode on a multihomed\nmachine may have similar quirks unless you specifically bind to one of its\naddresses.  It is not clear that kernel support for UDP connected sockets\nand/or my understanding of it is entirely complete here, so experiment...\n\nYou should be aware of some subtleties concerning UDP scanning.  If -z is on,\nnetcat attempts to send a single null byte to the target port, twice, with a\nsmall time in between.  You can either use the -w timeout, or netcat will try\nto make a \"sideline\" TCP connection to the target to introduce a small time\ndelay equal to the round-trip time between you and the target.  Note that if\nyou have a -w timeout and -i timeout set, BOTH take effect and you wait twice\nas long.  The TCP connection is to a normally refused port to minimize traffic,\nbut if you notice a UDP fast-scan taking somewhat longer than it should, it\ncould be that the target is actually listening on the TCP port.  Either way,\nany ICMP port-unreachable messages from the target should have arrived in the\nmeantime.  The second single-byte UDP probe is then sent.  Under BSD kernels,\nthe ICMP error is delivered to the \"connected socket\" and the second write\nreturns an error, which tells netcat that there is NOT a UDP service there.\nWhile Linux seems to be a fortunate exception, under many SYSV derived kernels\nthe ICMP is not delivered, and netcat starts reporting that *all* the ports are\n\"open\" -- clearly wrong.  [Some systems may not even *have* the \"udp connected\nsocket\" concept, and netcat in its current form will not work for UDP at all.]\nIf -z is specified and only one UDP port is probed, netcat's exit status\nreflects whether the connection was \"open\" or \"refused\" as with TCP.\n\nIt may also be that UDP packets are being blocked by filters with no ICMP error\nreturns, in which case everything will time out and return \"open\".  This all\nsounds backwards, but that's how UDP works.  If you're not sure, try \"echo\nw00gumz | nc -u -w 2 target 7\" to see if you can reach its UDP echo port at\nall.  You should have no trouble using a BSD-flavor system to scan for UDP\naround your own network, although flooding a target with the high activity that\n-z generates will cause it to occasionally drop packets and indicate false\n\"opens\".  A more \"correct\" way to do this is collect and analyze the ICMP\nerrors, as does SATAN's \"udp_scan\" backend, but then again there's no guarantee\nthat the ICMP gets back to you either.  Udp_scan also does the zero-byte\nprobes but is excruciatingly careful to calculate its own round-trip timing\naverage and dynamically set its own response timeouts along with decoding any\nICMP received.  Netcat uses a much sleazier method which is nonetheless quite\neffective.  Cisco routers are known to have a \"dead time\" in between ICMP\nresponses about unreachable UDP ports, so a fast scan of a cisco will show\nalmost everything \"open\".  If you are looking for a specific UDP service, you\ncan construct a file containing the right bytes to trigger a response from the\nother end and send that as standard input.  Netcat will read up to 8K of the\nfile and send the same data to every UDP port given.  Note that you must use a\ntimeout in this case [as would any other UDP client application] since the\ntwo-write probe only happens if -z is specified.\n\nMany telnet servers insist on a specific set of option negotiations before\npresenting a login banner.  On a raw connection you will see this as small\namount of binary gook.  My attempts to create fixed input bytes to make a\ntelnetd happy worked some places but failed against newer BSD-flavor ones,\npossibly due to timing problems, but there are a couple of much better\nworkarounds.  First, compile with -DTELNET and use -t if you just want to get\npast the option negotiation and talk to something on a telnet port.  You will\nstill see the binary gook -- in fact you'll see a lot more of it as the options\nare responded to behind the scenes.  The telnet responder does NOT update the\ntotal byte count, or show up in the hex dump -- it just responds negatively to\nany options read from the incoming data stream.  If you want to use a normal\nfull-blown telnet to get to something but also want some of netcat's features\ninvolved like settable ports or timeouts, construct a tiny \"foo\" script:\n\n\t#! /bin/sh\n\texec nc -otheroptions targethost 23\n\nand then do\n\n\tnc -l -p someport -e foo localhost \u0026\n\ttelnet localhost someport\n\nand your telnet should connect transparently through the exec'ed netcat to\nthe target, using whatever options you supplied in the \"foo\" script.  Don't\nuse -t inside the script, or you'll wind up sending *two* option responses.\n\nI've observed inconsistent behavior under some Linuxes [perhaps just older\nones?] when binding in listen mode.  Sometimes netcat binds only to \"localhost\"\nif invoked with no address or port arguments, and sometimes it is unable to\nbind to a specific address for listening if something else is already listening\non \"any\".  The former problem can be worked around by specifying \"-s 0.0.0.0\",\nwhich will do the right thing despite netcat claiming that it's listening on\n[127.0.0.1].  This is a known problem -- for example, there's a mention of it\nin the makefile for SOCKS.  On the flip side, binding to localhost and sending\npackets to some other machine doesn't work as you'd expect -- they go out with\nthe source address of the sending interface instead.  The Linux kernel contains\na specific check to ensure that packets from 127.0.0.1 are never sent to the\nwire; other kernels may contain similar code.  Linux, of course, *still*\ndoesn't support source-routing, but they claim that it and many other network\nimprovements are at least breathing hard.\n\nThere are several possible errors associated with making TCP connections, but\nto specifically see anything other than \"refused\", one must wait the full\nkernel-defined timeout for a connection to fail.  Netcat's mechanism of\nwrapping an alarm timer around the connect prevents the *real* network error\nfrom being returned -- \"errno\" at that point indicates \"interrupted system\ncall\" since the connect attempt was interrupted.  Some old 4.3 BSD kernels\nwould actually return things like \"host unreachable\" immediately if that was\nthe case, but most newer kernels seem to wait the full timeout and *then* pass\nback the real error.  Go figure.  In this case, I'd argue that the old way was\nbetter, despite those same kernels generally being the ones that tear down\n*established* TCP connections when ICMP-bombed.\n\nIncoming socket options are passed to applications by the kernel in the\nkernel's own internal format.  The socket-options structure for source-routing\ncontains the \"first-hop\" IP address first, followed by the rest of the real\noptions list.  The kernel uses this as is when sending reply packets -- the\nstructure is therefore designed to be more useful to the kernel than to humans,\nbut the hex dump of it that netcat produces is still useful to have.\n\nKernels treat source-routing options somewhat oddly, but it sort of makes sense\nonce one understands what's going on internally.  The options list of addresses\nmust contain hop1, hop2, ..., destination.  When a source-routed packet is sent\nby the kernel [at least BSD], the actual destination address becomes irrelevant\nbecause it is replaced with \"hop1\", \"hop1\" is removed from the options list,\nand all the other addresses in the list are shifted up to fill the hole.  Thus\nthe outbound packet is sent from your chosen source address to the first\n*gateway*, and the options list now contains hop2, ..., destination.  During\nall this address shuffling, the kernel does NOT change the pointer value, which\nis why it is useful to be able to set the pointer yourself -- you can construct\nsome really bizarre return paths, and send your traffic fairly directly to the\ntarget but around some larger loop on the way back.  Some Sun kernels seem to\nnever flip the source-route around if it contains less than three hops, never\nreset the pointer anyway, and tries to send the packet [with options containing\na \"completed\" source route!!] directly back to the source.  This is way broken,\nof course.  [Maybe ipforwarding has to be on?  I haven't had an opportunity to\nbeat on it thoroughly yet.]\n\n\"Credits\" section: The original idea for netcat fell out of a long-standing\ndesire and fruitless search for a tool resembling it and having the same\nfeatures.  After reading some other network code and realizing just how many\ncool things about sockets could be controlled by the calling user, I started\non the basics and the rest fell together pretty quickly.  Some port-scanning\nideas were taken from Venema/Farmer's SATAN tool kit, and Pluvius' \"pscan\"\nutility.  Healthy amounts of BSD kernel source were perused in an attempt to\ndope out socket options and source-route handling; additional help was obtained\nfrom Dave Borman's telnet sources.  The select loop is loosely based on fairly\nwell-known code from \"rsh\" and Richard Stevens' \"sock\" program [which itself is\nsort of a \"netcat\" with more obscure features], with some more paranoid\nsanity-checking thrown in to guard against the distinct likelihood that there\nare subtleties about such things I still don't understand.  I found the\nargument-hiding method cleanly implemented in Barrett's \"deslogin\"; reading the\nline as input allows greater versatility and is much less prone to cause\nbizarre problems than the more common trick of overwriting the argv array.\nAfter the first release, several people contributed portability fixes; they are\ncredited in generic.h and the Makefile.  Lauren Burka inspired the ascii art\nfor this revised document.  Dean Gaudet at Wired supplied a precursor to\nthe hex-dump code, and mudge@l0pht.com originally experimented with and\nsupplied code for the telnet-options responder.  Outbound \"-e \u003cprog\u003e\" resulted\nfrom a need to quietly bypass a firewall installation.  Other suggestions and\npatches have rolled in for which I am always grateful, but there are only 26\nhours per day and a discussion of feature creep near the end of this document.\n\nNetcat was written with the Russian railroad in mind -- conservatively built\nand solid, but it *will* get you there.  While the coding style is fairly\n\"tight\", I have attempted to present it cleanly [keeping *my* lines under 80\ncharacters, dammit] and put in plenty of comments as to why certain things\nare done.  Items I know to be questionable are clearly marked with \"XXX\".\nSource code was made to be modified, but determining where to start is\ndifficult with some of the tangles of spaghetti code that are out there.\nHere are some of the major points I feel are worth mentioning about netcat's\ninternal design, whether or not you agree with my approach.\n\nExcept for generic.h, which changes to adapt more platforms, netcat is a single\nsource file.  This has the distinct advantage of only having to include headers\nonce and not having to re-declare all my functions in a billion different\nplaces.  I have attempted to contain all the gross who's-got-what-.h-file\nthings in one small dumping ground.  Functions are placed \"dependencies-first\",\nsuch that when the compiler runs into the calls later, it already knows the\ntype and arguments and won't complain.  No function prototyping -- not even the\n__P(()) crock -- is used, since it is more portable and a file of this size is\neasy enough to check manually.  Each function has a standard-format comment\nahead of it, which is easily found using the regexp \" :$\".  I freely use gotos.\nLoops and if-clauses are made as small and non-nested as possible, and the ends\nof same *marked* for clarity [I wish everyone would do this!!].\n\nLarge structures and buffers are all malloc()ed up on the fly, slightly larger\nthan the size asked for and zeroed out.  This reduces the chances of damage\nfrom those \"end of the buffer\" fencepost errors or runaway pointers escaping\noff the end.  These things are permanent per run, so nothing needs to be freed\nuntil the program exits.\n\nFile descriptor zero is always expected to be standard input, even if it is\nclosed.  If a new network descriptor winds up being zero, a different one is\nasked for which will be nonzero, and fd zero is simply left kicking around\nfor the rest of the run.  Why?  Because everything else assumes that stdin is\nalways zero and \"netfd\" is always positive.  This may seem silly, but it was a\nlot easier to code.  The new fd is obtained directly as a new socket, because\ntrying to simply dup() a new fd broke subsequent socket-style use of the new fd\nunder Solaris' stupid streams handling in the socket library.\n\nThe catch-all message and error handlers are implemented with an ample list of\nphoney arguments to get around various problems with varargs.  Varargs seems\nlike deliberate obfuscation in the first place, and using it would also\nrequire use of vfprintf() which not all platforms support.  The trailing\nsleep in bail() is to allow output to flush, which is sometimes needed if\nnetcat is already on the other end of a network connection.\n\nThe reader may notice that the section that does DNS lookups seems much\ngnarlier and more confusing than other parts.  This is NOT MY FAULT.  The\nsockaddr and hostent abstractions are an abortion that forces the coder to\ndeal with it.  Then again, a lot of BSD kernel code looks like similar\nstruct-pointer hell.  I try to straighten it out somewhat by defining my own\nHINF structure, containing names, ascii-format IP addresses, and binary IP\naddresses.  I fill this structure exactly once per host argument, and squirrel\neverything safely away and handy for whatever wants to reference it later.\n\nWhere many other network apps use the FIONBIO ioctl to set non-blocking I/O\non network sockets, netcat uses straightforward blocking I/O everywhere.\nThis makes everything very lock-step, relying on the network and filesystem\nlayers to feed in data when needed.  Data read in is completely written out\nbefore any more is fetched.  This may not be quite the right thing to do under\nsome OSes that don't do timed select() right, but this remains to be seen.\n\nThe hexdump routine is written to be as fast as possible, which is why it does\nso much work itself instead of just sprintf()ing everything together.  Each\ndump line is built into a single buffer and atomically written out using the\nlowest level I/O calls.  Further improvements could undoubtedly be made by\nusing writev() and eliminating all sprintf()s, but it seems to fly right along\nas is.  If both exec-a-prog mode and a hexdump file is asked for, the hexdump\nflag is deliberately turned off to avoid creating random zero-length files.\nFiles are opened in \"truncate\" mode; if you want \"append\" mode instead, change\nthe open flags in main().\n\nmain() may look a bit hairy, but that's only because it has to go down the\nargv list and handle multiple ports, random mode, and exit status.  Efforts\nhave been made to place a minimum of code inside the getopt() loop.  Any real\nwork is sent off to functions in what is hopefully a straightforward way.\n\nObligatory vendor-bash: If \"nc\" had become a standard utility years ago,\nthe commercial vendors would have likely packaged it setuid root and with\n-DGAPING_SECURITY_HOLE turned on but not documented.  It is hoped that netcat\nwill aid people in finding and fixing the no-brainer holes of this sort that\nkeep appearing, by allowing easier experimentation with the \"bare metal\" of\nthe network layer.\n\nIt could be argued that netcat already has too many features.  I have tried\nto avoid \"feature creep\" by limiting netcat's base functionality only to those\nthings which are truly relevant to making network connections and the everyday\nassociated DNS lossage we're used to.  Option switches already have slightly\noverloaded functionality.  Random port mode is sort of pushing it.  The\nhex-dump feature went in later because it *is* genuinely useful.  The\ntelnet-responder code *almost* verges on the gratuitous, especially since it\nmucks with the data stream, and is left as an optional piece.  Many people have\nasked for example \"how 'bout adding encryption?\" and my response is that such\nthings should be separate entities that could pipe their data *through* netcat\ninstead of having their own networking code.  I am therefore not completely\nenthusiastic about adding any more features to this thing, although you are\nstill free to send along any mods you think are useful.\n\nNonetheless, at this point I think of netcat as my tcp/ip swiss army knife,\nand the numerous companion programs and scripts to go with it as duct tape.\nDuct tape of course has a light side and a dark side and binds the universe\ntogether, and if I wrap enough of it around what I'm trying to accomplish,\nit *will* work.  Alternatively, if netcat is a large hammer, there are many\nnetwork protocols that are increasingly looking like nails by now...\n\n_H* 960320 v1.10 RELEASE -- happy spring!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmainframed%2Fnc110-omvs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmainframed%2Fnc110-omvs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmainframed%2Fnc110-omvs/lists"}