Total Pageviews

Search: This Blog, Linked From Here, The Web, My fav sites, My Blogroll

07 October 2011

Netcat the Network Swiss Army knife

A must have tool



Netcat was originally released in 1996 and was designed to read and write data across TCP and UDP connections using the TCP/IP protocol suite. Just as cat reads and writes information to files, Netcat reads and writes information across network connections. Furthermore, Netcat is specifically designed to behave as cat does. Originally coded for UNIX, and despite not originally being maintained on a regular basis, Netcat has been rewritten into a number of versions and  implementations. It has been ported to a number of operating systems, but is most often seen on various Linux distributions as well as Microsoft Windows (Remember that Netcat is a command-line tool -- Start > Run > cmd.exe and execute nc -h or netcat -h --) and for mobiles Windows CE (named Netcat 4 wince) or for the iPhone. Netcat’s functionality is helpful either as a standalone program and as a back-end tool. Some of the many uses of Netcat include:
  • elementary port scanning(in sequential and random order) 
  • connect in "tunnel mode"
  • send data in "buffer mode"(keep data in buffer and sent after n sec)
  • hexdump of transmitted or received data(optionally redirected in a file)
  • transferring files
  • grabbing banners
  • port listening and redirection
  • backdoor
There are more implementations . Other than the original UNIX release of Netcat  [v1.10] (for Windows simply download the zip file unzip to the location of your choice, and you’re finished. Check out: hobbit.txt is the original documentation, readme.txt is an explanation of a security fix from version 1.10 to 1.11, and license.txt is the standard GNU general public license) exist at least two slightly different implementations (written from scratch):
also exists enhancements of netcat like:
  • Socat
  • Cryptcat
  • In the middle of 2005, Nmap announced another netcat incarnation called Ncat. Ncat is integrated with Nmap and is available in the standard Nmap download packages (including source code and Linux, Windows, and Mac binaries) available from the Nmap download page.
Note: Many pre-installed, pre-compiled, or packaged versions of traditional Netcat that come with a Linux distribution are not compiled with what is called the GAPING_SECURITY_HOLE option (this allows Netcat to execute programs with the –e option). These are typically “safe” compilations of the original Netcat source code (i.e.OpenBSD's netcat ).  The GNU version of Netcat automatically compiles with the –e option enabled, so by installing this version no additional configuration is necessary. Despite this, all other functionality of the original Netcat remains intact. Of course, executing programs is what makes Netcat such a powerful tool(in case of no other option consider re-compiling a "safe" nc implemetation). netcat should already be installed on your system - you can check with:
$ which nc
To learn more about netcat, take a look at its man page:
$ man nc 
If you have Netcat already installed and are unsure about whether or not it was already compiled with the –e option, simply run:
$ nc -h
Netcat  display the help screen. If –e is among your options, then Netcat was installed with this option. If –e is not among the options, you’ll have to re-compile Netcat, or use the GNU version.
  • Other than netmins penetration testers use Netcat for testing the security of target systems (is included in the Metasploit Framework). 
  • Malicious users use Netcat (normally one of the DIY many variations of it) as a means of gaining remote access to a system. In this sense, it is  understandable why many anti-virus programs have labeled Netcat as a “trojan” or a “hacktool.”
As with virtually any tool, there is no internal moral compass that limits its use for only legitimate purposes. Your decision in this case is
  1. simply to determine if Netcat was purposely downloaded and installed by you (and thus not a threat), or 
  2. surreptitiously installed by a malicious user for nefarious purposes.
You may consider configuring your anti-virus program to exclude a particular directory where you install Netcat when it scans or auto-protects your file system. Of course, you need to be aware of the dangers associated with this.
Netcat can perform as client (connection mode) and as server (listen mode). Here's also a Tunnel mode
  1. connect to somewhere(as client): nc [-options] hostname port[s] [ports] ...: That's the syntax for Netcat’s client mode. Netcat is used as a client on your machine to obtain some sort of information from another machine. In other words act as a client in your machine and bind his stdin, stdout to sent and received data flow (respectively to and) from another machine. Client behaves like telnet .So netcat can substitute telnet
    1. Port(s) parameter(s) are the port(s) netcat try to connect sequentially or random trough -r option. Anyway netcat can use one port at a time
  2. listen for inbound(as server): nc –l –p port [options] [remote_hostname] [remote_port] : That's the syntax for Netcat’s server mode. Notice the –l switch, which puts Netcat into listen mode (you’re setting up Netcat to listen for an incoming connection). After a remote connection is established server mode is identical to connect mode.
    1. The optional parameters remote_hostname and remote_port denote the remote host and source port from where we're available (willing) accept connections
    2. Some netcat implementations like OpenBSD not accept -p instead in traditional(Hobbie's) netcat -p must be specified
  3. Tunnel mode: Use  SSH to encrypt and tunnel traffic trough it .An advandage of tunnel mode is that tunnel is closed automatically after file transfer ends. Another one is that on server side must be open only the port related to SSH(instead one or more ports nc dedicated). On the server side(must run a SSH sever):
    $ cat backup.iso | nc -l 3333
    on the client side:
    $ ssh -f -L 23333: me@ sleep 10; nc 23333 | pv -b > backup.iso
Please note that unlike telnet or ssh or similar .. plain netcat does not have authorization methods, i.e. no user or password, so be careful how it is used, because once you are listen on a door anyone could possibly connect to(Use tunnel mode)
Netcat doesn’t really care what mode it’s using, and will do most anything you ask of it in either mode. I mean by default, netcat creates a TCP socket either in listening mode (server socket) or a socket that is used in order to connect to a server (client mode). Actually, netcat does not care whether the socket is meant to be a server or a client. All it does is to take the data from stdin and transfer it to the other end across the network.
 Netcat's common commands
  • nc -l : put Netcat into server or listening mode
  • nc : run Netcat in client mode
  • -c : Netcat close at end of file (EOF) from standard input (stdin). This option is only available in the Linux variant.
  • -d : This switch enables Netcat to be detached from the console and run in background mode. This is particularly useful if you don’t want Netcat to open up a console window (especially if someone might be watching). Note that this option is not available in the traditional netcat.
  • -e <progr> : Is the Netcat’s most powerful option.  This option, available only in server mode, allows Netcat to execute a specified program when a client connects to it. Consider the following commands:
    • nc –l –p 12345 –e cmd.exe (Windows)
    • nc.traditional –l –p 12345 –e /bin/bash (Linux)
      executes Netcat in server mode on local port 12345, and will execute cmd.exe (the Windows command shell) when a client connects to it.
      • To test this option, start Netcat in server modenc.traditional –l –p 12345 –e /bin/bash (some implementations without -p)
      • Open a second window, and start Netcat in client modenc.traditional -v localhost 12345
        • you get the output: localhost.localdomain [] 12345 (?) open or Connection from port 12345 [tcp/*] accepted(OBSD implementation)
        • execute a cmd like ls -l
        • Type exit(or Ctrl-C) at the prompt, and you’ll see that the Netcat server closes in the first window. Normally, Netcat is a single-use program(once the connection is closed, Netcat closes and is no longer available). However the –L option(only in Windows) reopens Netcat with the same command line after the original connection is closed: nc –l –p 12345 –e cmd.exe -L. --In OpenBSD exist -k option that do the work. In traditional don't exist a similar option--
          Connecting to this instance of Netcat will open a command shell to the client. Exiting that command shell will close the connection, but the –L option will open it up again. In that case if we want to close netcat we can  do a CTRL-C in server side. 
        • In all cases if you type Ctrl-C in server side client disconnect immediately
  • -n :  allow numeric-only IP addresses and no reverse lookup. Without –n (and assuming you have included the –v switch), Netcat will display forward and reverse name and address lookup for the specified host. With the –n option enabled, Netcat accepts only a numeric IP address and does no reverse lookup. Because of mismatched DNS records sometimes Netcat can display warnings when doing forward or reverse Domain Name System (DNS) searches.
  • -g or -G : allow you to configure Netcat to use source routing. In source routing, the sender specifies the route that a packet takes through a network. Since most routers block source-routed packets, this option is more or less obsolete.
  • -i : set a delay interval between lines sent or ports scanned(useful for scanning ports if rate limiting is a problem)
  • -o filename : do a dump (hex) of Netcat traffic to a file filename
  • -l -p port : specify on which port on the local (server) machine Netcat should listen for inbound connections. Netcat is a single-use program. Mean, once the connection is closed, Netcat closes and is no longer available. However the -L option(Windows only.You can overcome this limitation in Linux with a bit of scripting) reopens Netcat with the same command line after the original connection is closed(nc –l –p 12345 –e cmd.exe -L Connecting to this instance of Netcat will open a command shell to the client. Exiting that command shell will close the connection, but the –L option will open it up again.)
  • -p port or in some implementations port : Netcat can also scan ports in client mode. You can specify more than one port (separated by commas), ranges (all-inclusive) --Netcat starts at the top and works toward the bottom. Therefore, if you ask Netcat to scan ports 20–30, it will start at 30 and work backwards to 20 --, or even common port names. When specifying the port number of a host in client mode, the –p option is not necessary --Simply list the hostname followed by the port number(s) or range--.
  • -r ports: randomize ports. If you’re using Netcat to scan ports, –r will allow Netcat to scan in a random manner as opposed to the standard top to bottom approach. Furthermore, will also randomize your local source ports in server mode.
  • -s : to change the source address of a packet, which is useful for spoofing the location of origin -- This is another command whose usefulness has degraded over time due to smarter routers that drop such packets --. The other obvious limitation is that replies are sent to the spoofed address instead of the true location.
  • nc –l –p 12345 –e /bin/sh -t : configure Netcat to answer Telnet negotiations. In other words, Netcat can be setup as a simple Telnet server. Use Netcat, Telnet, or any client such as PuTTY to connect to this server, and you’ll
    have shell access via Telnet.
  • -u : set UDP rather than TCP (nc Vs telnet: telnet is unable use UDP)
  • -v : controls verbosity, or the amount of information that is displayed to the user. While you can run Netcat perfectly without this option, Netcat will run silently and only provide you information if an error occurs. Again, as with many other programs, you can increase the verbosity level with more than one v (both –v –v or –vv will work).Many users also combine –v with –w
  • -V : only for the GNU Linux version, -V displays the version information and then exits.
  • -v secs : set the network inactivity timeout. This option is useful for closing
    connections when servers don’t do it automatically, and for speeding up your
    requests. A common time is 3 seconds.
  • -z : Zero input/output mode. This option is primarily used for port scanning. When –z is selected, Netcat will not send any data to a TCP connection, and will send only limited data to a UDP connection.
Syntax nc –v –l –p 12345 and nc –vlp 12345 are equivalent.
Netcat is not encrypted. Furthermore, Telnet is a clear-text protocol.
Likewise, any communications over such a link are subject to sniffing(Use tunnel mode).
By allowing an incoming client to connect to Netcat, you are giving that client direct shell access. Furthermore, there is no user identification or authentication process associated with this access.  It is important to understand that while you might have legitimate reasons to do this, there are undoubtedly many nefarious uses for such an option.
  • nc –l –p 12345 > dumpfile : redirect nc's outpout(stdout) to a file(dumpfile). This could simply be any text input from the other end of the connection, or even a file being transmitted. In other words, whatever is being pushed into the listener will be redirected to dumpfile.
  • nc –l –p 12345 >> dumpfile : append. If you use the same filename, the single redirector will overwrite your original file. If you want to keep your original file, your safer option is to use the double “greater than” redirector to append the file instead of replacing it. The double redirector will also create a new file if one doesn’t already exist to append.
  • nc –l –p 12345 < dumpfile : redirect input. When a client connects to this server, Netcat will send the dumpfile to the client. In other words, the connecting Netcat client is pulling the file from the server.
  • pipe (|) : “pipeline.” Some common commands that are often used in concert with Netcat are 
    • cat (sending a file)
      • $ cat gnunet_cli.tar| nc.traditional -vv -l -p 54010
        listening on [any] 54010 ...
        connect to [] from [] 58231
        ^C sent 43714560, rcvd 0
    • echo, and tar (compressing and sending a directory. i.e. compress the critical files on the server machine with tar and have them pulled by a remote machine).
      $ tar -czf - /etc/ | nc -l 3333
      As you can see, there is a dash in the tar options instead of a filename. This is because tar’s output needs to be passed to netcat. On the remote machine, the backup is pulled in the same way as before:
      $ nc 3333 | pv -b > mybackup.tar.gz
    • You could even run Netcat twice to set up a relay. There are really no limits to the possibilities.
Simple Chat Interface Netcat is a networking program designed to read and write data across connections. Perhaps the easiest way to understand how this works is to simply set up a server and client. You can set up both of these on the same computer, or use two different computers. For the sake of this demonstration, we’ll start both server and client on the same interface. In one terminal window, start the server:
$ nc –l –p 12345
In a second window, connect to the server with the client:
$ nc localhost 12345
The result is a very elementary chat interface. Text entered on one side of the connection is simply sent to the other side of the connection when you hit enter(in either directions). Notice there is nothing to indicate the source of the text, only the output is printed. To close the chat, press CTRL+C on either system. Remote teminal --not in OBSD's netcat-- (backdoor) Without telnet or ssh we can run a remote terminal trough nc that way: server side:
$ nc -l -p 4000 -e /bin/sh
or in Windows
$ nc -l -p 4000 -t -e cmd.exe
and in client side(either Windows, *nix):
$ nc  4000
When i connect to server i have in my screen a remote shell(shell of the remote host) . So i can run commands in the remote host sitting in front of my host. Port Scanning Although it is not the best option for port scanning (It is Nmap), Netcat does have some rudimentary port scanning capabilities(many people, given the choice of only one tool, would also choose Netcat). Port scanning with Netcat occurs in the client mode. The syntax is as follows:
$ nc –[options] hostname [ports]
The most common options associated with port scanning are
  • –w (network inactivity timeout) and 
  • –z, both of which may help to speed up your scan. 
  • Other possibilities are –i (sets a delay interval between ports scanned), 
  • –n (prevents DNS lookup), and 
  • –r (scans ports randomly).
use the –v (verbose) option while port scanning (another option would be to redirect the output to a file). If you don’t do this, Netcat will still scan the ports, but won’t send you any output. In general, –v is almost always a good option to use.
On server1, you can scan for open ports(from port number 1 to port number 1000) on server2 as follows:
$ nc -v -w 1 -z 1-1000
You can also scan ports on the local system:
$ nc -v -w 1 localhost -z 1-1000
listing port syntax
$ nc –v 21, 80, 443
$ nc –v 1-200
$ nc –v http
Among common ports, Netcat will tell you the service associated with a specific port. In Linux, the /etc/services file serves the same purpose. These files are also the reference for using service names instead of port numbers.
By using the –u option(UDP ports), be aware that “no reply” is  recognized as an open port.
Transferring Files a) CLIENT PULL THE FILE Netcat has the ability to both pull and push(transferring) files. Consider the following example:
$ nc –l –p 12345 < textfile
In this case, Netcat is started in server mode on local port 12345, and is offering textfile. A client who connects to this server is pulling the file from the server, and will receive textfile:
$ nc 12345 > textfile
For long files would useful pv utility: Server side(send file):
$ cat backup.iso | pv -b | nc -l 3333
Client Side(download file)
$ nc 3333 | pv -b > backup.iso
b) SERVER PUSH THE FILE Server side(push file):
$ nc -lp 1234 > file
Client side:
$ nc -w 1 1234 < file
Why use Netcat instead of FTP? Consider the potentially nefarious situation in which
a) you have shell access on a target computer inside a firewall. b) You need to transfer some files to the  destination, but the firewall is blocking inbound traffic.
In this case, you can run Netcat locally in server mode, offering the file(s) you want to send. Next, run Netcat in client mode from the target(behind firewall).
In most cases, firewalls allow common outbound traffic, so you can probably hide your file transfers on a common port such as 80 (HTTP).
Netcat can also be used to push files. If you’re running Netcat from the destination (the place you want the file to end up), start Netcat in server mode:
$ nc –l –p 12345 > textfile
On the source machine, push the file by starting Netcat in client mode:
$ nc <destination address> 12345 < textfile
As with all connections using Netcat, file transfers are unencrypted(Please use SSH,SSL,IPsec etc tunnel mode). If you are concerned about the privacy of the data you are transferring over Netcat, consider using Cryptcat, a version of Netcat that incorporates encrypted tunnels. Cryptcat uses the same command-line syntax as Netcat, but uses twofish encryption. Also consider using Netcat inside an Secure Shell (SSH) tunnel as a means of encrypting Netcat’s traffic. Cloning Hard Drives & Partitions You can use netcat even to clone hard drives/partitions over the network. In this example, I want to clone /dev/sda from server1 to server2. Of course, the to-be-cloned partitions must be unmounted on the target system, so if you want to clone the system partition, you must boot the target system (server2) from a rescue system or Live-CD such as Knoppix. Please keep in mind that the target system's IP address might change under the live system (you can find out by running:
$ ifconfig
On server2, run:
$ nc -l -p 1234 | dd of=/dev/sda 
Afterwards, on server1, run( server2's IP address in this example is
$ dd if=/dev/sda | nc 1234
to start the cloning process. This can take some time, depending on the size of the hard drive or partitions. Creating a partition image and sending it to a remote machine on-the-fly:
$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333
On the remote machine, connect to the server and receive the partition image with the following command:
$ $ nc 3333 | pv -b > myhdb5partition.img.gz
This might not be as classy as the partition backups using partimage, but it is efficient. Serving Web Pages You can even use netcat to act as a web server:
$ while true; do nc -l -p 80 -q 1 < somepage.html; done
would serve the page somepage.html until you close the terminal window. Spoofing HTTP Headers You can use netcat to request web pages:
$ nc 80
You can then type in headers as follows:
GET / HTTP/1.1 Host: Referrer: User-Agent: my-browser
As you see, this allows you to make up your own referrers and browser (User-Agent). After you've typed in your headers, press ENTER twice, and the requested page will appear (including the headers sent back by the remote server):
server2:~# nc 80 GET / HTTP/1.1 Host: Referrer: User-Agent: my-browser
HTTP/1.1 200 OK Date: Fri, 28 Nov 2008 14:11:49 GMT Server: Apache/2.2.3 (Debian) mod_ssl/2.2.3 OpenSSL/0.9.8c Last-Modified: Wed, 26 Nov 2008 19:34:17 GMT ETag: "228c707-21b1-b6b7e040" Accept-Ranges: bytes Content-Length: 8625 Content-Type: text/html
Anonymize netcat If we have just installed tor we can anonimyze netcat's network traffic torifying netcat  i.e. the command below shows the anonymous server to which you have hijacked the command "torify". :
$ echo -e "GET /iponly/ HTTP/1.0\r\n" | torify nc 80


No comments:

Post a Comment