An overview of the features and basic techniques for using the netcat utility. Useful examples of using the netcat utility in Linux Netcat commands

Displaying a test HTML page to a client with a regular browser with one command (port 8080):
(echo -e "HTTP/1.1 200 OK\nContent-Type: text/html\n\n Hello World";) | nc -vv -l -p 8080
Transferring a file to a client with a regular browser in one command (port 8080):
(echo -e "HTTP/1.1 200\nContent-Disposition: attachment; filename=target-name-client-sees\nContent-Type: application/octet-stream\nConnection: close\n"; cat filename- on disk) | nc -vv -l -p 8080

how to use nc

(http://handynotes.ru/2010/01/unix-utility-netcat.html )

Let's start with a few simple examples and further we will use them as base.
If you remember, I said that netcat is the Swiss army knife. What would this knife be if it couldn't be used like a regular knife? This is why netcat can be used instead of regular telnet:

$nc www.google.com 80

It's actually more convenient than regular telnet because you can end the connection at any time by pressing Ctrl+C and it handles binary data like normal (no escape sequences, nothing).
You can add the “-v” option to display the results of actions in more detail, and the option (-vv) to get statistics on how many bytes were transferred during the current connection session.
Netcat can be used as a server. If you run it like below, it will listen on port 12345 (on all interfaces):

$ nc -l -p 12345

Now if you connect to port 12345 of this host, whatever you type will be sent to the remote side, which tells us that netcat can be used as a chat server. Run on one of the computers:

# On computer A with IP 10.10.10.10
$ nc -l -p 12345

And connect to it from another:

# On computer B
$nc 10.10.10.10 12345

Now both sides can talk!
This way of talking where both parties can talk to each other makes possible use nc for network I/O! For example, you can send an entire directory from one computer to another by piping tar through nc on the first computer, and redirecting the output to another tar process on the second.
Suppose you want to transfer files from the /data directory of computer A with IP 192.168.1.10 to computer B (with any IP). It's simple:


$ tar -cf - /data | nc -l -p 6666


# On computer B
$nc 192.168.1.10 6666 | tar-xf-

Don't forget to combine the pipeline with the Pipe Viewer described in the previous article to see statistics on how fast the transfer is!
A single file can be sent more simply:

# On computer A with IP 192.168.1.10
$cat file | nc -l -p 6666


# On computer B
$ nc 192.168.1.10 6666 > file

You can even copy and restore an entire disk using nc:

# On computer A with IP 192.168.1.10
$ cat /dev/hdb | nc -l -p 6666


# On computer B
$ nc 192.168.1.10 6666 > /dev/hdb

Note: The “-l” option cannot be used with “-p” on Mac computers! The solution is to simply replace “-l -p 6666? with “-l 6666?. Like here:

# now nc is listening on port 6666 for Mac computers
$ nc -l 6666

An outstanding use of netcat is port scanning. Netcat is not the best tool for this job, but it does it (the best, of course, is nmap):

$ nc -v -n -z -w 1 192.168.1.2 1-1000
(UNKNOWN) 445 (microsoft-ds) open
(UNKNOWN) 139 (netbios-ssn) open
(UNKNOWN) 111 (sunrpc) open
(UNKNOWN) 80 (www) open
(UNKNOWN) 25 (smtp) : Connection timed out
(UNKNOWN) 22 (ssh) open

The "-n" option prevents DNS lookups, "-z" does not wait for a response from the server, and "-w 1? sets the connection timeout to 1 second.
Another non-trivial use of netcat is as a proxy. Both port and host can be forwarded. Look at this example:

$ nc -l -p 12345 | www.google.com 80

This command starts nc on port 1234 and redirects all connections to google.com:80. If you now connect to this computer on port 12345 and make a request, you will find that you receive no data in response. This is correct because we have not set up a bidirectional channel. If you add a second channel, you will receive your data on a different port:

$ nc -l -p 12345 | nc www.google.com 80 | nc -l -p 12346

After sending a request on port 12345, receive your response data on port 12346.
Probably the most powerful feature of netcat is to run any process as a server:

$ nc -l -p 12345 -e /bin/bash

The "-e" option spawns the execution of input and output redirected via a network socket. Now if you connect to the host on port 12345 you can use bash:
$ nc localhost 12345
ls-las
total 4288
4 drwxr-xr-x 15 pkrumins users 4096 2009-02-17 07:47 .
4 drwxr-xr-x 4 pkrumins users 4096 2009-01-18 21:22 ..
8 -rw——- 1 pkrumins users 8192 2009-02-16 19:30 .bash_history
4 -rw-r—r— 1 pkrumins users 220 2009-01-18 21:04 .bash_logout

(http://execbit.ru/2011/05/23/netcat/)
1 Transfer files (execute the first command on the receiving machine, the second on the sending machine:

$ nc -l 31334 > filename $ nc 172.16.69.143 31334< filename

$ nc -f /var/log/messages | nc -l 31334 $ nc 172.16.69.143 31334

3 Use instead of telnet (first - telnet server, second - client):

$ nc -l -p 31334 -e /bin/sh $ nc 172.16.69.143 31334

4 Scan for open ports:

$ nc -z execbit.ru 1-1024

5 Fingerprint services based on banners:

$ echo "QUIT" | nc-execbit.ru 1-1024

6 Organize a reverse shell (the first is the client, the second is the server, but the shell will open from the server to the client).

Almost in any Linux distribution there is a small inconspicuous utility netcat, or simply nc. This program can create TCP sockets either in server mode to listen for a connection, or in client mode to connect to a server. And to be honest, it doesn't really matter to netcat whether you're going to use it as a server or as a client - it's only job is to collect data from stdin and pass it to the specified network address.

The simplest use case for netcat is to create a client-server chat. Although this is a very primitive way to create a chat, it clearly shows how this utility works. In the following examples, it will be assumed that the machine creating the idle socket (server) has an IP address of 192.168.0.1. So, we create a chat server that will listen for connections on TCP port 3333:

$ nc -l 3333

Now we can connect from another computer to this server:

$nc 192.168.0.1 3333

In this case, the keyboard acts as stdin. Everything typed on the keyboard on the server side will be transferred to the client terminal, and vice versa.

File transfer

In exactly the same way, you can use netcat to transfer files between two computers. With the following command, you can create a server that will prepare the file for transfer:

You can get the backup.iso file on another computer as follows:

$ nc 192.168.0.1 3333 > backup.iso

As you can see, netcat does not display any information about the data transfer process. When working with large files, this can be quite inconvenient. To solve this problem, you can use the utility (progress viewer). In this example, on the server side, information about the speed and volume of transmitted data will be displayed in real time:

$ cat backup.iso | pv -b | nc -l 3333

Similarly, you can show statistics on the client side:

$nc 192.168.0.1 3333 | pv -b > backup.iso

Other examples

The netcat utility can also be useful for creating an image partition hard disk with the ability to send it to a remote server on the fly:

$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333

And on a remote machine, you can accept the created image like this:

$nc 192.168.0.1 3333 | pv -b > myhdb5partition.img.gz

If you need to send a group of files - for example, a set of configuration files - you can combine netcat and tar archiver:

$ tar -czf - /etc/ | nc -l 3333

The hyphen as a filename in the tar options is necessary in order to print the output of the archiver to stdin, which is then redirected to netcat. You can accept the created backup on a remote machine in the same way as described earlier:

$nc 192.168.0.1 3333 | pv -b > mybackup.tar.gz

Safety

Obviously, when using netcat in this way, information is transmitted over the network in its original unencrypted form. For transferring non-critical data, this is perfectly acceptable, but for transferring any valuable information, it is reasonable to use netcat in combination with an SSH tunnel.

Using an SSH tunnel has two advantages:

  1. The information is transmitted inside an encrypted tunnel so that it is well protected;
  2. There is no need to open any additional ports in the firewall configuration on the server as the connection will be established via SSH

On the server side, the file in netcat is exposed in exactly the same way as described earlier:

$ cat backup.iso | nc -l 3333

But on the client side, we connect to the netcat socket waiting for connections through an SSH tunnel:

$ ssh -f -L 23333:127.0.0.1:3333 [email protected] sleep10; \nc 127.0.0.1 23333 | pv -b > backup.iso

Of course, there are other ways to put a connection into an SSH tunnel, but creating and using a tunnel in this way has the useful feature that the tunnel is automatically closed when the data transfer through netcat is finished.

…and a portable port scanner

Incredibly, netcat can also be used to scan open ports. The -z option will help with this:

$ nc -z 192.168.0.1 80-90 Connection to 192.168.0.1 80 port succeeded!

In this example, netcat scanned the port range 80-90 and reported that port 80 was open on the remote machine.

The man pages for the netcat utility also contain a number of other useful tips and tricks. interesting examples use of this program.

In this article, I will review the popular network utility netcat and useful tricks for working with it.


Netcat is a Unix utility that allows you to establish TCP and UDP connections, receive data from there and transmit them. Despite its usefulness and simplicity, many do not know how to use it and unfairly bypass it.


Using this utility, you can perform some steps when conducting penetration testing. This can be useful when the attacked machine does not have (or will attract attention) installed packages, there are restrictions (for example, IoT/Embedded devices), etc.


What can be done with netcat:

  • Scan ports;
  • Forward ports;
  • Collect service banners;
  • Listen port (bind for reverse connection);
  • Download and upload files;
  • Output raw HTTP content;
  • Create a mini chat.

In general, using netcat, you can replace part of the unix utilities, so this tool can be considered a kind of combine for performing certain tasks.

Practical examples

In many cases, if it is necessary to check a particular host, they use telnet, or their own services to identify the host or banner. How netcat can help us:

Checking for an open TCP port 12345

$ nc -vn 192.168.1.100 12345
nc: connect to 192.168.1.100 12345 (tcp) failed: Connection refused

$ nc -v 192.168.1.100 22
Connection to 192.168.1.100 22 port succeeded!
SSH-2.0-OpenSSH

Scanning TCP ports with netcat:

$ nc -vnz 192.168.1.100 20-24

With such a scan, there will be no connection to the port, but only the output of a successful connection:


nc: connectx to 192.168.1.100 port 20 (tcp) failed: Connection refused
nc: connectx to 192.168.1.100 port 21 (tcp) failed: Connection refused
found 0 associations
found 1 connections:
1: flags=82
outif en0
src 192.168.1.100 port 50168
dst 192.168.1.100 port 22
rank info not available
TCP aux info available
Connection to 192.168.1.100 port 22 succeeded!
nc: connectx to 192.168.1.100 port 23 (tcp) failed: Connection refused
nc: connectx to 192.168.1.100 port 24 (tcp) failed: Connection refused

Scanning UDP ports.

Root privileges are required to scan UDP ports with nmap. If they are not there, in this case the netcat utility can also help us:


$ nc -vnzu 192.168.1.100 5550-5560
Connection to 192.168.1.100 port 5555 succeeded!

Sending a UDP packet

$ echo -n "foo" | nc -u -w1 192.168.1.100 161

This can be useful when interacting with network devices.

Receiving data on the UDP port and outputting the received data

$ nc -u localhost 7777

After the first message, the output will be stopped. If you need to receive multiple messages, then you need to use while true:


$ while true; do nc -u localhost 7777; done

File transfer. Using netcat, you can both receive files and transfer files to a remote host:


nc 192.168.1.100 5555< 1.txt
nc -lvp 5555 > /tmp/1.txt

Netcact as a simple web server.

Netcat can act as a simple web server to display html pages.


$ while true; do nc -lp 8888< index.html; done

Using a browser at: http://netcat host:8888/index.html. To use the standard web server port number 80, you will need to run nc with root privileges:


$ while true; do sudo nc -lp 80< test.html; done

Chat between nodes

On the first node (192.168.1.100):


$ nc -lp 9000

On the second node:


$nc 192.168.1.100 9000

After executing the commands, all characters entered into the terminal window on any of the nodes will appear in the terminal window of the other node.

Reverse shell

Using netcat, you can organize a convenient reverse shell:


nc -e /bin/bash -lp 4444

Now you can connect from the remote host:


$nc 192.168.1.100 4444

You should not give up if there are no certain tools, often quite cumbersome, sometimes the task can be solved with improvised means.

Department of Road Design

Lab #1

on the course "Informatics"

Performed by a student of group No. 114359 Raykhman Sergey Yuryevich

checked

Lab #1

Topic: Norton Commander Utility

Target: Learn how to manage your computer with Norton Commander

Norton Commander allows you to perform the following functions: 1) perform MS-DOS functions, 2) Display the contents of directories on disks, 3) display a directory tree on disk, 4) view files, 5) edit text files, 6) copy, move, rename, delete files, 7) change file attributes.

launch Norton Commander

To launch Norton Commander, type in command line"nc" and press "Enter". Exit Norton Commander - F10 or ALT+X

View of the screen and panels

After launching Norton Commander, two rectangular windows (panels) appear on the screen.


Below these panels is the MS-DOS prompt and an information line with function key values.

F1 HELP - brief information about the assignment of keys when working with NC.

F2 MENU - user menu

F3 VIEW - viewing a text file, document

F4 EDIT - edit text file

F5 COPY - copy files

F6 RENMOV - forward, rename file

F7 MKDIR - create directory(s)

F8 DELETE - delete files or subdirectories

F9 PULL DN - menus containing NC operating modes are displayed on the top line of the screen.

F10 QUIT - exit from NC

Menu on keypress F9

Left and Right - sets the modes for displaying information on the left and right panels

Files - various operations are performed with files

Commands - executes various NC commands, sets NC configuration and operating modes.

One of the menu items is highlighted, use the arrows to select another item<¬>, <­>, <®>, <¯>and the "Enter" key is pressed.

File selection

To copy, delete, move files, select them by pressing the Ins key. To cancel the selection, press “Ins” again. Information about the number of selected files appears at the bottom of the panel.

Create a directory

To create a directory, press the "F7" key, type its name, press "Enter".

To enter a directory, press the “Enter” key on its name. When you press the "ALT+F10" keys, a directory tree is displayed on the screen. The cursor keys can be used to quickly move to the desired subdirectory.

Main keys NC

TAB - switch to another panel

ALT + F1 - display in the left panel of the table of contents of another disk.

ALT + F2 - display in the right panel of the table of contents of another disk

CTRL + F1 - remove the left panel from the screen

CTRL+F2 - hide the right panel from the screen

CTRL+O - remove both panels

CTRL+U - swap panels

To start the computer, you need to type “LOGIN” in the prompt line, enter the password (335_2).

Lab assignments

Using the commands, create a subdirectory structure on the disk:


nc [-46bCDdhklnrStUuvZz] [-I length][-i interval][-O length][-P proxy_username][-p source_port][-q seconds][-s source][-T toskeyword][-V rtable] [-w timeout][-X proxy_protocol][-x proxy_address[:port]] [destination] [port]

Options

-4 forces nc to use IPv4 addresses only.
-6 forces nc to use IPv6 addresses only.
-b Allow broadcast.
-C Send as line ending.
-D Enable debugging on the socket.
-d Do not attempt to read from stdin .
-h Print out nc help.
-I length Specifies the size of the TCP receive buffer .
-i interval Specifies a delay time interval between lines of text sent and received. Also, causes a delay time between connections to multiple ports.
-k forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.
-l Used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host . It is an error to use this option in conjunction with the -p, -s, or -z options. Additionally, any timeouts specified with the -w options are ignored.
-n Do not do any DNS or service lookups on any specified addresses, hostnames or ports .
-O length Specifies the size of the TCP send buffer.
-P proxy_username Specifies a username to present to a proxy server that requires authentication . If no username is specified then authentication will not be attempted. Proxy authentication is only supported for HTTP CONNECT proxies at present.
-p source_port Specifies the source port nc should use, subject to privilege restrictions and availability.
-q seconds after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever.
-r Specifies that source or destination ports should be chosen randomly instead of sequentially within a range or in the order that the system assigns them.
-S Enables the RFC 2385 TCP MD5 signature option.
-s source Specifies the of the interface that is used to send the packets . For UNIX-domain datagram sockets, specifies the local temporary socket file to create and use so that datagrams can be received. It is an error to use this option in conjunction with the -l option.
-T toskeyword Change IPv4 TOS value. toskeyword may be one of critical, inetcontrol, low cost, low delay, netcontrol, throughput, reliability, or one of the DiffServ Code Points: ef, af11 ... af43, cs0 ... cs7; or a number in either hex or decimal .
-t Causes nc to send RFC 854 DON"T and WON"T responses to RFC 854 DO and WILL requests. This makes it possible to use nc to script telnet sessions.
-U Specifies to use UNIX-domain sockets.
-u Use UDP instead of the default option of TCP. For UNIX-domain sockets, use a datagram socket instead of a stream socket. If a UNIX-domain socket is used, a temporary receiving socket is created in /tmp unless the -s flag is given.
-V rtable Set the routing table to be used. The default is 0.
-v have nc give more verbose output.
-w timeout Connections which cannot be established or are idle timeout after timeout seconds. The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.
-X proxy_protocol Requests that nc should use the specified protocol when talking to the proxy server. Supported protocols are " 4 " (SOCKS v.4), " 5 " (SOCKS v.5) and " connect" (HTTPS proxy). If the protocol is not specified, SOCKS version 5 is used.
-x proxy_address[:port] Requests that nc should connect to destination using a proxy at proxy_address and port. If port is not specified, the well-known port for the proxy protocol is used (1080 for SOCKS, 3128 for HTTPS).
-Z DCCP mode.
-z Specifies that nc should only scan for listening daemons, without sending any data to them. It is an error to use this option in conjunction with the -l option.

destination can be a numerical IP address or a symbolic hostname (unless the -n option is given). In general, a destination must be specified, unless the -l option is given (in which case the local host is used). For UNIX-domain sockets, a destination is required and is the socket path to connect to (or listen on if the -l option is given).

port can be a single integer or a range of ports. Ranges are in the form nn-mm. In general, a destination port must be specified, unless the -U option is given.

Client/Server model

It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For example:

Nc -l 1234

nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:

Nc 127.0.0.1 1234

There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection was set up nc does not really care which side is being used as a 'server' and which side is being used as a 'client'. The connection may be terminated using an EOF (‘ ^D’).

There is no -c or -e option in modern netcat, but you still can execute a command after connection being established by redirecting file descriptors. Be careful here because opening a port and let anyone connected execute arbitrary command on your site is DANGEROUS. If you really need to do this, here is an example:

On ‘server’ side:

Rm-f /tmp/f; mkfifo /tmp/f cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f

On ‘client’ side:

nc host.example.com 1234

(shell prompt from host.example.com)

Start by using nc to listen on a specific port, with output captured into a file:

nc -l 1234 > filename.out

Using a second machine, connect to the listening nc process, feeding it the file that is to be transferred:

nc host.example.com 1234< filename.in

After the file is transferred, the connection will close automatically.

Talking to servers

It is sometimes useful to talk to servers "by hand" rather than through a user interface. It can aid in troubleshooting, when it might be necessary to verify what data a server is sending in response to commands issued by the client. For example, to retrieve the homepage of a website:

Printf "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80

Note that this also displays the headers sent by the web server. They can be filtered using a tool such as sed, if necessary.

More complicated examples can be built up when the user knows the format of requests required by the server. As another example, an e-mail may be submitted to an SMTP server using:

Nc [-C] localhost 25<< EOF HELO host.example.com MAIL FROM:< >RCPT TO:< >DATA Body of e-mail. . QUIT EOF

port scanning

It may be useful to know which ports are open and running services on a target machine. The -z flag can be used to tell nc to report open ports, rather than initiate a connection. Usually, it's useful to turn on verbose output to stderr by use this option in conjunction with -v option.

Nc -zv host.example.com 20-30 Connection to host.example.com 22 port succeeded! Connection to host.example.com 25 port succeeded!

The port range was specified to limit the search to ports 20 - 30 , and is scanned by increasing order.

You can also specify a list of ports to scan, for example:

nc -zv host.example.com 80 20 22 nc: connect to host.example.com 80 (tcp) failed: Connection refused nc: connect to host.example.com 20 (tcp) failed: Connection refused Connection to host.example .com port succeeded!

The ports are scanned by the order you given.

Alternatively, it might be useful to know which server software is running, and which versions. This information is often contained in the greeting banners. To retrieve these, it is necessary to first make a connection, and then break the connection when the banner was retrieved. This can be accomplished by specifying a small timeout with the -w flag, or perhaps by issuing a "QUIT" command to the server:

Echo "QUIT" | nc host.example.com 20-30 SSH-1.99-OpenSSH_3.6.1p2 Protocol mismatch. 220 host.example.com IMS SMTP Receiver Version 0.84 Ready

Examples

nc -p 31337 -w 5 host.example.com 42

Opens a TCP connection to port 42 of host.example.com, using port 31337 as the source port, with a timeout of 5 seconds.

nc -u host.example.com 53 nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

The same as the above example, but this time enabling proxy authentication with username " ruser" if the proxy requires it.

related commands

ifconfig- View or modify the configuration of network interfaces.

Share