netcat is a network utility for reading from and writing to network connections on either TCP or UDP. Hobbit ([email protected])
created netcat in 1995 as a network analog of Unix cat command. The flexibility and usefulness
of this tool have prompted people to write numerous other Netcat implementations -- often with modern features not found in the original.
Netcat is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts.
At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you
would need and has several interesting built-in capabilities.
Most common version is 1.1:
Name : netcat Relocations: (not relocatable)
Version : 1.10 Vendor: SUSE LINUX Products GmbH, Nuernberg, Germany
Release : 883.2 Build Date: Fri Jun 16 10:04:19 2006
Install Date: Mon Dec 15 16:02:36 2008 Build Host: bassani.suse.de
Group : Productivity/Networking/Other Source RPM: netcat-1.10-883.2.src.rpm
Size : 130566 License: Other License(s), see package, distributable
Signature : DSA/SHA1, Fri Jun 16 10:07:49 2006, Key ID a84edae89c800aca
Packager : http://bugs.opensuse.org
Summary : A Simple But Powerful Network Tool
Description :
Netcat is a simple Unix utility that reads and writes data across
network connections using TCP or UDP protocols. It is designed to be a
reliable back-end tool that can be used directly or easily driven by
other programs and scripts. At the same time, it is a feature-rich
network debugging and exploration tool, because it can create almost
any kind of connection you may need and has several interesting
built-in capabilities.
Find the documentation in /usr/share/doc/packages/netcat/README.
Authors:
--------
[email protected]
Distribution: SUSE Linux Enterprise 10 (X86-64)
Among the most interesting clones under active development is socat, which extends Netcat to support many other socket types,
SSL encryption, SOCKS proxies, and more. See socat It can be used,
for example, as a TCP relay.
Other takes on Netcat include OpenBSD's nc, Cryptcat, Netcat6, PNetcat, SBD.
A Windows version of netcat was created by Chris Wysopal. See
Netcat for Windows
Several projects look dead. For example
GNU Netcat 0.7.1 by Giovanni
Giacobbi. The project was not updated since Jan 2004.
It provides the possibility to connect two arbitrary scripts running on different computers with one writing and the second reading
from a pipe. This makes it useful for wide range application. Because of its versatility, netcat is also called the "TCP/IP
Swiss Army knife". According to Hobbit notable features of netcat are:
Outbound or inbound connections, TCP or UDP, to or from any ports
Full DNS forward/reverse checking, with appropriate warnings
Ability to use any local source port
Ability to use any locally-configured network source address
Ability to reconnect
Built-in loose source-routing capability
Can read command line arguments from standard input
Slow-send mode, one line every N seconds
Optional ability to let another program service inbound connections
Examples
One of the most practical usages of this network connection is the file transfer. As a basic Netcat function, this feature may be
used during installation. For a freshly installed computer, setting up servers often involves importing configuration files from the
other computer. And initially neither ftp or scp protocols may be available. For example, ftp
protocol can be blocked by DMZ firewall or channeled via proxy. In other words multiple layers of control mechanisms may interfere with
their functionality. And people responsible for firewall forget to do their work in time. In this environment you can still transfer
files with just one nc command using any open port visible in nmap, for example port 25
At the server console:
$ netcat -v -w 3 -p 25 l- > settings.tgz
and on the client side:
$ netcat -v 10.0.1.1 25 < settings.tgz
The command line for the server uses the argument -w to cause Netcat to wait for a few seconds. Magically,
the file is transferred from the client to the server. Now you can unzip them and configure the server. Think of this as a pipeline
over TCP/IP.
Security related uses, for example firewall testing
Network performance testing
Among alternative implementationswe again would like to single our socathttp://www.dest-unreach.org/socat/ has some interesting new functionality,
but the idea is the same as netcat . It extends Netcat to support several other socket types, SSL encryption, SOCKS proxies,
and more. It can be used, for example, as a TCP relay.
Network troubleshooting sometimes requires tracking specific network packets based on
complex filter criteria or just determining whether a connection can be made.
... ... ...
Using the ncat command, you will set up a TCP listener, which is a TCP service
that waits for a connection from a remote system on a specified port. The following command
starts a listening socket on TCP port 9999.
$ sudo ncat -l 9999
This command will "hang" your terminal. You can place the command into background mode, to
operate similar to a service daemon using the & (ampersand) signal. Your
prompt will return.
$ sudo ncat -l 8080 &
From a remote system, use the following command to attempt a connection:
$ telnet <IP address of ncat system> 9999
The attempt should fail as shown:
Trying <IP address of ncat system>...
telnet: connect to address <IP address of ncat system>: No route to host
This might be similar to the message you receive when attempting to connect to your original
service. The first thing to try is to add a firewall exception to the ncat
system:
$ sudo firewall-cmd --add-port=9999/tcp
This command allows TCP requests on port 9999 to pass through to a listening daemon on port
9999.
Retry the connection to the ncat system:
$ telnet <IP address of ncat system> 9999
Trying <IP address of ncat system>...
Connected to <IP address of ncat system>.
Escape character is '^]'.
This message means that you are now connected to the listening port, 9999, on the remote
system. To disconnect, use the keyboard combination, CTRL + ] . Type quit to return to a
prompt.
$ telnet <IP address of ncat system> 9999
Trying <IP address of ncat system>...
Connected to <IP address of ncat system>.
Escape character is '^]'.
^]
telnet>quit
Connection closed.
$
Disconnecting will also kill the TCP listening port on the remote (ncat) system, so don't
attempt another connection until you reissue the ncat command. If you want to keep
the listening port open rather than letting it die each time you disconnect, issue the -k (keep
open) option. This option keeps the listening port alive. Some sysadmins don't use this option
because they might leave a listening port open potentially causing security problems or port
conflicts with other services.
$ sudo ncat -k -l 9999 &
What ncat tells you
The success of connecting to the listening port of the ncat system means that
you can bind a port to your system's NIC. You can successfully create a firewall exception. And
you can successfully connect to that listening port from a remote system. Failures along the
path will help narrow down where your problem is.
What ncat doesn't tell you
Unfortunately, there's no solution for connectivity issues in this troubleshooting technique
that isn't related to binding, port listening, or firewall exceptions. This is a limited scope
troubleshooting session, but it's quick, easy, and definitive. What I've found is that most
connectivity issues boil down to one of these three. My next step in the process would be to
remove and reinstall the service package. If that doesn't work, download a different version of
the package and see if that works for you. Try going back at least two revisions until you find
one that works. You can always update to the latest version after you have a working
service.
Wrap up
The ncat command is a useful troubleshooting tool. This article only focused on
one tiny aspect of the many uses for ncat . Troubleshooting is as much of an art
as it is a science. You have to know which answers you have and which ones you don't have. You
don't have to troubleshoot or test things that already work. Explore ncat 's
various uses and see if your connectivity issues go away faster than they did before.
I use Telnet, netcat, Nmap, and other tools to test whether a remote service is up and
whether I can connect to it. These tools are handy, but they aren't installed by default on all
systems.
Fortunately, there is a simple way to test a connection without using external tools. To see
if a remote server is running a web, database, SSH, or any other service, run:
If the connection fails, the Failed to connect message is displayed on your
screen.
Assume serverA is behind a firewall/NAT. I want to see if the firewall is configured to
allow a database connection to serverA , but I haven't installed a database server yet. To
emulate a database port (or any other port), I can use the following:
Netcat (also known as 'nc') is a networking tool used for reading or writing from
TCP and UDP sockets using an easy interface. It is designed as a dependable 'back-end'
device that can be used directly or easily driven by other programs and scripts. Therefore,
this tool is a treat to network administrators, programmers, and pen-testers as it's a feature
rich network debugging and investigation tool.
To open netcat simply go to your shell and enter 'nc':
#nc
CONNECTING TO A HOST WITH NETCAT
Use the -u option to start a TCP
connection to a specified host and port:
#nc -u <host_ip> <port>
LISTEN TO INBOUND
CONNECTIONS
You can set nc to listen on a port using -l option
#nc -l <port>
SCAN PORTS WITH
NETCAT
This can easily be done using the '-z' flag which instructs netcat not to initiate a
connection but just check if the port is open. For example, In the following command we
instruct netcat to check which ports are open between 80 and 100 on ' localhost '
#nc -z <host_ip> <port_range>
ADVANCED PORT SCAN
To run an advanced port scan on a target, use the following command
#nc -v -n -z -w1 -r <target_ip>
This command will attempt to connect to random ports (-r) on the target ip running verbosely
(-v) without resolving names (-n). without sending any data (-z) and waiting no more than 1
second for a connection to occur (-w1)
TCP BANNER GRABBING WITH NETCAT
You can grab the banner of any tcp service running on an ip address using nc:
#echo "" | nc -v -n -w1 <target_ip> <port_range>
TRANSFER FILES WITH NETCAT
For this, you should have nc installed on both sending and receiving machines. First you
have to start the nc in listener mode in receiving host
#nc -l <port> > file.txt
Now run the following command on the sending host:
#nc <target_ip> <port> --send-only < data.txt
In conclusion, Netcat comes with a lot of cool features that we can use to simplify our
day-to-day tasks. Make sure to check out this article to learn
some more interesting features in this tool.
As you know from my previous two
articles,
Linux
troubleshooting: Setting up a TCP listener with ncat
and
The
ncat command is a problematic security tool for Linux sysadmins
,
netcat
is
a command that is both your best friend and your worst enemy. And this article further perpetuates this fact with
a look into how
ncat
delivers
a useful, but potentially dangerous, option for creating a port redirection link. I show you how to set up a port
or site forwarding link so that you can perform maintenance on a site while still serving customers.
The scenario
You need to perform maintenance on an
Apache installation on
server1
, but you don't
want the service to appear offline for your customers, which in this scenario are internal corporate users of the
labor portal that records hours worked for your remote users. Rather than notifying them that the portal will be
offline for six to eight hours, you've decided to create a forwarding service to another system,
server2
,
while you take care of
server1
's needs.
This method is an easy way of keeping a
specific service alive without tinkering with DNS or corporate firewall NAT settings.
Server1: Port 8088
Server2: Port 80
The steps
To set up this site/service forward, you
need to satisfy the following prerequisites:
ncat-nmap
package (should be installed by default)
A functional duplicate of the
server1
portal
on
server2
Root or
sudo
access
to servers 1 and 2 for firewall changes
If you've cleared these hurdles, it's time
to make this change happen.
The implementation
Configuring
ncat
in
this way makes use of named pipes, which is an efficient way to create this two-way communication link by writing
to and reading from a file in your home directory. There are multiple ways to do this, but I'm going to use the
one that works best for this type of port forwarding.
Create the named pipe
Creating the named pipe is easy using the
mkfifo
command.
I used the
file
command
to demonstrate that the file is there and it is a named pipe. This command is not required for the service to
work. I named the file
svr1_to_svr2
,
but you can use any name you want. I chose this name because I'm forwarding from
server1
to
server2
.
Create the forward service
Formally, this was called
setting
up a Listener-to-Client relay
, but it makes a little more sense if you think of this in firewall terms, hence
my "forward" name and description.
Issuing this command drops you back to
your prompt because you put the service into the background with the
&
.
As you can see, the named pipe and the service are both created as a standard user. I discussed the reasons for
this restriction in my previous article,
The
ncat command is a problematic security tool for Linux sysadmins
.
Command breakdown
The first part of the command,
ncat
-k -l 8088
, sets up the listener for connections that ordinarily would be answered by the Apache service
on
server1
. That service is offline, so you
create a listener to answer those requests. The
-k
option
is the keep-alive feature, meaning that it can serve multiple requests. The
-l
is
the listen option.
Port
8088
is the port you want to mimic, which is that of the customer portal.
The second part, to the right of the pipe
operator (
|
),
accepts and relays the requests to 192.168.1.60 on port 80. The named pipe
(svr1_to_svr2
)
handles the data in and out.
The usage
Now that you have your relay set up, it's
easy to use. Point your browser to the original host and customer portal, which is
http://server1:8088
.
This automatically redirects your browser to
server2
on
port 80. Your browser still displays the original URL and port.
I have found that too many repetitive
requests can cause this service to fail with a broken pipe message on
server1
.
This doesn't always kill the service, but it can. My suggestion is to set up a script to check for the
forward
command,
and if it doesn't exist, restart it. You can't check for the existence of the
svr1_to_svr2
file
because it always exists. Remember, you created it with the
mkfifo
command.
The caveat
The downside of this
ncat
capability
is that a user could forward traffic to their own duplicate site and gather usernames and passwords. The malicious
actor would have to kill the current port listener/web service to make this work, but it's possible to do this
even without root access. Sysadmins have to maintain vigilance through monitoring and alerting to avoid this type
of security loophole.
The wrap up
The
ncat
command
has so many uses that it requires one article per feature to describe each one. This article introduced you to the
concept of Listener-to-Client relay, or service forwarding, as I call it. It's useful for short maintenance
periods but should not be used for permanent redirects. For those, you should edit DNS and corporate firewall NAT
rules to send requests to their new destinations. You should remind yourself to turn off any
ncat
listeners
when you're finished with them as they do open a system to compromise. Never create these services with the root
user account.
[ Make managing your network easier than ever with
Network
automation for everyone
, a free book from Red Hat. ]
Check out these related articles on Enable Sysadmin
The life of a sysadmin is hectic, rushed,
and often frustrating. So, what you really need is a toolbox filled with tools that you easily recognize and can
use quickly without another learning curve when things are going bad. One such tool is the
ncat
command.
ncat - Concatenate and redirect sockets
The
ncat
command
has many uses, but the one I use it for is troubleshooting network connectivity issues. It is a handy, quick, and
easy to use tool that I can't live without. Follow along and see if you decide to add it to your toolbox as well.
Ncat is a feature-packed networking
utility which reads and writes data across networks from the command line. Ncat was written for the Nmap
Project and is the culmination of the currently splintered family of Netcat incarnations. It is designed to be
a reliable back-end tool to instantly provide network connectivity to other applications and users. Ncat will
not only work with IPv4 and IPv6 but provides the user with a virtually limitless number of potential uses.
Among Ncat's vast number of features
there is the ability to chain Ncats together; redirection of TCP, UDP, and SCTP ports to other sites; SSL
support; and proxy connections via SOCKS4, SOCKS5 or HTTP proxies (with optional proxy authentication as well).
Firewall problem or something else?
You've just installed <insert network
service here>, and you can't connect to it from another computer on the same network. It's frustrating. The
service is enabled. The service is started. You think you've created the correct firewall exception for it, but
yet, it doesn't respond.
Your troubleshooting life begins. In what
can stretch from minutes to days to infinity and beyond, you attempt to troubleshoot the problem. It could be many
things: an improperly configured (or unconfigured) firewall exception, a NIC binding problem, a software problem
somewhere in the service's code, a service misconfiguration, some weird compatibility issue, or something else
unrelated to the network or the service blocking access. This is your scenario. Where do you start when you've
checked all of the obvious places?
The ncat command to the rescue
The
ncat
command
should be part of your basic Linux distribution, but if it isn't, install the
nmap-ncat
package
and you'll have the latest version of it. Check the
ncat
man
page for usage, if you're interested in its many capabilities beyond this simple troubleshooting exercise.
Using the
ncat
command,
you will set up a TCP listener, which is a TCP service that waits for a connection from a remote system on a
specified port. The following command starts a listening socket on TCP port 9999.
$ sudo ncat -l 9999
This command will "hang" your terminal.
You can place the command into background mode, to operate similar to a service daemon using the
&
(ampersand)
signal. Your prompt will return.
$ sudo ncat -l 8080 &
From a remote system, use the following
command to attempt a connection:
$ telnet <IP address of ncat system> 9999
The attempt should fail as shown:
Trying <IP address of ncat system>...
telnet: connect to address <IP address of ncat system>: No route to host
This might be similar to the message you
receive when attempting to connect to your original service. The first thing to try is to add a firewall exception
to the
ncat
system:
$ sudo firewall-cmd --add-port=9999/tcp
This command allows TCP requests on port
9999 to pass through to a listening daemon on port 9999.
Retry the connection to the
ncat
system:
$ telnet <IP address of ncat system> 9999
Trying <IP address of ncat system>...
Connected to <IP address of ncat system>.
Escape character is '^]'.
This message means that you are now
connected to the listening port, 9999, on the remote system. To disconnect, use the keyboard combination,
CTRL
+ ]
. Type
quit
to return to a
prompt.
$ telnet <IP address of ncat system> 9999
Trying <IP address of ncat system>...
Connected to <IP address of ncat system>.
Escape character is '^]'.
^]
telnet>quit
Connection closed.
$
Disconnecting will also kill the TCP
listening port on the remote (ncat) system, so don't attempt another connection until you reissue the
ncat
command.
If you want to keep the listening port open rather than letting it die each time you disconnect, issue the -k
(keep open) option. This option keeps the listening port alive. Some sysadmins don't use this option because they
might leave a listening port open potentially causing security problems or port conflicts with other services.
$ sudo ncat -k -l 9999 &
What ncat tells you
The success of connecting to the listening
port of the
ncat
system
means that you can bind a port to your system's NIC. You can successfully create a firewall exception. And you can
successfully connect to that listening port from a remote system. Failures along the path will help narrow down
where your problem is.
What ncat doesn't tell you
Unfortunately, there's no solution for
connectivity issues in this troubleshooting technique that isn't related to binding, port listening, or firewall
exceptions. This is a limited scope troubleshooting session, but it's quick, easy, and definitive. What I've found
is that most connectivity issues boil down to one of these three. My next step in the process would be to remove
and reinstall the service package. If that doesn't work, download a different version of the package and see if
that works for you. Try going back at least two revisions until you find one that works. You can always update to
the latest version after you have a working service.
Wrap up
The
ncat
command
is a useful troubleshooting tool. This article only focused on one tiny aspect of the many uses for
ncat
.
Troubleshooting is as much of an art as it is a science. You have to know which answers you have and which ones
you don't have. You don't have to troubleshoot or test things that already work. Explore
ncat
's
various uses and see if your connectivity issues go away faster than they did before.
The socat utility is a relay
for bidirectional data transfers between two independent data channels.
There are many different types of channels socat can connect, including:
Files
Pipes
Devices (serial line, pseudo-terminal, etc)
Sockets (UNIX, IP4, IP6 - raw, UDP, TCP)
SSL sockets
Proxy CONNECT connections
File descriptors (stdin, etc)
The GNU line editor (readline)
Programs
Combinations of two of these
This tool is regarded as the advanced version of netcat . They do similar things, but socat
has more additional functionality, such as permitting multiple clients to listen on a port, or
reusing connections.
Why do we need socat?
There are many ways to use socate effectively. Here are a few examples:
TCP port forwarder (one-shot or daemon)
External socksifier
Tool to attack weak firewalls (security and audit)
Shell interface to Unix sockets
IP6 relay
Redirect TCP-oriented programs to a serial line
Logically connect serial lines on different computers
Establish a relatively secure environment ( su and chroot ) for
running client or server shell scripts with network connections
How do we use socat?
The syntax for socat is fairly simple:
socat [options] <address> <address>
You must provide the source and destination addresses for it to work. The syntax for these
addresses is:
protocol:ip:port
Examples of using socat
Let's get started with some basic examples of using socat for various
connections.
1. Connect to TCP port 80 on the local or remote system:
# socat - TCP4:www.example.com:80
In this case, socat transfers data between STDIO (-) and a TCP4 connection to
port 80 on a host named www.example.com.
2. Use socat as a TCP port forwarder:
For a single connection, enter:
# socat TCP4-LISTEN:81 TCP4:192.168.1.10:80
For multiple connections, use the fork option as used in the examples
below:
In this example, when a client connects to port 3334, a new child process is generated. All
data sent by the clients is appended to the file /tmp/test.log . If the file does
not exist, socat creates it. The option reuseaddr allows an immediate
restart of the server process.
In this case, socat transfers data from stdin to the specified
multicast address using UDP over port 6666 for both the local and remote connections. The
command also tells the interface eth0 to accept multicast packets for the given
group.
Practical uses for socat
Socat is a great tool for troubleshooting. It is also handy for easily making
remote connections. Practically, I have used socat for remote MySQL connections.
In the example below, I demonstrate how I use socat to connect my web application
to a remote MySQL server by connecting over the local socket.
The above command connects to the remote server 192.168.100.5 by using port 3307.
However, all communication will be done on the Unix socket
/var/lib/mysql/mysql.sock , and this makes it appear to be a local
server.
Wrap up
socat is a sophisticated utility and indeed an excellent tool for every
sysadmin to get things done and for troubleshooting. Follow this link to read more examples of
using socat .
NC command is for performing maintenance/diagnosis tasks related to network . It can perform operations like read,write or
data redirections over the network, similar to how you can use cat command to manipulate files on Linux system. Nc command can be used
as a utility to scan ports, monitoring or can also act as a basic TCP proxy.
Organizations can utilize it to review their network security, web servers, telnet servers, mail servers and so on, by checking the
ports that are opened and then secure them. NC command can also be used to capture information being sent by system.
Now let's discuss how we can use NC command with some examples,
Examples for NC command
Connect to a remote server
Following example shows how we can connect to remote server with nc command,
$ nc 10.10.10.100 80
here, 10.10.10.100 is IP of the server we want to connect to & 80 is the port number for the remote server. Once connected we can
perform some other functions like we can get the total page content with
GET/HTTP/1.1
or fetch page name,
GET/HTTP/1.1
or we can get banner for OS fingerprinting with the following,
HEAD/HTTP/1.1
This will let us know what software & version is being utilised to run the webserver.
Listen to inbound connection requests
To check a server for incoming connection request on a port number, use following example
$ nc -l 8080
Now NC is in listening mode to check port 8080 for incoming connection requests. Now listening mode will keep on running, until terminated
manually. But we can address this option 'w' for NC,
$ nc -w 10 8080
here, 10 means NC will listen for connections for 10 seconds only.
Connecting to UDP ports
By default, we can connect to TCP ports with NC but to listen to incoming request made to UDP ports we have to use option 'u' ,
$ nc -l -u 55
Using NC for Port forwarding
With option 'c' of NC, we can redirect a port to another. Complete example is,
$ nc -u -l 8080 -c ' nc -u -l 8090'
here, we have forwarded all incoming requests from port 8080 to port 8090.
Using NC as Proxy server
To use NC command as a proxy, use
$ nc – l 8080 | nc 10.10.10.200 80
here, all incoming connections to port 8080 will be diverted to 10.10.10.200 server on port 80.
Now with the above command, we only created a one way passage. To create a return passage or 2 way communication channel, use the
following commands,
$ mkfifo 2way
$ nc – l 8080 0<2way | nc 10.10.10.200 80 1>2way
Now you will have the capacity to send and get information over nc proxy.
Using NC as chat tool
Another utility that NC command can serve is as a chat tool. Yes we can also use it as a chat. To create it, first run the following
command on one server,
$ nc – l 8080
Than to connect on remote machine, run
$ nc 10.10.10.100 8080
Now we can start conversation using the terminal/CLI.
Using NC to create a system backdoor
Now this one is the most common application of NC & is mostly used by hackers a lot. Basically this creates a backdoor to system
which can be exploited by hackers (you should not be doing it, its wrong).
One must be aware of this as to safeguard against this kind of exploits.
Following command can be used to create a backdoor,
$ nc -l 5500 -e /bin/bash
here, we have attached port 5500 to /bin/bash, which can now be connected from a remote machine to execute the commands,
$ nc 10.10.10.100 5500
Force server to remain up
Server will stop listening for connection once a client connection has been terminated. But with option 'k', we can force a server
to remain running, even when no client is connected.
$ nc -l -k 8080
We now end this tutorial on how to use NC command, please feel free to send in any questions or queries you have regarding this article.
If nmap is not installed try nc / netcat command as follow. The -z flag can be used to tell nc to report open
ports, rather than initiate a connection. Run nc command with -z flag. You need to specify host name / ip along with the
port range to limit and speedup operation:
Connection to localhost 25 port [tcp/smtp] succeeded!
Connection to vip-1.vsnl.nixcraft.in 25 port [tcp/smtp] succeeded!
Connection to vip-1.vsnl.nixcraft.in 80 port [tcp/http] succeeded!
Connection to vip-1.vsnl.nixcraft.in 143 port [tcp/imap] succeeded!
Connection to vip-1.vsnl.nixcraft.in 199 port [tcp/smux] succeeded!
Connection to vip-1.vsnl.nixcraft.in 783 port [tcp/*] succeeded!
Connection to vip-1.vsnl.nixcraft.in 904 port [tcp/vmware-authd] succeeded!
Connection to vip-1.vsnl.nixcraft.in 993 port [tcp/imaps] succeeded!
One of the Linux command line tools I had initially under-estimated is netcat or just nc. 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.
The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it
shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the
192.168.0.1 IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:
$ nc -l 3333
On the other end, connect to the server with the following:
$ nc 192.168.0.1 3333
In this case, the keyboard acts as the stdin. Anything you type in the server machine's terminal is transfered to the client machine
and vice-versa.
Transfering Files
In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with
the following:
$ cat backup.iso | nc -l 3333
Receive backup.iso on the client machine with the following:
$ nc 192.168.0.1 3333 > backup.iso
As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing
with large files. In such cases, a pipe-monitoring utility like
pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered
in real-time on the server side:
$ cat backup.iso | pv -b | nc -l 3333
Of course, the same can be implemented on the client side by piping netcat's output through pv:
$ nc 192.168.0.1 3333 | pv -b > backup.iso
Other Examples
Netcat is extremely useful for 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:
Another useful thing is to 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 192.168.0.1 3333 | pv -b > mybackup.tar.gz
Security
It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable
in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH
tunnel.
Using an SSH tunnel has two advantages:
The data is transfered inside an encrypted tunnel, so it is well-protected.
You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections
will take place through SSH.
You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs
on this machine too.
$ cat backup.iso | nc -l 3333
On the client machine connect to the listening socket through an SSH tunnel:
This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after
file transfer finishes. For more information and explanation about it please read my article about
auto-closing SSH tunnels.
Telnet-like Usage
Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word "server"
from the "WordNet" database at the dict.org dictionary server, I'd do:
$ nc dict.org 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
server
n 1: a person whose occupation is to serve at table (as in a
restaurant) [syn: {waiter}]
2: (court games) the player who serves to start a point
3: (computer science) a computer that provides client stations
with access to files and printers as shared resources to a
computer network [syn: {host}]
4: utensil used in serving food or drink
.
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
QUIT
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]
Works as a Port Scanner too
A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just
informs about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:
$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!
In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.
The man page contains some more interesting examples, so take the time to read it.
Port scanning is done by system admin and hackers to find the open ports at some machine. It helps them to identify the venerability
in the system.
$nc -z -v -n 172.31.100.7 21-25
It can work in both TCP and UDP mode, default is TCP mode, to change to udp use -u option
z option tell netcat to use zero IO .i.e the connection is closed as soon as it opens and no actual data exchange
take place. v option is used for verbose option. n option tell netcat not to use the DNS lookup for the address.
This command will print all the open ports between 21 to 25.
Banner is a text that services sends when you connects to them. Banner are very usefull when you are trying to velberability in
the system as it identify the type and version of the services. NOTE not all services may send banner.
Once You have found the open ports you can easily grab the service banner by connecting to them using netcat.
$ nc -v 172.31.100.7 21
The Linux netcat command will connect to open port 21 and will print the banner of the service running at that port.
Ncat is a feature-packed networking utility which will read and write data across a network from the command line. Ncat was written
for the Nmap Project as a much-improved reimplementation of the venerable Netcat.
It uses both TCP and UDP for communication and is designed to be a reliable back-end tool to instantly provide network connectivity
to other applications and users. Ncat will not only work with IPv4 and IPv6 but provides the user with a virtually limitless number
of potential uses.
Among Ncat's vast number of features there is the ability to chain Ncats together, redirect both TCP and UDP ports to other sites,
SSL support, and proxy connections via SOCKS4 or HTTP (CONNECT method) proxies (with optional proxy authentication as well). Some
general principles apply to most applications and thus give you the capability of instantly adding networking support to software
that would normally never support it.
The Ncat Users' Guide contains full documentation including
many tips, tricks, and practical real-life examples! There is also an Ncat
man page for a quick usage summary.
Netcat is a simple Unix utility that reads and writes data across network connections, using TCP or UDP protocols. It is designed
to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same time, it is
a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you may need and has several
interesting built-in capabilities.
You can find the documentation in /opt/freeware/share/doc/packages/netcat/README.
The simplest example of its usage is to create a server-client chat system. Although this is a very primitive way to chat, it
shows how netcat works. In the following examples it is assumed that the machine that creates the listening socket (server) has the
192.168.0.1 IP address. So, create the chat server on this machine and set it to listen to 3333 TCP port:
$ nc -l 3333
On the other end, connect to the server with the following:
$ nc 192.168.0.1 3333
In this case, the keyboard acts as the stdin. Anything you type in the server machine's terminal is transfered to the client machine
and vice-versa.
Transfering Files
In the very same way it can be used to transfer files between two computers. You can create a server that serves the file with
the following:
$ cat backup.iso | nc -l 3333
Receive backup.iso on the client machine with the following:
$ nc 192.168.0.1 3333 > backup.iso
As you may have noticed, netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing
with large files. In such cases, a pipe-monitoring utility like
pv can be used to show a progress indicator. For example, the following shows the total amount of data that has been transfered
in real-time on the server side:
$ cat backup.iso | pv -b | nc -l 3333
Of course, the same can be implemented on the client side by piping netcat's output through pv:
$ nc 192.168.0.1 3333 | pv -b > backup.iso
Other Examples
Netcat is extremely useful for 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:
Another useful thing is to 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 192.168.0.1 3333 | pv -b > mybackup.tar.gz
Security
It is obvious that using netcat in the way described above, the data travels in the clear across the network. This is acceptable
in case of a local network, but, in case of transfers across the internet, then it would be a wise choice to do it through an SSH
tunnel.
Using an SSH tunnel has two advantages:
The data is transfered inside an encrypted tunnel, so it is well-protected.
You do not need to keep any open ports in the firewall configuration of the machine that will act as the server, as the connections
will take place through SSH.
You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs
on this machine too.
$ cat backup.iso | nc -l 3333
On the client machine connect to the listening socket through an SSH tunnel:
This way of creating and using the SSH tunnel has the advantage that the tunnel is automagically closed after file
transfer finishes. For more information and explanation about it please read my article about
auto-closing SSH tunnels.
Telnet-like Usage
Netcat can be used in order to talk to servers like telnet does. For example, in order to get the definition of the word "server"
from the "WordNet" database at the dict.org dictionary server, I'd do:
$ nc dict.org 2628
220 ..............some WELCOME.....
DEFINE wn server
150 1 definitions retrieved
151 "server" wn "WordNet (r) 2.0"
server
n 1: a person whose occupation is to serve at table (as in a
restaurant) [syn: {waiter}]
2: (court games) the player who serves to start a point
3: (computer science) a computer that provides client stations
with access to files and printers as shared resources to a
computer network [syn: {host}]
4: utensil used in serving food or drink
.
250 ok [d/m/c = 1/0/18; 0.000r 0.000u 0.000s]
QUIT
221 bye [d/m/c = 0/0/0; 16.000r 0.000u 0.000s]
Works as a Port Scanner too
A useful command line flag is -z. When it is used, netcat does not initiate a connection to the server, but just informs
about the open port it has found. Also, instead of a single port, it can accept a port-range to scan. For example:
$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!
In this example, netcat scanned the 80-90 range of ports and reported that port 80 is open on the remote machine.
The man page contains some more interesting examples, so take the time to read it.
2009/05/09: on RedHat based systems CFLAGS may have -Wall predefined which breaks socat's build process with something like
#error HAVE_BASIC_OFF_T is out of range: HAVE_BASIC_OFF_T..., please report this as bug.
In this case replace the configure file with this version
(resp. configure.gz or
configure.in) and restart the build process: make distclean; ./configure; make.
2009/05/07: socat version 1.7.1.1 fixes a couple of bugs, some of which could crash socat under some circumstances (CHANGES).
2009/04/04: the third beta version (2.0.0-b3) of
socat version 2 is ready for
download. It contains all new bug
fixes and features of 1.7.1.0 (plus fix:setenv, see below) and introduces the possibility to integrate external programs in address
chains (see doc/socat-addresschain.html
and doc/socat-exec.html).
2009/04/03: Todd Stansell reported a bug that crashed socat versions 1.7.0.0 to 1.7.1.0 (and all earlier versions with option
su) on systems without a native setenv() function, especially Solaris up to version 9. Here is the
patch.
2009/04/02: socat version 1.7.1.0 provides a few new address options to better control its closing behaviour - see
CHANGES.
2009/04/01: socat version 1.7.0.1 fixes some bugs (connect-timeout, SIGSEGV on listen, end-close).
2008/11/01: a public gitrepository containing
socat 1.6.0.0 and all later releases is available.
2008/10/15: socat version 1.7.0.0 brings support for
SCTP stream,
raw interface, and
generic sockets. New option
escape allows to interrupt raw terminal
connections. Listening and receiving sockets can set a couple of environment variables. Added base control of System V STREAMS. Lots
of corrections were performed. socat compiles on Mac OS X again.
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
2 Copying A File From One System To The Other
Let's say we want to copy the file ISPConfig-2.2.27.tar.gz from server1 to server2. To do this, run
server2:
nc -lp 1234 > ISPConfig-2.2.27.tar.gz
on server2 (1234 is some unused port - you can replace it with another value if you like). server2 will then wait for the file
ISPConfig-2.2.27.tar.gz on port 1234.
More recent versions of the netcat command (nc) will not allow the -p and -l options to be used at the same time, so instead
of:
nc -l -p 1234 | dd of=/dev/sda
you would type:
nc -l 1234 | dd of=/dev/sda
If you are using nc with dd to transfer an image of a partition from one machine to the other, one of the problems is that dd
and netcat won't show you a progress bar of the operation. One solution to this is to install pipe viewer by Andrew Wood. It then
allows you to pipe the netcat command to the pipe viewer, allowing you to view the progress of the entire operation and for debugging.
How do I use nc / netcat instead of messing with syslogd?
This is called one minute configuration. You can easily get output on 192.168.1.100 without using syslogd. All you have to do
is run netcat (nc) command, on 192.168.1.100: $ nc -l -p 30000 -u
Login to any other box, enter command: # modprobe netconsole [email protected]/eth0,[email protected]/00:19:D1:2A:BA:A8
Output should start to appear on 192.168.1.100 from 192.168.1.5 without configuring syslogd or anything else.
Your task is copy HostA /dev/sda to HostB's /dev/sdb using netcat command. First login as root user
Command to type on hostB (receiving end ~ write image mode)
You need to open port on hostB using netcat, enter : # netcat -p 2222 -l |bzip2 -d | dd of=/dev/sdb
Where,
-p 2222 : Specifies the source port nc should use, subject to privilege restrictions and availability. Make
sure port 2222 is not used by another process.
-l : Used to specify that nc should listen for an incoming connection rather than initiate a connection to
a remote host.
bzip2 -d : Compresses image using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding.
This will speed up network transfer ( -d : force decompression mode)
dd of=/dev/sda : /dev/sda is your hard disk. You can also specify partition such as /dev/sda1
Command to type on hostA (send data over a network ~ read image mode)
Now all you have to do is start copying image. Again login as root and enter: # bzip2 -c /dev/sda | netcat hostA 2222
OR use IP address: # bzip2 -c /dev/sda | netcat 192.168.1.1 2222
This process takes its own time.
A note about latest netcat version 1.84-10 and above
If you are using latest nc / netcat version above syntax will generate an error. It is an error to use -l option in conjunction
with the -p, -s, or -z options. Additionally, any timeouts specified with the -w option are ignored. So use nc command as follows.
On hostA, enter: # nc -l 2222 > /dev/sdb
On hostB, enter: # nc hostA 2222< /dev/sda
OR # nc 192.168.1.1 2222< /dev/sda
Using a second machine (hostB), connect to the listening nc process at 2222 (hostA), feeding it the file (/dev/sda)which is to
be transferred. You can use bzip2 as follows.
On hostA, enter: # nc -l 2222 | bzip2 -d > /dev/sdb
On hostB, enter: # bzip2 -c /dev/sda | nc 192.168.1.1 2222
You should definitely use bs=16M or something like that. Otherwise, the copy will take forever. Copying a 300 GB hard drive
over a 1 Gbps cross-over cable took about 1 1/2 hours or so using bs=16M Without this option, the same thing would have taken
about 7 hours.
In short use command as follows: # netcat -p 2222 -l |bzip2 -d | dd of=/dev/sdb
Netcat - The TCP/IP Swiss Army Knife Tom Armstrong
February 15, 2001
Overview
Netcat is a tool that every security professional should be aware of and possibly have in their 'security tool box'. In May/June
of 2000, insecure.org conducted a survey of 1200 Nmap users from the Nmap-hackers mailing list to determine their favorite security
tools. Netcat was the second most popular tool, not including Nmap. A quick search on securityportal (www.securityportal.com)
found 166 matches of netcat. Most of the matches describe or use netcat in some way. Netcat is a utility that is able to write and
read data across TCP and UDP network connections. If you are responsible for network or system security it essential that you understand
the capabilities of netcat.
Netcat should not be installed unless you have authority to do so. Never install any executable unless you can trust the providor.
If possible review the source and compile it yourself. To be safe only use netcat in a test environment.
Hobbit ([email protected]) created netcat in 1995 as a feature-rich network debugging and
exploration tool. Its purpose was to be able to create just about any type of network connection. According to Hobbit-
Some of the features of netcat are:
Outbound or inbound connections, TCP or UDP, to or from any ports
Full DNS forward/reverse checking, with appropriate warnings
Ability to use any local source port
Ability to use any locally-configured network source address>
Built-in port-scanning capabilities, with randomizer
Built-in loose source-routing capability
Can read command line arguments from standard input>
Slow-send mode, one line every N seconds
Optional ability to let another program service inbound connections>
Some of the potential uses of netcat:
Script backends
Scanning ports and inventorying services
Backup handlers
File transfers
Server testing and simulation
Firewall testing
Proxy gatewaying
Network performance testing
Address spoofing tests
Protecting X servers
1001 other uses you`ll likely come up with
The original version of netcat was released to run on Unix and Linux. Weld Pond ([email protected])
released the Windows NT version in 1998. The source code is available for both versions.
Remote command prompt anyone?
On a Windows NT server issue the following command in the directory that contains netcat:
nc -l -p1234 -d -e cmd.exe –L
This –l puts netcat into listen mode, the -p1234 tells netcat to use port 1234, the –d allows netcat to run detached from the
console, the –e cmd.exe tells netcat to execute the cmd.exe program when a connection is made, and the –L will restart Netcat with
the same command line when the connection is terminated.
On the client system issue the following command:
nc destination 1234
This command causes netcat to connect to the server named destination on port 1234. Immediately you are given a console connection
to the destination server. Be careful! To exit the remote console session type:
exit
You will be returned to your own console and will be able to reconnect to the destination server because netcat was started on
the destination server with the –L option.
FTP & drive mapping blocked?
To receive a file named newfile on the destination system start netcat with the following command:
nc –l –p 1234 >newfile
On the source system send a file named origfile to the destination system with the following command:
nc destination 1234 <origfile
Issue a ^C on the source system and your done. Be sure to check the file to be sure it is the same size as the original.
Hiding Netcat on Windows NT
Here are a few ways that a hacker could use to hide netcat on a system or use it behind a firewall:
Rename the executable or recompile with a different name. Beware that using a copy of netcat that you aren't sure how the
source was compiled is very dangerous. If possible review the source code and compile it yourself.
Detach from the console option (-d)
Use a port that is well known and allowed through any firewalls between the two systems.
Port Scanning
A scanning example from Hobbit is "nc -v -w 2 -z target 20-30". Netcat will try connecting to every port between 20 and 30 [inclusive]
at the target, and will likely inform you about an FTP server, telnet server, and mailer along the way. The -z switch prevents sending
any data to a TCP connection and very limited probe data to a UDP connection, and is thus useful as a fast scanning mode just to
see what ports the target is listening on. To limit scanning speed if desired, -i will insert a delay between each port probe. Even
though netcat can be used for port scanning it isn't its strength. A tool such as nmap is better suited for port scanning.
Netcat + Encryption = Cryptcat
Netcat is a useful tool as it is, but if someone were using it you would be able to at least get a feel for what they were doing.
At least you could before Cryptcat! Cryptcat is the standard netcat enhanced with Bruce Schneier's twofish encryption. It can be
found at www.farm9.com. Linux, OpenBSD, FreeBSD, and Windows versions are available.
So much for sniffing any netcat traffic!
Command Option Overview
Netcat accepts its commands with options first, then the target host, and everything thereafter is interpreted as port names or
numbers, or ranges of ports in M-N syntax. Netcat does not currently handle portnames with hyphens.
Option
Description
-d
Allows netcat to detach from the console on Windows NT.
-e
Executes a program if netcat is compiled with the
–DGAPING_SECURITY_HOLE.
-i
Sets the interval time. Netcat uses large 8K reads and writes. This basically sends data one line
at a time. This is normally used when data is read from files or pipes.
-g
Used to construct a loose-source-routed path for your connection. This is modeled after "traceroute".
-G
Positions the "hop pointer" within the list.
-l
Forces netcat to listen for an inbound connection. An example "nc –l –p 1234 <filename" tells
netcat to listen for a connection on port 1234 and once a connection is made to send the file named filename. The file is sent
whether the connecting system wants it or not. If you specify a target host netcat will only accept an bound connection only
from that host and if you specify one, only from the specified foreign source port.
-L
Restarts Netcat with the same command line that was used when the connection was started.. This
way you can connect over and over to the same Netcat process.
-n
Forces netcat to only accept numeric IP addresses and to not do any DNS lookups for anything
-o
Used to obtain a hex dump file of the data sent either way, use "-o logfile". The dump lines begin
with "<" or ">" to respectively indicate "from the net" or "to the net", and contain the total count per direction, and hex
or ascii representations of the traffic.
-p
Required for outbound connections. The parameter can be numeric or a name as listed in the services
file. If –p is not used netcat will bind to whatever unused port the systems gives it, unless the –r option is used.
-r
Causes port scanning to be done randomly. Normally it is done highest to lowest.
-s
Used to specifiy local network source address. Usage "-s ip-addr" or "-s name".
-t
Enables netcat to respond to telnet option negotiation if netcat is compiled with –DTELNET parameter.
Telnet daemons will get no useful answers, as they would from a telnet program.
-u
Tells netcat to use UDP instead of TCP.
-v
Controls the level of verbosity.
(without –n) netcat will do a full forward and reverse name and address lookup for the host, and warn you about the
all-to-common problem of mismatched names in the DNS.
Usually want to use the –w 3, which limits the time spent trying to make a connection.
If multiple ports are given –v must be specified twice.
-w
Limits the time spent trying to make a connection.
-z
Prevents sending any data to a TCP connection and very limited probe data to a UDP connection.
Use –i to insert a delay between each port probe. This is useful as a fast scanning mode just to see what ports the target
is listening on.
Conclusion
Netcat is a powerful tool that every security professional should be familiar with. It should be used with caution. I would not
recommend installing netcat on your production networks. I would suggest using it to test your firewall, and router configurations
in a test environment. It can also be used to test your operating system lockdown procedures. Be certain that you have the authority
to install and use netcat on your network before doing so. You might even want to review the source code to learn how Hobbit built
netcat and how Weld Pond ported it to the Windows platform.
So as an example, I will start two copies of netcat on the same machine locally:
adam@adamp:~$ netcat -l -p 1111
Here, using the -l switch, we are able to specify that netcat should go into listen mode i.e. to listen on
the specified port. Using p 1111 we are able to specify that we are using port 1111. To summarize,
netcat will sit and listen for TCP connections on port 1111 and print any data it receives out to the
screen. In another window we start netcat as:
adam@adamp:~$ netcat 127.0.0.1 1111
This will connect to host 127.0.0.1 (Locally) on port 1111.
We are now able to have a full two way data transmission, in Window 1:
adam@adamp:~$ netcat -l -p 1111This message was typed in WINDOW1. This message was typed in WINDOW2Now I'm going to end communication
with ^C (Ctrl-C)
adam@adamp:~$
And in Window 2:
adam@adamp:~$ netcat 127.0.0.1 1111
This message was typed in WINDOW1 This message was typed in WINDOW2 Now I'm going to end communication with ^C (Ctrl-C)
adam@adamp:~$
This is the most basic use of netcat described. Here, we are using a BASH shell, and thus we may pipe |
data to and from netcat, as well as using the redirection (>, >>, <, <<) to allow netcat to integrate into
the shell environment. We will now examine using netcat with one of the redirection operators. Lets
say we wanted to simply transmit a plaintext file. In one window, we will start netcat as:
adam@adamp:~$ netcat -l -p 1111 > outputfile
This will run netcat with the same parameters specified above, except it will redirect
all text received into outputfile.
adam@adamp:~$ echo > infile << EOF
> This is a test file.
> I am going to attempt to transmit this.
> Using Netcat.
> EOF
adam@adamp:~
$
Here, we have created some text in a file, and this is the file we are going to attempt to transmit:
And here we can confirm that it has. The -q 10 in the command line will quit after EOF (Otherwise
netcat will hang waiting for more input for cat and we will have to terminate it manually). The
parameter 10 causes it to quit after 10 seconds anyway.
Tar
Now, there is no reason why we can't integrate tar and netcat together, and use this to transmit a
directory across a netcat socket:
On one side: tar zcfp - /path/to/directory | nc -w 3 127.0.0.1 1234
The tar statement before the pipe tars and compresses (using gzip) every file within that directory,
before printing its output to stdout (The screen). It is then caught by the pipe, and piped to nc which in
this example, connects to 127.0.0.1 on port 1234 and sends it the data which would normally hit the
screen. The w 3 switch causes nc to allow for a 3 second timeout (In the event of a temporary
disconnection or similar).
On the other side: nc -l -p 1234 | tar xvfpz
This will listen on port 1234 for a connection, and will pass any data received to tar. Using the option v
we can print out filenames to screen:
Simple Socket Reply
With what we have learned so far, we are easily able to get netcat to listen in on a socket, and pump out
any data we wish when it receives a connection.
As an example:
while true; do echo "Leave me alone" | netcat -l -p 1234 w10; done
Consider this line. Firstly lets examine echo "Leave me alone" | netcat -l -p 1234 -w10
What we are doing here, is listening in on port 1234 with a wait time of 10 seconds. If/when we receive
a connection, pipe the results of echo "Leave me alone" to netcat. The w 10 is necessary, as otherwise
any connection made in will remain open forever. We can also optionally add a v in to the netcat
command line which will give us verbose information, i.e. who is connecting.
Every time a connection times out (either with the w 10 command line switch, or because a connection
has been made and then closed), netcat will exit. As this is not what we want, we put the command line
within a standard BASH: while CONDITION; do STATEMENT; done clause, which when the
condition is set to true will run forever.
Inetd
If you build netcat with GAPING_SECURITY_HOLE defined, you can use it as an "inetd" substitute
to test experimental network servers that would otherwise run under "inetd".
A script or program will have its input and output hooked to the network the same way, perhaps sans
some fancier signal handling.
Given that most network services do not bind to a particular local address, whether they are under
"inetd" or not, it is possible for netcat avoid the "address already in use" error by binding to a specific
address.
This lets you [as root, for low ports] place netcat "in the way" of a standard service, since inbound
connections are generally sent to such specifically-bound listeners first and fall back to the ones bound
to "any".
This allows for a one-off experimental simulation of some service, without having to screw around
with inetd.conf. Running with -v turned on and collecting a connection log from standard error is
recommended.
Netcat as well can make an outbound connection and then run a program or script on the originating
end, with input and output connected to the same network port.
This "inverse inetd" capability could enhance the backup-server concept described above or help
facilitate things such as a "network dialback" concept.
The possibilities are many and varied here; if such things are intended as security mechanisms, it may
be best to modify netcat specifically for the purpose instead of wrapping such functions in scripts.
Speaking of inetd, netcat will function perfectly well *under* inetd as a TCP connection redirector for
inbound services, like a "plug-gw" without the authentication step.
This is very useful for doing stuff like redirecting traffic through your firewall out to other places like
web servers and mail hubs, while posing no risk to the firewall machine itself.
Put netcat behind inetd and tcp_wrappers, perhaps thusly:
and you have a simple and effective "application relay" with access control and logging. Note use of
the wait time as a "safety" in case realwww isn't reachable or the calling user aborts the connection --
otherwise the relay may hang there forever.
Inetd/tcp_wrappers and netcat information, courtesy of: http://www.spyder-fonix.com/netcat.html
Talking to syslogd -r
Syslog Daemons running with the r switch log not only their own hosts data but accept remote UDP
broadcasts. They listen in on UDP port 514.
"echo '<0>message' | nc -w 1 -u loggerhost 514"
If loggerhost is running syslogd r and can accept your messages.
Note the -u switch here, to put netcat into UDP mode. Specifying the <0> before your message ensures
that your message receives top priority within syslog (kern.emerg)
Scanning
The scanning features of netcat can be used against yours or your friends networks to get useful
information about which hosts have certain ports open. You can also send a precompiled data file to
each. For example:
Will scan 127.0.0.1 on ports 20-250, 500-600 and 5990-7000. Every port that it finds is open, it will
pipe the output of echo "EXIT" being the word "EXIT" to that port.
The results are as follows:
(For the sanity of my server, I have blocked out a number of parts from certain service banners.)
And now with UDP scanning: nc -v -w 1 127.0.0.1 u 20-250 500-600 5990-7000 we receive:
-v was to put netcat into verbose mode, and u was telling netcat to fall into UDP mode.
Spoofing
"Your TCP spoofing possibilities are mostly limited to destinations you can source-route to, while
locally bound to your phony address.
Many sites block source-routed packets these days for precisely this reason.
If your kernel does oddball things when sending source-routed packets, try moving the pointer
around with -G. You may also have to fiddle with the routing on your own
machine before you start receiving packets back.
Warning: some machines still send out traffic using the source address of the outbound interface,
regardless of your binding, especially in the case of localhost.
Check first. If you can open a connection but then get no data back from it, the target host is probably
killing the IP options on its end [this is an option inside TCP wrappers and several other packages],
which happens after the 3-way handshake is completed.
If you send some data and observe the "send-q" side of "netstat" for that connection increasing but
never getting sent, that's another symptom. Beware: if Sendmail 8.7.x detects a source-routed SMTP
connection, it extracts the hop list and sticks it in the Received: header!"
http://www.spyder-fonix.com/netcat.html
Spoofing is a useful technique, as is source routing.
Source routing is almost obsolete now, and the majority of routers filter out source routed packets.
Source routing in a nutshell is basically setting the route that the packet will take at the source, and
storing that information along with the packet.
Normally, each router makes its own mind up as to where a packet will get routed, and follows its
predefined routing tables. If we have access to all routers between our device and the target device
(which can be one machine if youre talking about your local LAN server), then we are able to modify
the routing entries on those devices, bind a phoney address to our machine and source route packets to
the intended destination.
Spoofing is where we modify the source address of a packet so that the recipient believes it came from
a different address. There are two problems with this;
•
A number of clever ISP routers will drop packets with incorrect source addresses.
•
If the destination host does get to receive your spoofed packet, it will send data back to the
spoofed address (instead of ours). This does have a number of uses however in the example of
ICMP ping flooding a host and spoofing the source address to Microsoft.com (as a theoretical
example).
Simple Response Service
echo -e "GET http://www.google.com HTTP/1.0\n\n" | nc w 5www.google.com 80
We make a connection to google.com on port 80 (Web server port), and put in an HTTP request for
http://www.google.com. At this point, we are presented with the HTML spurted out by the web server.
We can pipe this to "| less" or similar or even our favourite HTML interpreter.
Take a look at this example, and you will see what we have done here. In one instance we have created
an HTML file webfrontend and we now pipe that HTML to any incoming connection to netcat on port
1111.
We then make a connection on the larger window, using lynx http://127.0.0.1:1111 and we have
made ourselves a tiny http server, possibly could be used as a holding page server or something similar.
Advanced Uses
Now we'll set up a server netcat to listen on port 1111. We'll also set up a client netcat to talk to the real
web server on port 81. By getting them to pass all data they receive to each other, together they form a
proxy; something that sits in the middle of a network connection. Here are the commands we use:
mknod backpipe p
nc -l -p 1111 0backpipe
Because bash pipes only carry data in one direction, we need to provide a way to carry the responses as
well. We can create a pipe on the local filesystem to carry the data in the backwards direction with the
mknod command; this only needs to be run once.
Requests coming into the proxy from the client arrive at the first nc, listening on port 1111. They get
handed off to the "tee" command, which logs them to the inflow file, then continue on to the second nc
command which hands them off to the real web server. When a response comes back from the server, it
arrives back at the second nc command, gets logged in the second tee command to the outflow file, and
then gets pushed into the backpipe pipe on the local filesystem. Since the first netcat is listening to that
pipe, these responses get handed to that first netcat, which then dutifully gives them back to the original
client.
While the above example is for watching tcp streams going to and from a web server, the above
technique is useful for watching any tcp connection. In fact, since nc also works with udp packets
something telnet can't do - it should be possible to even set up udp proxies this way.
Windows Command Shell
As we can see from the image above, we have started netcat with options of l p 1234 e
"c:\windows\system32\cmd.exe". These are the same options as with the Unix shell, and this should
theoretically start a cmd.exe shell listening in on port 1234:
As you see from above, this has succeeded. Netcat and program execution for Windows can be used in
exactly the same way.
Unauthorised Proxying
Assume you are an administrator of a Linux router. Using the methods above, as well as your iptables
software, you can proxy a users outgoing connection through your nc proxy. Using iptables with the j
DNAT target and the j REDIRECT target, you can transparently proxy outgoing connections through
to any other ports you want, and what better to use than your nc proxy?
Cryptcat
Cryptcat can be found at: http://sourceforge.net/projects/cryptcat/ and is the ultimate companion for
Netcat. It includes a lightweight version of Netcat, featuring encrypted transport properties. (Just for
those superbly paranoid!). Useful for encrypting communications out of a network.
Final Thoughts
If I was given one tool on a freshly installed PC, I would ask for Netcat. Due to its versatility and its
huge range of uses, it can be used as a transfer tool, a scanning tool, a server, a proxy and so much
more. I have put down everything useful I can think of, and welcome any further suggestions directed
to [email protected]
Command Cheat Sheet
The following are the most useful uses of netcat:
For windows nc d can be used to detach from the console.
nc -l -p [port] will create a simple listening tcp port. Add u to put into UDP mode.
nc -e [program] To redirect stdin/stdout from program.
nc -w [timeout] To set a timeout before netcat automatically quits. (Used within a loop usually)
program | nc To pipe output of program to netcat
nc | program To pipe output of netcat to program
nc -h Help sheet
nc -v To put into verbose mode, or use v v to put into ultra-verbose mode!
nc -g or nc G Source routing flags
nc -t Use telnet negotiation (If performing telnet negotiation)
.
nc -o [file] Hex dump traffic to file
nc -z No I/O (Used for scanning ports)
Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol. It
is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same
time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you would need
and has several interesting built-in capabilities.
It provides access to the following main features:
Outbound and inbound connections, TCP or UDP, to or from any ports.
Featured tunneling mode which allows also special tunneling such as UDP to TCP, with the possibility of specifying
all network parameters (source port/interface, listening port/interface, and the remote host allowed to connect to the tunnel.
Built-in port-scanning capabilities, with randomizer.
Advanced usage options, such as buffered send-mode (one line every N seconds), and hexdump (to stderr or to a specified file)
of trasmitted and received data.
Optional RFC854 telnet codes parser and responder.
netcat could forward data stream from stdin to a TCP or UDP socket, and from a TCP or UDP socket to stdout. Just like the
cat program to forward data from stdin to stdout. According to unconfirmed sources, that's the origin of the netcat
program name.
/usr/bin/yes generates stream of y
zw@q ~ % yes
y
y
y
y
y
y
y
Press ctrl-C to stop the y's. You can generated stream on no too.
zw@q ~ % yes no
no
no
no
no
no
The hub (hub.c) and cable (cable.c)
utilities are certainly inspired by netcat which could forward data stream from a socket to stdout, and from stdin to a socket. Did
I forget to recommend the netcat companion documentation for you to read? ;-) Hub is designed to be like a server, and cable is designed
to be like a client. Instead of forwarding data between stdin/stdout and a socket, hub and cable forward and multiplex data
from a socket to any other sockets. That's where the names come from. They're just like Ethernet hub and cable. Lets' see a screenshot.
Yeah, screenshot! ;-)
zw@q ~ % ./hub
lullaby internetworks lab: (server alike) hub $Revision: 1.2 $
Copyright (C) 2001 zhaoway <[email protected]>
Usage: hub [hub buffer size] [tcp port number] [number of hub ports]
o hub buffer size is in bytes. for example 10240.
o tcp port number is at least 1024 so i do not need to be root.
o number of hub ports is at least 2. happy.
zw@q ~ %
Hub will listen on a TCP port simulating a many port Ethernet hub. Data come in from one hub port will be forwarded to other hub
ports. You could test the hub alone without cable using netcat. Note: nc is the acronym for netcat.
Launch hub in the console A: ConA % ./hub 10240 10000 2
From console B, connect a netcat: ConB % nc localhost 10000
From console C, connect another netcat: ConC % nc localhost 10000
Then you could type in ConC and read the output in ConB, vice versa.
Then there is cable:
zw@q ~ % ./cable
lullaby internetworks lab: (client alike) cable $Revision: 1.2 $
Copyright (C) 2001 zhaoway <[email protected]>
Usage: cable [cable buffer size] [1st ip] [1st port] [2nd ip] [2nd port] ..
o cable buffer size is in bytes. for example 10240.
o ports should be listening or connection attempts will fail.
o number of ip addr and port pairs is at least 2.
zw@q ~ %
Cable is more or less like a shared Ethernet bus coaxial cable. It forwards and multiplexes data between listening socket daemons.
Let's test it too.
Launch a netcat daemon in ConA: ConA % nc -l -p 10000
Launch another netcat daemon in ConB: ConB % nc -l -p 10001
Then you could type in ConA and read the output from ConB, vice versa.
There are some interesting techniques used in developing hub and cable. Notably the select() function call. But for
now, we will focus on our course to reinvent the /usr/bin/yes first. ;-)
It's not a very easy task to reinvent /usr/bin/yes using netcat and hub and cable. I could only give a cheat answer.
And that's why I need to set the buffer size command line argument. But anyway, let's begin!
The main idea is as following. First we set up a three-port hub, then we using cable to connect two hub port together, after that
we could using netcat to echo any character into the remain free hub port. It's like the following diagram:
| cable
\|/ ,---------,
| | |
V V V
,--[ ]-------[ ]-------[ ]--.
| A B C |
| three-port hub |
`---------------------------'
Because the nature of the hub, data sent in from port A, will be forwarded to port B and port C, since port B and C are connected
by a cable, the data come out of the hub will go right back in, and then being multiplexed and forwarded to port A and circulating
in the cable loop to eternity. Eventually port A will receive infinite copies of the original data sent in.
Lets' construct the device.
In ConA, we launch the three-port hub: ConA % ./hub 10240 10000 3
In ConB, we loop the cable: ConB % ./cable 10240 127.0.0.1 10000 127.0.0.1 10000
Now after we finished construction of our device, then we will using netcat to finally finish our reinvention of /usr/bin/yes.
ConC % echo "y" | nc localhost 10000
The tricky exercises left for the reader is: what if we change the buffer size of both cable and hub from 10240 to 1? You could
try and see for yourself.
The Last but not LeastTechnology is dominated by
two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt.
Ph.D
FAIR USE NOTICEThis site contains
copyrighted material the use of which has not always been specifically
authorized by the copyright owner. We are making such material available
to advance understanding of computer science, IT technology, economic, scientific, and social
issues. We believe this constitutes a 'fair use' of any such
copyrighted material as provided by section 107 of the US Copyright Law according to which
such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free)
site written by people for whom English is not a native language. Grammar and spelling errors should
be expected. The site contain some broken links as it develops like a living tree...
You can use PayPal to to buy a cup of coffee for authors
of this site
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or
referenced source) and are
not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society.We do not warrant the correctness
of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be
tracked by Google please disable Javascript for this site. This site is perfectly usable without
Javascript.