|
Softpanorama
(slightly skeptical)
Open Source Software Educational Society |
May the
source be with you,
but remember the KISS principle ;-)
|
Netcat -- reading from and writing to network connections
on either TCP or UDP
netcat is a network utility for reading from and writing to network
connections on either TCP or UDP. Hobbit (hobbit@avian.org)
created netcat in 1995 as a network analog of Unix cat tool. The original
version is no longer maintained. 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 now includes:
/usr/bin/nc
/usr/share/doc/nc-1.84/README
/usr/share/doc/nc-1.84/scripts/README
/usr/share/doc/nc-1.84/scripts/alta
/usr/share/doc/nc-1.84/scripts/bsh
/usr/share/doc/nc-1.84/scripts/dist.sh
/usr/share/doc/nc-1.84/scripts/irc
/usr/share/doc/nc-1.84/scripts/iscan
/usr/share/doc/nc-1.84/scripts/ncp
/usr/share/doc/nc-1.84/scripts/probe
/usr/share/doc/nc-1.84/scripts/web
/usr/share/doc/nc-1.84/scripts/webproxy
/usr/share/doc/nc-1.84/scripts/webrelay
/usr/share/doc/nc-1.84/scripts/websearch
/usr/share/man/man1/nc.1.gz
Fully POSIX compatible rewrite from scratch is known as
GNU Netcat. The current Version
of
GNU Netcat 0.7.1 It is maintained by Giovanni Giacobbi.
http://sourceforge.net/projects/nmap-ncat/?abmode=1
A Windows version of netcat was created by Chris Wysopal. Among
the most interesting clones is Socat, which extends Netcat to support many
other socket types, SSL encryption, SOCKS proxies, and more. It can be used,
for example, as a TCP relay. Another interesting implementation
is Chris Gibson's
Ncat.
Other takes on Netcat include OpenBSD's nc, Cryptcat, Netcat6, PNetcat, SBD.
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
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
http://www.dest-unreach.org/socat/ socat has some new modern
functionality, but the idea is the same as netcat
Notes:
- This is a Spartan WHYFF (We Help
You For Free) site written by people for whom English
is not a native language.
Some amount of grammar and spelling errors should be
expected.
- The site contain some broken links
as it develops like a living tree...
Please try to use Google, Open directory,
etc. to find a replacement link (see
HOWTO search the WEB for details). We would appreciate
if you can
mail us a correct link.
|
|
|
|
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/13: Gentil Kiwi updated his Cygwin based binary socat
packages at
http://www.gentilkiwi.com/telechargements-s43-t-socat.htm#englishversion.
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 git
repository 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.
1 Preliminary Note
I'm using two systems in this article:
- server1.example.com: IP address
192.168.0.100
- server2.example.com: IP address
192.168.0.101
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.
On server1, run
server1:
nc -w 1 server2.example.com 1234 < ISPConfig-2.2.27.tar.gz
to start the file transfer.
Selected Comments
Maximo Migliari:
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.
target machine:
nc -l 1234 | pv | dd of=/dev/sda
source machine:
dd if=/dev/sda | nc 192.168.0.12 1234
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 6666@192.168.1.5/eth0,30000@192.168.1.100/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.
Further readings:
Our sample setup
-----------------------
HostA // 192.168.1.1
------------------------
sda
NETWORK
sdb
------------------------
HostB // 192.168.1.2
-------------------------
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
Further readings
How do I improve performance?
As suggested by anonymous user:
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, 2001Overview
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 (hobbit@avian.org) 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 (weld@l0pht.com) 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.
References
1. Insecure.org, "Top 50 Security Tools"
URL: http://www.insecure.org/tools.html
(August 21, 2000)
2. Hobbit, "New tool available: Netcat"
URL:
http://lists.insecure.org/bugtraq/1995/Oct/0028.html (October 28,
1995)
3. Weld Pond, "Netcat 1.10 for NT"
URL:
http://www.l0pht.com/~weld/netcat/readment.txt (February 2, 1998)
4. Hobbit, "Netcat 1.10"
URL:
http://www.l0pht.com/~weld/netcat/readme.html (March 20, 1996)
5. Farm9, "cryptcat = netcat + encryption"
URL:
http://farm9.com/content/Free_Tools/Cryptcat (October 2, 2000)
6. Hobbit, "Netcat 1.10"
URL:
http://www.l0pht.com/~weld/netcat/readme.html (March 20, 1996)
Simple File Transfer
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:
adam@adamp:~$ cat infile | netcat 127.0.0.1 1111 q 10adam@adamp:~$
http://www.learnsecurityonline.com © Learn Security Online, Inc.
2004-2005
Hopefully this has now been transmitted to the otherside:
adam@adamp:~$ cat outputfile
This is a test file.
I am going to attempt to transmit this.
Using Netcat.
adam@adamp:~
$
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:
www stream tcp nowait nobody /etc/tcpd /bin/nc -w 3 realwww 80
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:
Echo EXIT | nc -w 1 127.0.0.1 20-250 500-600 5990-7000
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:
adam@adamp:~$ nc -u -v -w 1 127.0.0.1 20-250 500-600 5990-7000localhost
[127.0.0.1] 250 (?) openadam@adamp:~$
-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 adam@apnicsolutions.com
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 <zw@debian.org>
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 <zw@debian.org>
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
- Arrange the cable:
ConC % ./cable 10240 127.0.0.1 10000
127.0.0.1 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
y
y
y
y
y
y
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.
Have fun and good luck!
In case of broken links
please try to use Google search. If you find the page please notify
us about new location
Netcat
- Wikipedia, the free encyclopedia
The GNU Netcat
-- Official homepage
ONLamp.com Netcat and Reverse Telnet
Play
with the Lovely Netcat LG #74
freshmeat.net
Project details for netcat
Wonders of 'dd' and 'netcat' Cloning OS harddrives
SecurityDocs
NetCat Tutorial
Netcat – The TCP-IP
Swiss Army Knife
nc man page
The GNU Netcat
-- Official homepage
The GNU Netcat -- Official homepage -- Downloads
freshmeat.net
Project details for netcat SecurityFocus also hosts the
Windows version of Netcat.
Copyright © 1996-2009 by Dr. Nikolai Bezroukov.
www.softpanorama.org was
created as a service to the UN Sustainable Development Networking Programme (SDNP)
in the author free time.
Submit
comments This document is an industrial compilation designed and created
exclusively for educational use and is placed under the copyright of the
Open Content License(OPL).
Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made
for educational purposes only in compliance with the fair use doctrine.
Disclaimer:
- The statements, views and opinions presented on
this web page are those of the author and are not endorsed by, nor do they necessarily
reflect, the opinions of the author present and former employers, SDNP or any other
organization the author may be associated with.
- We do not warrant the correctness of the information provided or its
fitness for any purpose
- In no way this site is associated with or endorse cybersquatters
using
the term "softpanorama" with other main or country domains (e.g. softpanorama.com) with
bad faith intent to profit from the goodwill belonging to
someone else.
Last modified:
August 16, 2009