Movatterモバイル変換


[0]ホーム

URL:


SourceForge.net Logo
[Project] [Download] [Contact] [Code]Netcat 1.10===========   /\_/\  / 0 0 \Netcat is a simple Unix utility which reads and writes data ====v====across network connections, using TCP or UDP protocol.  \  W  /It is designed to be a reliable "back-end" tool that can  |     |     _be used directly or easily driven by other programs and  / ___ \    /scripts.  At the same time, it is a feature-rich network / /   \ \  |debugging and exploration tool, since it can create almost(((-----)))-'any kind of connection you would need and has several /interesting built-in capabilities.  Netcat, or "nc" as the(      ___actual program is named, should have been supplied long ago \__.=|___Eas another one of those cryptic but standard Unix tools.        /In the simplest usage, "nc host port" creates a TCP connection to the givenport on the given target host.  Your standard input is then sent to the host,and anything that comes back across the connection is sent to your standardoutput.  This continues indefinitely, until the network side of the connectionshuts down.  Note that this behavior is different from most other applicationswhich shut everything down and exit after an end-of-file on the standard input.Netcat can also function as a server, by listening for inbound connectionson arbitrary ports and then doing the same reading and writing.  With minorlimitations, netcat doesn't really care if it runs in "client" or "server"mode -- it still shovels data back and forth until there isn't any more left.In either mode, shutdown can be forced after a configurable time of inactivityon the network side.And it can do this via UDP too, so netcat is possibly the "udp telnet-like"application you always wanted for testing your UDP-mode servers.  UDP, as the"U" implies, gives less reliable data transmission than TCP connections andsome systems may have trouble sending large amounts of data that way, but it'sstill a useful capability to have.You may be asking "why not just use telnet to connect to arbitrary ports?"Valid question, and here are some reasons.  Telnet has the "standard inputEOF" problem, so one must introduce calculated delays in driving scripts toallow network output to finish.  This is the main reason netcat stays runninguntil the *network* side closes.  Telnet also will not transfer arbitrarybinary data, because certain characters are interpreted as telnet options andare thus removed from the data stream.  Telnet also emits some of itsdiagnostic messages to standard output, where netcat keeps such thingsreligiously separated from its *output* and will never modify any of the realdata in transit unless you *really* want it to.  And of course telnet isincapable of listening for inbound connections, or using UDP instead.  Netcatdoesn't have any of these limitations, is much smaller and faster than telnet,and has many other advantages.Some of netcat's major features are:Outbound or inbound connections, TCP or UDP, to or from any portsFull DNS forward/reverse checking, with appropriate warningsAbility to use any local source portAbility to use any locally-configured network source addressBuilt-in port-scanning capabilities, with randomizerBuilt-in loose source-routing capabilityCan read command line arguments from standard inputSlow-send mode, one line every N secondsHex dump of transmitted and received dataOptional ability to let another program service established connectionsOptional telnet-options responderEfforts have been made to have netcat "do the right thing" in all its variousmodes.  If you believe that it is doing the wrong thing under whatevercircumstances, please notify me and tell me how you think it should behave.If netcat is not able to do some task you think up, minor tweaks to the codewill probably fix that.  It provides a basic and easily-modified template forwriting other network applications, and I certainly encourage people to makecustom mods and send in any improvements they make to it.  This is the secondrelease; the overall differences from 1.00 are relatively minor and have mostlyto do with portability and bugfixes.  Many people provided greatly appreciatedfixes and comments on the 1.00 release.  Continued feedback from the Internetcommunity is always welcome!Netcat is entirely my own creation, although plenty of other code was used asexamples.  It is freely given away to the Internet community in the hope thatit will be useful, with no restrictions except giving credit where it is due.No GPLs, Berkeley copyrights or any of that nonsense.  The author assumes NOresponsibility for how anyone uses it.  If netcat makes you rich somehow andyou're feeling generous, mail me a check.  If you are affiliated in any waywith Microsoft Network, get a life.  Always ski in control.  Comments,questions, and patches tonc110-devel@lists.sourceforge.net.
Exploration of features=======================Where to begin?  Netcat is at the same time so simple and versatile, it's liketrying to describe everything you can do with your Swiss Army knife.  This willgo over the basics; you should also read the usage examples and notes later onwhich may give you even more ideas about what this sort of tool is good for.If no command arguments are given at all, netcat asks for them, reads a linefrom standard input, and breaks it up into arguments internally.  This can beuseful when driving netcat from certain types of scripts, with the side effectof hiding your command line arguments from "ps" displays.The host argument can be a name or IP address.  If -n is specified, netcatwill only accept numeric IP addresses and do no DNS lookups for anything.  If-n is not given and -v is turned on, netcat will do a full forward and reversename and address lookup for the host, and warn you about the all-too-commonproblem of mismatched names in the DNS.  This often takes a little longer forconnection setup, but is useful to know about.  There are circumstances underwhich this can *save* time, such as when you want to know the name for some IPaddress and also connect there.  Netcat will just tell you all about it, savingthe manual steps of looking up the hostname yourself.  Normally mismatch-checking is case-insensitive per the DNS spec, but you can define ANAL atcompile time to make it case-sensitive -- sometimes useful for uncovering minorerrors in your own DNS files while poking around your networks.A port argument is required for outbound connections, and can be numeric or aname as listed in /etc/services.  If -n is specified, only numeric argumentsare valid.  Special syntax and/or more than one port argument cause differentbehavior -- see details below about port-scanning.The -v switch controls the verbosity level of messages sent to standard error.You will probably want to run netcat most of the time with -v turned on, so youcan see info about the connections it is trying to make.  You will probablyalso want to give a smallish -w argument, which limits the time spent trying tomake a connection.  I usually alias "nc" to "nc -v -w 3", which makes itfunction just about the same for things I would otherwise use telnet to do.The timeout is easily changed by a subsequent -w argument which overrides theearlier one.  Specifying -v more than once makes diagnostic output MOREverbose.  If -v is not specified at all, netcat silently does its work unlesssome error happens, whereupon it describes the error and exits with a nonzerostatus.  Refused network connections are generally NOT considered to be errors,unless you only asked for a single TCP port and it was refused.Note that -w also sets the network inactivity timeout.  This does not have anyeffect until standard input closes, but then if nothing further arrives fromthe network in the next seconds, netcat tries to read the net oncemore for good measure, and then closes and exits.  There are a lot of networkservices now that accept a small amount of input and return a large amount ofoutput, such as Gopher and Web servers, which is the main reason netcat waswritten to "block" on the network staying open rather than standard input.Handling the timeout this way gives uniform behavior with network servers that*don't* close by themselves until told to.UDP connections are opened instead of TCP when -u is specified.  These aren'treally "connections" per se since UDP is a connectionless protocol, althoughnetcat does internally use the "connected UDP socket" mechanism that mostkernels support.  Although netcat claims that an outgoing UDP connection is"open" immediately, no data is sent until something is read from standardinput.  Only thereafter is it possible to determine whether there really is aUDP server on the other end, and often you just can't tell.  Most UDP protocolsuse timeouts and retries to do their thing and in many cases won't botheranswering at all, so you should specify a timeout and hope for the best.  Youwill get more out of UDP connections if standard input is fed from a sourceof data that looks like various kinds of server requests.To obtain a hex dump file of the data sent either way, use "-o logfile".  Thedump lines begin with "<" or ">" to respectively indicate "from the net" or"to the net", and contain the total count per direction, and hex and asciirepresentations of the traffic.  Capturing a hex dump naturally slows netcatdown a bit, so don't use it where speed is critical.Netcat can bind to any local port, subject to privilege restrictions and portsthat are already in use.  It is also possible to use a specific local networksource address if it is that of a network interface on your machine.  [Note:this does not work correctly on all platforms.]  Use "-p portarg" to grab aspecific local port, and "-s ip-addr" or "-s name" to have that be your sourceIP address.  This is often referred to as "anchoring the socket".  Root userscan grab any unused source port including the "reserved" ones less than 1024.Absence of -p will bind to whatever unused port the system gives you, just likeany other normal client connection, unless you use -r [see below].Listen mode will cause netcat to wait for an inbound connection, and then thesame data transfer happens.  Thus, you can do "nc -l -p 1234< filename" andwhen someone else connects to your port 1234, the file is sent to them whetherthey wanted it or not.  Listen mode is generally used along with a local portargument -- this is required for UDP mode, while TCP mode can have the systemassign one and tell you what it is if -v is turned on.  If you specify a targethost and optional port in listen mode, netcat will accept an inbound connectiononly from that host and if you specify one, only from that foreign source port.In verbose mode you'll be informed about the inbound connection, including whataddress and port it came from, and since listening on "any" applies to severalpossibilities, which address it came *to* on your end.  If the system supportsIP socket options, netcat will attempt to retrieve any such options from aninbound connection and print them out in hex.If netcat is compiled with -DGAPING_SECURITY_HOLE, the -e argument specifiesa program to exec after making or receiving a successful connection.  In thelistening mode, this works similarly to "inetd" but only for a single instance.Use with GREAT CARE.  This piece of the code is normally not enabled; if youknow what you're doing, have fun.  This hack also works in UDP mode.  Note thatyou can only supply -e with the name of the program, but no arguments.  If youwant to launch something with an argument list, write a two-line wrapper scriptor just use inetd like always.If netcat is compiled with -DTELNET, the -t argument enables it to respondto telnet option negotiation [always in the negative, i.e. DONT or WONT].This allows it to connect to a telnetd and get past the initial negotiationfar enough to get a login prompt from the server.  Since this feature hasthe potential to modify the data stream, it is not enabled by default.  Youhave to understand why you might need this and turn on the #define yourself.Data from the network connection is always delivered to standard output asefficiently as possible, using large 8K reads and writes.  Standard input isnormally sent to the net the same way, but the -i switch specifies an "intervaltime" which slows this down considerably.  Standard input is still read inlarge batches, but netcat then tries to find where line breaks exist and sendsone line every interval time.  Note that if standard input is a terminal, datais already read line by line, so unless you make the -i interval rather long,what you type will go out at a fairly normal rate.  -i is really designedfor use when you want to "measure out" what is read from files or pipes.Port-scanning is a popular method for exploring what's out there.  Netcataccepts its commands with options first, then the target host, and everythingthereafter is interpreted as port names or numbers, or ranges of ports in M-Nsyntax.  CAVEAT: some port names in /etc/services contain hyphens -- netcatcurrently will not correctly parse those, so specify ranges using numbers ifyou can.  If more than one port is thus specified, netcat connects to *all* ofthem, sending the same batch of data from standard input [up to 8K worth] toeach one that is successfully connected to.  Specifying multiple ports alsosuppresses diagnostic messages about refused connections, unless -v isspecified twice for "more verbosity".  This way you normally get notified onlyabout genuinely open connections.  Example: "nc -v -w 2 -z target 20-30" willtry connecting to every port between 20 and 30 [inclusive] at the target, andwill likely inform you about an FTP server, telnet server, and mailer along theway.  The -z switch prevents sending any data to a TCP connection and verylimited probe data to a UDP connection, and is thus useful as a fast scanningmode just to see what ports the target is listening on.  To limit scanningspeed if desired, -i will insert a delay between each port probe.  There aresome pitfalls with regard to UDP scanning, described later, but in general itworks well.For each range of ports specified, scanning is normally done downward withinthat range.  If the -r switch is used, scanning hops randomly around withinthat range and reports open ports as it finds them.  [If you want them listedin order regardless, pipe standard error through "sort"...]  In addition, ifrandom mode is in effect, the local source ports are also randomized.  Thisprevents netcat from exhibiting any kind of regular pattern in its scanning.You can exert fairly fine control over your scan by judicious use of -r andselected port ranges to cover.  If you use -r for a single connection, thesource port will have a random value above 8192, rather than the next one thekernel would have assigned you.  Note that selecting a specific local portwith -p overrides any local-port randomization.Many people are interested in testing network connectivity using IP sourcerouting, even if it's only to make sure their own firewalls are blockingsource-routed packets.  On systems that support it, the -g switch can be usedmultiple times [up to 8] to construct a loose-source-routed path for yourconnection, and the -G argument positions the "hop pointer" within the list.If your network allows source-routed traffic in and out, you can testconnectivity to your own services via remote points in the internet.  Note thatalthough newer BSD-flavor telnets also have source-routing capability, it isn'tclearly documented and the command syntax is somewhat clumsy.  Netcat'shandling of "-g" is modeled after "traceroute".Netcat tries its best to behave just like "cat".  It currently does nothing toterminal input modes, and does no end-of-line conversion.  Standard input froma terminal is read line by line with normal editing characters in effect.  Youcan freely suspend out of an interactive connection and resume.  ^C or whateveryour interrupt character is will make netcat close the network connection andexit.  A switch to place the terminal in raw mode has been considered, but sofar has not been necessary.  You can send raw binary data by reading it out ofa file or piping from another program, so more meaningful effort would be spentwriting an appropriate front-end driver.Netcat is not an "arbitrary packet generator", but the ability to talk to rawsockets and/or nit/bpf/dlpi may appear at some point.  Such things are clearlyuseful; I refer you to Darren Reed's excellent ip_filter package, which nowincludes a tool to construct and send raw packets with any contents you want.Example uses -- the light side==============================Again, this is a very partial list of possibilities, but it may get you tothink up more applications for netcat.  Driving netcat with simple shell orexpect scripts is an easy and flexible way to do fairly complex tasks,especially if you're not into coding network tools in C.  My coding isn'tparticularly strong either [although undoubtedly better after writing thisthing!], so I tend to construct bare-metal tools like this that I can triviallyplug into other applications.  Netcat doubles as a teaching tool -- one canlearn a great deal about more complex network protocols by trying to simulatethem through raw connections!An example of netcat as a backend for something else is the shell-scriptWeb browser, which simply asks for the relevant parts of a URL and pipes"GET /what/ever" into a netcat connection to the server.  I used to do thiswith telnet, and had to use calculated sleep times and other stupidity tokludge around telnet's limitations.  Netcat guarantees that I get the wholepage, and since it transfers all the data unmodified, I can even pull downbinary image files and display them elsewhere later.  Some folks may find theidea of a shell-script web browser silly and strange, but it starts up andgets me my info a hell of a lot faster than a GUI browser and doesn't hideany contents of links and forms and such.  This is included, as scripts/web,along with several other web-related examples.Netcat is an obvious replacement for telnet as a tool for talking to daemons.For example, it is easier to type "nc host 25", talk to someone's mailer, andjust ^C out than having to type ^]c or QUIT as telnet would require you to do.You can quickly catalog the services on your network by telling netcat toconnect to well-known services and collect greetings, or at least scan for openports.  You'll probably want to collect netcat's diagnostic messages in youroutput files, so be sure to include standard error in the output using`>& file' in *csh or `> file 2>&1' in bourne shell.A scanning example: "echo QUIT | nc -v -w 5 target 20-250 500-600 5990-7000"will inform you about a target's various well-known TCP servers, includingr-services, X, IRC, and maybe a few you didn't expect.  Sending in QUIT andusing the timeout will almost guarantee that you see some kind of greeting orerror from each service, which usually indicates what it is and what version.[Beware of the "chargen" port, though...]  SATAN uses exactly this technique tocollect host information, and indeed some of the ideas herein were taken fromthe SATAN backend tools.  If you script this up to try every host in yoursubnet space and just let it run, you will not only see all the services,you'll find out about hosts that aren't correctly listed in your DNS.  Then youcan compare new snapshots against old snapshots to see changes.  For goingafter particular services, a more intrusive example is in scripts/probe.Netcat can be used as a simple data transfer agent, and it doesn't reallymatter which end is the listener and which end is the client -- input at oneside arrives at the other side as output.  It is helpful to start the listenerat the receiving side with no timeout specified, and then give the sending sidea small timeout.  That way the listener stays listening until you contact it,and after data stops flowing the client will time out, shut down, and take thelistener with it.  Unless the intervening network is fraught with problems,this should be completely reliable, and you can always increase the timeout.  Atypical example of something "rsh" is often used for: on one side,nc -l -p 1234 | uncompress -c | tar xvfp -and then on the other sidetar cfp - /some/dir | compress -c | nc -w 3 othermachine 1234will transfer the contents of a directory from one machine to another, withouthaving to worry about .rhosts files, user accounts, or inetd configurationsat either end.  Again, it matters not which is the listener or receiver; the"tarring" machine could just as easily be running the listener instead.  Onecould conceivably use a scheme like this for backups, by having cron-jobs fireup listeners and backup handlers [which can be restricted to specific addressesand ports between each other] and pipe "dump" or "tar" on one machine to "ddof=/dev/tapedrive" on another as usual.  Since netcat returns a nonzero exitstatus for a denied listener connection, scripts to handle such tasks couldeasily log and reject connect attempts from third parties, and then retry.Another simple data-transfer example: shipping things to a PC that doesn't haveany network applications yet except a TCP stack and a web browser.  Point thebrowser at an arbitrary port on a Unix server by telling it to downloadsomething like http://unixbox:4444/foo, and have a listener on the Unix sideready to ship out a file when the connect comes in.  The browser may pervertbinary data when told to save the URL, but you can dig the raw data out ofthe on-disk cache.If you build netcat with GAPING_SECURITY_HOLE defined, you can use it as an"inetd" substitute to test experimental network servers that would otherwiserun under "inetd".  A script or program will have its input and output hookedto the network the same way, perhaps sans some fancier signal handling.  Giventhat most network services do not bind to a particular local address, whetherthey are under "inetd" or not, it is possible for netcat avoid the "addressalready in use" error by binding to a specific address.  This lets you [asroot, for low ports] place netcat "in the way" of a standard service, sinceinbound connections are generally sent to such specifically-bound listenersfirst and fall back to the ones bound to "any".  This allows for a one-offexperimental simulation of some service, without having to screw around withinetd.conf.  Running with -v turned on and collecting a connection log fromstandard error is recommended.Netcat as well can make an outbound connection and then run a program or scripton the originating end, with input and output connected to the same networkport.  This "inverse inetd" capability could enhance the backup-server conceptdescribed above or help facilitate things such as a "network dialback" concept.The possibilities are many and varied here; if such things are intended assecurity mechanisms, it may be best to modify netcat specifically for thepurpose instead of wrapping such functions in scripts.Speaking of inetd, netcat will function perfectly well *under* inetd as a TCPconnection redirector for inbound services, like a "plug-gw" without theauthentication step.  This is very useful for doing stuff like redirectingtraffic through your firewall out to other places like web servers and mailhubs, while posing no risk to the firewall machine itself.  Put netcat behindinetd and tcp_wrappers, perhaps thusly:www stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80and you have a simple and effective "application relay" with access controland logging.  Note use of the wait time as a "safety" in case realwww isn'treachable or the calling user aborts the connection -- otherwise the relay mayhang there forever.You can use netcat to generate huge amounts of useless network data forvarious performance testing.  For example, doingyes AAAAAAAAAAAAAAAAAAAAAA | nc -v -v -l -p 2222 > /dev/nullon one side and then hitting it withyes BBBBBBBBBBBBBBBBBBBBBB | nc othermachine 2222 > /dev/nullfrom another host will saturate your wires with A's and B's.  The "veryverbose" switch usage will tell you how many of each were sent and receivedafter you interrupt either side.  Using UDP mode produces tremendously MOREtrash per unit time in the form of fragmented 8 Kbyte mobygrams -- enough tostress-test kernels and network interfaces.  Firing random binary data intovarious network servers may help expose bugs in their input handling, whichnowadays is a popular thing to explore.  A simple example data-generator isgiven in data/data.c included in this package, along with a small collectionof canned input files to generate various packet contents.  This program isdocumented in its beginning comments, but of interest here is using "%r" togenerate random bytes at well-chosen points in a data stream.  If you cancrash your daemon, you likely have a security problem.The hex dump feature may be useful for debugging odd network protocols,especially if you don't have any network monitoring equipment handy or aren'troot where you'd need to run "tcpdump" or something.  Bind a listening netcatto a local port, and have it run a script which in turn runs another netcatto the real service and captures the hex dump to a log file.  This sets up atransparent relay between your local port and wherever the real service is.Be sure that the script-run netcat does *not* use -v, or the extra info itsends to standard error may confuse the protocol.  Note also that you cannothave the "listen/exec" netcat do the data capture, since once the connectionarrives it is no longer netcat that is running.Binding to an arbitrary local port allows you to simulate things like r-serviceclients, if you are root locally.  For example, feeding "^@root^@joe^@pwd^@"[where ^@ is a null, and root/joe could be any other local/remote usernamepair] into a "rsh" or "rlogin" server, FROM your port 1023 for example,duplicates what the server expects to receive.  Thus, you can test for insecure.rhosts files around your network without having to create new user accounts onyour client machine.  The program data/rservice.c can aid this process byconstructing the "rcmd" protocol bytes.  Doing this also prevents "rshd" fromtrying to create that separate standard-error socket and still gives you aninput path, as opposed to the usual action of "rsh -n".  Using netcat forthings like this can be really useful sometimes, because rsh and rlogingenerally want a host *name* as an argument and won't accept IP addresses.  Ifyour client-end DNS is hosed, as may be true when you're trying to extractbackup sets on to a dumb client, "netcat -n" wins where normal rsh/rlogin isuseless.If you are unsure that a remote syslogger is working, test it with netcat.Make a UDP connection to port 514 and type in "<0>message", which shouldcorrespond to "kern.emerg" and cause syslogd to scream into every file it hasopen [and possibly all over users' terminals].  You can tame this down byusing a different number and use netcat inside routine scripts to send syslogmessages to places that aren't configured in syslog.conf.  For example,"echo '<38>message' | nc -w 1 -u loggerhost 514" should send to auth.noticeon loggerhost.  The exact number may vary; check against your syslog.h first.Netcat provides several ways for you to test your own packet filters.  If youbind to a port normally protected against outside access and make a connectionto somewhere outside your own network, the return traffic will be coming toyour chosen port from the "outside" and should be blocked.  TCP may get throughif your filter passes all "ack syn", but it shouldn't be even doing that to lowports on your network.  Remember to test with UDP traffic as well!  If yourfilter passes at least outbound source-routed IP packets, bouncing a connectionback to yourself via some gateway outside your network will create "incoming"traffic with your source address, which should get dropped by a correctlyconfigured anti-spoofing filter.  This is a "non-test" if you're also droppingsource-routing, but it's good to be able to test for that too.  Any packetfilter worth its salt will be blocking source-routed packets in bothdirections, but you never know what interesting quirks you might turn up byplaying around with source ports and addresses and watching the wires with anetwork monitor.You can use netcat to protect your own workstation's X server against outsideaccess.  X is stupid enough to listen for connections on "any" and never tellyou when new connections arrive, which is one reason it is so vulnerable.  Onceyou have all your various X windows up and running you can use netcat to bindjust to your ethernet address and listen to port 6000.  Any new connectionsfrom outside the machine will hit netcat instead your X server, and you get alog of who's trying.  You can either tell netcat to drop the connection, orperhaps run another copy of itself to relay to your actual X server on"localhost".  This may not work for dedicated X terminals, but it may bepossible to authorize your X terminal only for its boot server, and run a relaynetcat over on the server that will in turn talk to your X terminal.  Sincenetcat only handles one listening connection per run, make sure that whateverway you rig it causes another one to run and listen on 6000 soon afterward, oryour real X server will be reachable once again.  A very minimal script justto protect yourself could bewhile true ; do  nc -v -l -s -p 6000 localhost 2donewhich causes netcat to accept and then close any inbound connection to yourworkstation's normal ethernet address, and another copy is immediately run bythe script.  Send standard error to a file for a log of connection attempts.If your system can't do the "specific bind" thing all is not lost; run yourX server on display ":1" or port 6001, and netcat can still function as a probealarm by listening on 6000.Does your shell-account provider allow personal Web pages, but not CGI scripts?You can have netcat listen on a particular port to execute a program or scriptof your choosing, and then just point to the port with a URL in your homepage.The listener could even exist on a completely different machine, avoiding thepotential ire of the homepage-host administrators.  Since the script will getthe raw browser query as input it won't look like a typical CGI script, andsince it's running under your UID you need to write it carefully.  You may wantto write a netcat-based script as a wrapper that reads a query and sets upenvironment variables for a regular CGI script.  The possibilities for usingnetcat and scripts to handle Web stuff are almost endless.  Again, see theexamples under scripts/.Example uses -- the dark side=============================Equal time is deserved here, since a versatile tool like this can be usefulto any Shade of Hat.  I could use my Victorinox to either fix your car ordisassemble it, right?  You can clearly use something like netcat to attackor defend -- I don't try to govern anyone's social outlook, I just build tools.Regardless of your intentions, you should still be aware of these threats toyour own systems.The first obvious thing is scanning someone *else's* network for vulnerableservices.  Files containing preconstructed data, be it exploratory orexploitive, can be fed in as standard input, including command-line argumentsto netcat itself to keep "ps" ignorant of your doings.  The more random thescanning, the less likelihood of detection by humans, scan-detectors, ordynamic filtering, and with -i you'll wait longer but avoid loading down thetarget's network.  Some examples for crafting various standard UDP probes aregiven in data/*.d.Some configurations of packet filters attempt to solve the FTP-data problem byjust allowing such connections from the outside.  These come FROM port 20, TOhigh TCP ports inside -- if you locally bind to port 20, you may find yourselfable to bypass filtering in some cases.  Maybe not to low ports "inside", butperhaps to TCP NFS servers, X servers, Prospero, ciscos that listen on 200xand 400x...  Similar bypassing may be possible for UDP [and maybe TCP too] if aconnection comes from port 53; a filter may assume it's a nameserver response.Using -e in conjunction with binding to a specific address can enable "servertakeover" by getting in ahead of the real ones, whereupon you can snarf datasent in and feed your own back out.  At the very least you can log a hex dumpof someone else's session.  If you are root, you can certainly use -s and -e torun various hacked daemons without having to touch inetd.conf or the realdaemons themselves.  You may not always have the root access to deal with lowports, but what if you are on a machine that also happens to be an NFS server?You might be able to collect some interesting things from port 2049, includinglocal file handles.  There are several other servers that run on high portsthat are likely candidates for takeover, including many of the RPC services onsome platforms [yppasswdd, anyone?].  Kerberos tickets, X cookies, and IRCtraffic also come to mind.  RADIUS-based terminal servers connect incomingusers to shell-account machines on a high port, usually 1642 or thereabouts.SOCKS servers run on 1080.  Do "netstat -a" and get creative.There are some daemons that are well-written enough to bind separately to allthe local interfaces, possibly with an eye toward heading off this sort ofproblem.  Named from recent BIND releases, and NTP, are two that come to mind.Netstat will show these listening on address.53 instead of *.53.  You won'tbe able to get in front of these on any of the real interface addresses, whichof course is especially interesting in the case of named, but these serverssometimes forget about things like "alias" interface addresses or interfacesthat appear later on such as dynamic PPP links.  There are some hacked webservers and versions of "inetd" floating around that specifically bind as well,based on a configuration file -- these generally *are* bound to alias addressesto offer several different address-based services from one machine.Using -e to start a remote backdoor shell is another obvious sort of thing,easier than constructing a file for inetd to listen on "ingreslock" orsomething, and you can access-control it against other people by specifying aclient host and port.  Experience with this truly demonstrates how fragile thebarrier between being "logged in" or not really is, and is further expressed byscripts/bsh.  If you're already behind a firewall, it may be easier to make an*outbound* connection and then run a shell; a small wrapper script canperiodically try connecting to a known place and port, you can later listenthere until the inbound connection arrives, and there's your shell.  Runninga shell via UDP has several interesting features, although be aware that once"connected", the UDP stub sockets tend to show up in "netstat" just like TCPconnections and may not be quite as subtle as you wanted.  Packets may also belost, so use TCP if you need reliable connections.  But since UDP isconnectionless, a hookup of this sort will stick around almost forever, even ifyou ^C out of netcat or do a reboot on your side, and you only need to rememberthe ports you used on both ends to reestablish.  And outbound UDP-plus-execconnection creates the connected socket and starts the program immediately.  Ona listening UDP connection, the socket is created once a first packet isreceived.  In either case, though, such a "connection" has the interesting sideeffect that only your client-side IP address and [chosen?] source port willthereafter be able to talk to it.  Instant access control!  A non-local thirdparty would have to do ALL of the following to take over such a session:forge UDP with your source address [trivial to do; see below]guess the port numbers of BOTH ends, or sniff the wire for themarrange to block ICMP or UDP return traffic between it and your real  source, so the session doesn't die with a network write error.The companion program data/rservice.c is helpful in scripting up any sort ofr-service username or password guessing attack.  The arguments to "rservice"are simply the strings that get null-terminated and passed over an "rcmd"-styleconnection, with the assumption that the client does not need a separatestandard-error port.  Brute-force password banging is best done via "rexec" ifit is available since it is less likely to log failed attempts.  Thus, doing"rservice joe joespass pwd | nc target exec" should return joe's home dir ifthe password is right, or "Permission denied."  Plug in a dictionary and go totown.  If you're attacking rsh/rlogin, remember to be root and bind to a portbetween 512 and 1023 on your end, and pipe in "rservice joe joe pwd" and such.Netcat can prevent inadvertently sending extra information over a telnetconnection.  Use "nc -t" in place of telnet, and daemons that try to ask forthings like USER and TERM environment variables will get no useful answers, asthey otherwise would from a more recent telnet program.  Some telnetds actuallytry to collect this stuff and then plug the USER variable into "login" so thatthe caller is then just asked for a password!  This mechanism could cause alogin attempt as YOUR real username to be logged over there if you use aBorman-based telnet instead of "nc -t".Got an unused network interface configured in your kernel [e.g. SLIP], orsupport for alias addresses?  Ifconfig one to be any address you like, and bindto it with -s to enable all sorts of shenanigans with bogus source addresses.The interface probably has to be UP before this works; some SLIP versionsneed a far-end address before this is true.  Hammering on UDP services is thena no-brainer.  What you can do to an unfiltered syslog daemon should be fairlyobvious; trimming the conf file can help protect against it.  Many routers outthere still blindly believe what they receive via RIP and other routingprotocols.  Although most UDP echo and chargen servers check if an incomingpacket was sent from *another* "internal" UDP server, there are many that stilldo not, any two of which [or many, for that matter] could keep each otherentertained for hours at the expense of bandwidth.  And you can always makesomeone wonder why she's being probed by nsa.gov.Your TCP spoofing possibilities are mostly limited to destinations you cansource-route to while locally bound to your phony address.  Many sites blocksource-routed packets these days for precisely this reason.  If your kerneldoes oddball things when sending source-routed packets, try moving the pointeraround with -G.  You may also have to fiddle with the routing on your ownmachine before you start receiving packets back.  Warning: some machines stillsend out traffic using the source address of the outbound interface, regardlessof your binding, especially in the case of localhost.  Check first.  If you canopen a connection but then get no data back from it, the target host isprobably killing the IP options on its end [this is an option inside TCPwrappers and several other packages], which happens after the 3-way handshakeis completed.  If you send some data and observe the "send-q" side of "netstat"for that connection increasing but never getting sent, that's another symptom.Beware: if Sendmail 8.7.x detects a source-routed SMTP connection, it extractsthe hop list and sticks it in the Received: header!SYN bombing [sometimes called "hosing"] can disable many TCP servers, and ifyou hit one often enough, you can keep it unreachable for days.  As is true ofmany other denial-of-service attacks, there is currently no defense against itexcept maybe at the human level.  Making kernel SOMAXCONN considerably largerthan the default and the half-open timeout smaller can help, and indeed somepeople running large high-performance web servers have *had* to do that just tohandle normal traffic.  Taking out mailers and web servers is sociopathic, buton the other hand it is sometimes useful to be able to, say, disable a site'sidentd daemon for a few minutes.  If someone realizes what is going on,backtracing will still be difficult since the packets have a phony sourceaddress, but calls to enough ISP NOCs might eventually pinpoint the source.It is also trivial for a clueful ISP to watch for or even block outgoingpackets with obviously fake source addresses, but as we know many of them arenot clueful or willing to get involved in such hassles.  Besides, outboundpackets with an [otherwise unreachable] source address in one of their netblocks would look fairly legitimate.Notes=====A discussion of various caveats, subtleties, and the design of the innards.As of version 1.07 you can construct a single file containing command argumentsand then some data to transfer.  Netcat is now smart enough to pick out thefirst line and build the argument list, and send any remaining data across thenet to one or multiple ports.  The first release of netcat had trouble withthis -- it called fgets() for the command line argument, which behind thescenes does a large read() from standard input, perhaps 4096 bytes or so, andfeeds that out to the fgets() library routine.  By the time netcat 1.00 starteddirectly read()ing stdin for more data, 4096 bytes of it were gone.  It nowuses raw read() everywhere and does the right thing whether reading from files,pipes, or ttys.  If you use this for multiple-port connections, the singleblock of data will now be a maximum of 8K minus the first line.  Improvementshave been made to the logic in sending the saved chunk to each new port.  Notethat any command-line arguments hidden using this mechanism could still beextracted from a core dump.When netcat receives an inbound UDP connection, it creates a "connected socket"back to the source of the connection so that it can also send out data usingnormal write().  Using this mechanism instead of recvfrom/sendto has severaladvantages -- the read/write select loop is simplified, and ICMP errors can ineffect be received by non-root users.  However, it has the subtle side effectthat if further UDP packets arrive from the caller but from different sourceports, the listener will not receive them.  UDP listen mode on a multihomedmachine may have similar quirks unless you specifically bind to one of itsaddresses.  It is not clear that kernel support for UDP connected socketsand/or my understanding of it is entirely complete here, so experiment...You should be aware of some subtleties concerning UDP scanning.  If -z is on,netcat attempts to send a single null byte to the target port, twice, with asmall time in between.  You can either use the -w timeout, or netcat will tryto make a "sideline" TCP connection to the target to introduce a small timedelay equal to the round-trip time between you and the target.  Note that ifyou have a -w timeout and -i timeout set, BOTH take effect and you wait twiceas long.  The TCP connection is to a normally refused port to minimize traffic,but if you notice a UDP fast-scan taking somewhat longer than it should, itcould be that the target is actually listening on the TCP port.  Either way,any ICMP port-unreachable messages from the target should have arrived in themeantime.  The second single-byte UDP probe is then sent.  Under BSD kernels,the ICMP error is delivered to the "connected socket" and the second writereturns an error, which tells netcat that there is NOT a UDP service there.While Linux seems to be a fortunate exception, under many SYSV derived kernelsthe ICMP is not delivered, and netcat starts reporting that *all* the ports are"open" -- clearly wrong.  [Some systems may not even *have* the "udp connectedsocket" concept, and netcat in its current form will not work for UDP at all.]If -z is specified and only one UDP port is probed, netcat's exit statusreflects whether the connection was "open" or "refused" as with TCP.It may also be that UDP packets are being blocked by filters with no ICMP errorreturns, in which case everything will time out and return "open".  This allsounds backwards, but that's how UDP works.  If you're not sure, try "echow00gumz | nc -u -w 2 target 7" to see if you can reach its UDP echo port atall.  You should have no trouble using a BSD-flavor system to scan for UDParound your own network, although flooding a target with the high activity that-z generates will cause it to occasionally drop packets and indicate false"opens".  A more "correct" way to do this is collect and analyze the ICMPerrors, as does SATAN's "udp_scan" backend, but then again there's no guaranteethat the ICMP gets back to you either.  Udp_scan also does the zero-byteprobes but is excruciatingly careful to calculate its own round-trip timingaverage and dynamically set its own response timeouts along with decoding anyICMP received.  Netcat uses a much sleazier method which is nonetheless quiteeffective.  Cisco routers are known to have a "dead time" in between ICMPresponses about unreachable UDP ports, so a fast scan of a cisco will showalmost everything "open".  If you are looking for a specific UDP service, youcan construct a file containing the right bytes to trigger a response from theother end and send that as standard input.  Netcat will read up to 8K of thefile and send the same data to every UDP port given.  Note that you must use atimeout in this case [as would any other UDP client application] since thetwo-write probe only happens if -z is specified.Many telnet servers insist on a specific set of option negotiations beforepresenting a login banner.  On a raw connection you will see this as smallamount of binary gook.  My attempts to create fixed input bytes to make atelnetd happy worked some places but failed against newer BSD-flavor ones,possibly due to timing problems, but there are a couple of much betterworkarounds.  First, compile with -DTELNET and use -t if you just want to getpast the option negotiation and talk to something on a telnet port.  You willstill see the binary gook -- in fact you'll see a lot more of it as the optionsare responded to behind the scenes.  The telnet responder does NOT update thetotal byte count, or show up in the hex dump -- it just responds negatively toany options read from the incoming data stream.  If you want to use a normalfull-blown telnet to get to something but also want some of netcat's featuresinvolved like settable ports or timeouts, construct a tiny "foo" script:#! /bin/shexec nc -otheroptions targethost 23and then donc -l -p someport -e foo localhost &telnet localhost someportand your telnet should connect transparently through the exec'ed netcat tothe target, using whatever options you supplied in the "foo" script.  Don'tuse -t inside the script, or you'll wind up sending *two* option responses.I've observed inconsistent behavior under some Linuxes [perhaps just olderones?] when binding in listen mode.  Sometimes netcat binds only to "localhost"if invoked with no address or port arguments, and sometimes it is unable tobind to a specific address for listening if something else is already listeningon "any".  The former problem can be worked around by specifying "-s 0.0.0.0",which will do the right thing despite netcat claiming that it's listening on[127.0.0.1].  This is a known problem -- for example, there's a mention of itin the makefile for SOCKS.  On the flip side, binding to localhost and sendingpackets to some other machine doesn't work as you'd expect -- they go out withthe source address of the sending interface instead.  The Linux kernel containsa specific check to ensure that packets from 127.0.0.1 are never sent to thewire; other kernels may contain similar code.  Linux, of course, *still*doesn't support source-routing, but they claim that it and many other networkimprovements are at least breathing hard.There are several possible errors associated with making TCP connections, butto specifically see anything other than "refused", one must wait the fullkernel-defined timeout for a connection to fail.  Netcat's mechanism ofwrapping an alarm timer around the connect prevents the *real* network errorfrom being returned -- "errno" at that point indicates "interrupted systemcall" since the connect attempt was interrupted.  Some old 4.3 BSD kernelswould actually return things like "host unreachable" immediately if that wasthe case, but most newer kernels seem to wait the full timeout and *then* passback the real error.  Go figure.  In this case, I'd argue that the old way wasbetter, despite those same kernels generally being the ones that tear down*established* TCP connections when ICMP-bombed.Incoming socket options are passed to applications by the kernel in thekernel's own internal format.  The socket-options structure for source-routingcontains the "first-hop" IP address first, followed by the rest of the realoptions list.  The kernel uses this as is when sending reply packets -- thestructure is therefore designed to be more useful to the kernel than to humans,but the hex dump of it that netcat produces is still useful to have.Kernels treat source-routing options somewhat oddly, but it sort of makes senseonce one understands what's going on internally.  The options list of addressesmust contain hop1, hop2, ..., destination.  When a source-routed packet is sentby the kernel [at least BSD], the actual destination address becomes irrelevantbecause it is replaced with "hop1", "hop1" is removed from the options list,and all the other addresses in the list are shifted up to fill the hole.  Thusthe outbound packet is sent from your chosen source address to the first*gateway*, and the options list now contains hop2, ..., destination.  Duringall this address shuffling, the kernel does NOT change the pointer value, whichis why it is useful to be able to set the pointer yourself -- you can constructsome really bizarre return paths, and send your traffic fairly directly to thetarget but around some larger loop on the way back.  Some Sun kernels seem tonever flip the source-route around if it contains less than three hops, neverreset the pointer anyway, and tries to send the packet [with options containinga "completed" source route!!] directly back to the source.  This is way broken,of course.  [Maybe ipforwarding has to be on?  I haven't had an opportunity tobeat on it thoroughly yet.]"Credits" section: The original idea for netcat fell out of a long-standingdesire and fruitless search for a tool resembling it and having the samefeatures.  After reading some other network code and realizing just how manycool things about sockets could be controlled by the calling user, I startedon the basics and the rest fell together pretty quickly.  Some port-scanningideas were taken from Venema/Farmer's SATAN tool kit, and Pluvius' "pscan"utility.  Healthy amounts of BSD kernel source were perused in an attempt todope out socket options and source-route handling; additional help was obtainedfrom Dave Borman's telnet sources.  The select loop is loosely based on fairlywell-known code from "rsh" and Richard Stevens' "sock" program [which itself issort of a "netcat" with more obscure features], with some more paranoidsanity-checking thrown in to guard against the distinct likelihood that thereare subtleties about such things I still don't understand.  I found theargument-hiding method cleanly implemented in Barrett's "deslogin"; reading theline as input allows greater versatility and is much less prone to causebizarre problems than the more common trick of overwriting the argv array.After the first release, several people contributed portability fixes; they arecredited in generic.h and the Makefile.  Lauren Burka inspired the ascii artfor this revised document.  Dean Gaudet at Wired supplied a precursor tothe hex-dump code, and mudge@l0pht.com originally experimented with andsupplied code for the telnet-options responder.  Outbound "-e" resultedfrom a need to quietly bypass a firewall installation.  Other suggestions andpatches have rolled in for which I am always grateful, but there are only 26hours per day and a discussion of feature creep near the end of this document.Netcat was written with the Russian railroad in mind -- conservatively builtand solid, but it *will* get you there.  While the coding style is fairly"tight", I have attempted to present it cleanly [keeping *my* lines under 80characters, dammit] and put in plenty of comments as to why certain thingsare done.  Items I know to be questionable are clearly marked with "XXX".Source code was made to be modified, but determining where to start isdifficult with some of the tangles of spaghetti code that are out there.Here are some of the major points I feel are worth mentioning about netcat'sinternal design, whether or not you agree with my approach.Except for generic.h, which changes to adapt more platforms, netcat is a singlesource file.  This has the distinct advantage of only having to include headersonce and not having to re-declare all my functions in a billion differentplaces.  I have attempted to contain all the gross who's-got-what-.h-filethings in one small dumping ground.  Functions are placed "dependencies-first",such that when the compiler runs into the calls later, it already knows thetype and arguments and won't complain.  No function prototyping -- not even the__P(()) crock -- is used, since it is more portable and a file of this size iseasy enough to check manually.  Each function has a standard-format commentahead of it, which is easily found using the regexp " :$".  I freely use gotos.Loops and if-clauses are made as small and non-nested as possible, and the endsof same *marked* for clarity [I wish everyone would do this!!].Large structures and buffers are all malloc()ed up on the fly, slightly largerthan the size asked for and zeroed out.  This reduces the chances of damagefrom those "end of the buffer" fencepost errors or runaway pointers escapingoff the end.  These things are permanent per run, so nothing needs to be freeduntil the program exits.File descriptor zero is always expected to be standard input, even if it isclosed.  If a new network descriptor winds up being zero, a different one isasked for which will be nonzero, and fd zero is simply left kicking aroundfor the rest of the run.  Why?  Because everything else assumes that stdin isalways zero and "netfd" is always positive.  This may seem silly, but it was alot easier to code.  The new fd is obtained directly as a new socket, becausetrying to simply dup() a new fd broke subsequent socket-style use of the new fdunder Solaris' stupid streams handling in the socket library.The catch-all message and error handlers are implemented with an ample list ofphoney arguments to get around various problems with varargs.  Varargs seemslike deliberate obfuscation in the first place, and using it would alsorequire use of vfprintf() which not all platforms support.  The trailingsleep in bail() is to allow output to flush, which is sometimes needed ifnetcat is already on the other end of a network connection.The reader may notice that the section that does DNS lookups seems muchgnarlier and more confusing than other parts.  This is NOT MY FAULT.  Thesockaddr and hostent abstractions are an abortion that forces the coder todeal with it.  Then again, a lot of BSD kernel code looks like similarstruct-pointer hell.  I try to straighten it out somewhat by defining my ownHINF structure, containing names, ascii-format IP addresses, and binary IPaddresses.  I fill this structure exactly once per host argument, and squirreleverything safely away and handy for whatever wants to reference it later.Where many other network apps use the FIONBIO ioctl to set non-blocking I/Oon network sockets, netcat uses straightforward blocking I/O everywhere.This makes everything very lock-step, relying on the network and filesystemlayers to feed in data when needed.  Data read in is completely written outbefore any more is fetched.  This may not be quite the right thing to do undersome OSes that don't do timed select() right, but this remains to be seen.The hexdump routine is written to be as fast as possible, which is why it doesso much work itself instead of just sprintf()ing everything together.  Eachdump line is built into a single buffer and atomically written out using thelowest level I/O calls.  Further improvements could undoubtedly be made byusing writev() and eliminating all sprintf()s, but it seems to fly right alongas is.  If both exec-a-prog mode and a hexdump file is asked for, the hexdumpflag is deliberately turned off to avoid creating random zero-length files.Files are opened in "truncate" mode; if you want "append" mode instead, changethe open flags in main().main() may look a bit hairy, but that's only because it has to go down theargv list and handle multiple ports, random mode, and exit status.  Effortshave been made to place a minimum of code inside the getopt() loop.  Any realwork is sent off to functions in what is hopefully a straightforward way.Obligatory vendor-bash: If "nc" had become a standard utility years ago,the commercial vendors would have likely packaged it setuid root and with-DGAPING_SECURITY_HOLE turned on but not documented.  It is hoped that netcatwill aid people in finding and fixing the no-brainer holes of this sort thatkeep appearing, by allowing easier experimentation with the "bare metal" ofthe network layer.It could be argued that netcat already has too many features.  I have triedto avoid "feature creep" by limiting netcat's base functionality only to thosethings which are truly relevant to making network connections and the everydayassociated DNS lossage we're used to.  Option switches already have slightlyoverloaded functionality.  Random port mode is sort of pushing it.  Thehex-dump feature went in later because it *is* genuinely useful.  Thetelnet-responder code *almost* verges on the gratuitous, especially since itmucks with the data stream, and is left as an optional piece.  Many people haveasked for example "how 'bout adding encryption?" and my response is that suchthings should be separate entities that could pipe their data *through* netcatinstead of having their own networking code.  I am therefore not completelyenthusiastic about adding any more features to this thing, although you arestill free to send along any mods you think are useful.Nonetheless, at this point I think of netcat as my tcp/ip swiss army knife,and the numerous companion programs and scripts to go with it as duct tape.Duct tape of course has a light side and a dark side and binds the universetogether, and if I wrap enough of it around what I'm trying to accomplish,it *will* work.  Alternatively, if netcat is a large hammer, there are manynetwork protocols that are increasingly looking like nails by now..._H* 960320 v1.10 RELEASE -- happy spring!

[8]ページ先頭

©2009-2025 Movatter.jp