Ncat is a rewrite from scratch of the popular (but long deprecated) Netcat program, nc; there are other variants of Ncat, some rewritten from the original code and others written from scratch. As a result, similar programs with similar functionality may be named differently or have different features and options, but the basic functionality is the same. This white paper describes Ncat, a variant of Netcat from the author of Nmap; Ncat is a popular program and is installed by default instead of Netcat in some distributions. Ncat is a multi-functional network utility that reads and writes data over the network from the command line. Ncat was written for the Nmap project as a greatly improved version of the venerable Netcat program.
It uses TCP and UDP protocols for communication and is designed as a reliable mechanism that can instantly connect to other programs and users over the network. Ncat not only works with IPv4 and IPv6, but also offers users a potentially unlimited number of usage options. Among the many features of Ncat is the ability to create chains by forwarding TCP and UDP ports to other sites, SSL support, support for proxy connections via SOCKS4 or HTTP proxy (CONNECT method) (with additional authentication). There are Some general principles apply to most applications, so network support can be instantly added to software that doesn’t normally support it.
Using:
ncat [опції] [ім'я_хоста] [порт]
Options:
Опції, що приймають час, мають на увазі секунди. Додати 'ms' для мілісекунд, 's' для секунд, 'm' для хвилин або 'h' для годинника (наприклад, 500ms). -4 Використовувати тільки IPv4 -6 Використовувати тільки IPv6 -U, --unixsock Використовувати лише доменні сокети Unix -C, --crlf Використовувати CRLF для послідовності EOL (кінець рядка) -c, --sh-exec <команда> Виконати цю команду через /bin/sh -e, --exec <команда> Виконати задану команду --lua-exec <имя_файла> Виконати цей скрипт Lua -g hop1[,hop2,...] Вільні вихідні точки переходу (максимум 8) -G <n> Вільний вихідний покажчик маршруту (4, 8, 12, ...) -m, --max-conns <n> Максимум <n> одночасних підключень -h, --help Показати довідку -d, --delay <время> Очікування між читанням/записом -o, --output <имя_файла> Зберегти дані сесії у файл -x, --hex-dump <имя_файла> Зберегти дані сесії у шістнадцятковому вигляді у файл -i, --idle-timeout <время> Таймаут бездіяльності читання/запису -p, --source-port порт Вказати порт джерела для використання -s, --source addr Вказати адресу джерела для використання (не впливає на -l) -l, --listen Прослуховувати порт чекаючи на вхідні з'єднання -k, --keep-open Приймуть кілька з'єднань у режимі прослуховування -n, --nodns Не перетворювати імена хостів через DNS -t, --telnet Відповідати на переговори Telnet -u, --udp Використовувати UDP замість дефолтного TCP --sctp Використовувати SCTP замість дефолтного TCP -v, --verbose Встановити рівень вербальності (можна вказати кілька разів) -w, --wait <время> Таймаут з'єднання -z Режим нульового введення/виводу, повідомляти тільки про статус з'єднання --append-output Додавати, а не закривати вказані вихідні файли --send-only Тільки надсилати дані, ігнорувати отримання; вийти на EOF --recv-only Тільки отримувати дані, ніколи нічого не надсилати --allow Дозволити підключатися до Ncat лише заданому хосту --allowfile Файл зі списком хостів, дозволеним для підключення до Ncat --deny Заборонити вказаним хостам підключатися до Ncat --denyfile файл зі списком хостів, кому заборонено підключатися до Ncat --broker Увімкнути посередництво підключень Ncat --chat Запустити простий чат-сервер Ncat --proxy <адрес[:порт]> Вказати адресу хоста, через яку виконувати проксування --proxy-type <тип> Вказати тип проксі ("http" або "socks4" або "socks5") --proxy-auth <auth> Аутентифікація з проксі-сервером HTTP або SOCKS --ssl Підключитися або прослуховувати з SSL --ssl-cert Вказати файл SSL сертифіката (PEM) для прослуховування --ssl-key Вказати приватний ключ SSL (PEM) для прослуховування --ssl-verify Верифікувати надійність та доменне ім'я сертифіката --ssl-trustfile Файл PEM, що містить довірені SSL сертифікати --ssl-ciphers Список шифрів, що містить SSL шифри для використання --ssl-alpn Список протоколів ALPN для використання. --version Показати версію Ncat та вийти
Ncat — socket concatenation and redirection
ncat [ОПЦІЇ...] [ім'я_хоста] [порт]
Ncat operates in two main modes: connect mode and listening mode. Other modes, such as HTTP proxy, act as special cases of the two main modes. In connection mode, Ncat runs as a client. The server is listening.
In connect mode, the hostname and port arguments tell you what to connect to. The host_name must be specified, it can be a host name (such as a domain name, for example) or an IP address. If a port is specified, it must be a decimal number. If port is omitted, the default value of 31337 is used.
In listening mode, host_name and port control the address of the server to bind to. In listener mode, both arguments are optional. If the hostname is omitted, all available IPv4 and IPv6 addresses are listened by default. If port is omitted, port 31337 is listened by default.
-4 (IPv4 only) Force IPv4 only.
-6 (IPv6 only) Force IPv6 only.
-U, –unixsock (Use Unix domain sockets) Use Unix domain sockets instead of network sockets. This option can be used alone for streaming sockets or in combination with –udp for datagram sockets. The -U mode is described later in the subsection titled “Unix Domain Sockets”.
-u, –udp (Use UDP) Use UDP for connections (default is TCP).
–sctp (Use SCTP) Use SCTP for connection (default is TCP). SCTP support is implemented in TCP-compatible mode.
To understand the following Ncat options, you need to know about the Internet Protocol options. There are a number of optional parameters that can be present in Internet Protocol version 4 datagrams. Typically, they configure a number of behavior options, such as the method to be used when routing the source, some controls and validations, and a number of experimental features.
Free outgoing routing
Source-free routing is an IP option that can be used for address translation. LSR is also used to implement mobility in IP networks.
Free egress routing uses the egress routing option in IP to record the set of routers that should visit the packet. The packet’s destination is changed to the next router the packet should visit. By setting a forwarding agent (FA) on one of the routers that the packet must visit, an LSR is equivalent to tunneling. If the corresponding node stores the LSR parameters and reverses them, this is equivalent to the mobile IPv6 functionality.
The name free outgoing routing is due to the fact that only part of the path is specified in advance.
Strict outbound routing
Strict outgoing routing differs from loose outgoing routing in that each step of the route where the packet is sent is determined in advance.
-g hop1[,hop2,…] (Free outgoing routing) Sets the hops (hop, nodes) of free outgoing routing. You can use -g once with a comma-separated list of hops, use -g multiple times with a single node to build a list, or combine two. Hops can be specified as IP addresses or hostnames.
-G ptr (Set Outbound Routing Pointer) Sets the IPv4 outbound route pointer to use with -g. The argument must be a multiple of 4 and not greater than 28. Not all operating systems support setting this pointer to anything other than four.
-p port, –source-port port (Specify source port) Set port number for Ncat binding.
-s host, –source host (Specify source address) Specify address for Ncat binding.
See the Access Control Options section for information on setting restrictions on the hosts that can connect to the Ncat listener.
-l, –listen (Listen for connections) Listen for connections instead of connecting to the remote machine.
-m numconns, –max-conns numconns (Specifies maximum number of connections) The maximum number of simultaneous connections accepted by an instance of Ncat. The default is 100 (on Windows it is 60).
-k, –keep-open (Allow multiple connections) Normally, the listening server accepts only one connection and then closes when the connection is closed. This option makes the server accept several simultaneous connections and wait for other connections, even if the first ones were closed. It should be combined with –listen. In this mode, there is no way for Ncat to know when network input has finished, so it will run until explicitly stopped. This also means that it will never close its output stream, so any program reading from Ncat and looking for the end of the file will also hang.
–broker Allow multiple parties to connect to a centralized Ncat server and communicate with each other. Ncat can provide communication between systems behind NATs or otherwise unable to connect directly. This option is used in conjunction with –listen to enable broker mode on the –listen port.
–chat (Ad-hoc “chat server”) The –chat option enables a chat mode designed for text exchange between multiple users. Intermediary connections are enabled in chat mode. Before sending to other connected devices, Ncat alerts each received message with an identifier. The ID is unique for each connected client. This helps distinguish who sent what. Additionally, non-printable characters, such as control characters, are escaped to prevent damage to the terminal.
–ssl (Use SSL) In connection mode, this option transparently negotiates an SSL session with an SSL server to securely encrypt the connection. This is especially useful for communicating with HTTP servers with SSL support, etc. In server mode, this option listens for incoming SSL connections, not plain text traffic. In UDP connection mode, this option includes Datagram TLS (DTLS). This is not supported as a server.
–ssl-verify (Verify Server Certificates) In client mode, –ssl-verify is –ssl, but this option also requires server certificate verification. Ncat comes with a default set of trusted certificates in the ca-bundle.crt file. Some operating systems provide a default list of trusted certificates, these will also be used if available. Use –ssl-trustfile to specify your list. Use -v one or more times to get details about verification failures. Ncat does not check certificates for revocation. This option has no effect in server mode.
–ssl-cert certfile.pem (Specify SSL certificate) This option passes the location of the PEM-encoded certificate files used for server (listening) or client (connected mode) authentication. Use in combination with –ssl-key.
–ssl-key keyfile.pem (Specify SSL private key) This option passes the location of the PEM-encoded private key file that comes with the certificate specified by the –ssl-cert option.
–ssl-trustfile cert.pem (Certificate Trusted List) This option sets the list of certificates that are trusted for certificate verification. It has no effect unless combined with –ssl-verify. The argument to this option is the name of the PEM file containing the trusted certificates. Typically, this file will contain certificates from Certification Authorities, although it may also contain server certificates. When this option is used, Ncat does not use its default certificates.
–ssl-ciphers cipher-list (Specifies a list of SSL ciphers) This option sets a list of the set of ciphers that Ncat will use when connecting to servers or when accepting SSL connections from clients. The syntax is described in the OpenSSL ciphers(1) page:
man 1 ciphers
and defaults to:
ALL:!aNULL:!eNULL:!LOW:!EXP:!RC4:!MD5:@STRENGTH
–ssl-alpn ALPN list (Specifies a list of ALPNs) This option allows you to specify a comma-separated list of protocols for sending files over TLS extension Application-Layer Protocol Negotiation. Not supported by all versions of OpenSSL.
–proxy host[:port] (Specifies the proxy address) Requests are proxied via host:port using the protocol specified with –proxy-type . If no port is specified, the common port for the proxy protocol is used (1080 for SOCKS and 3128 for HTTP). However, when specifying an IPv6 HTTP proxy server using an IP address rather than a hostname, a port number must also be specified. If the proxy requires authentication, use –proxy-auth.
–proxy-type protocol (Specifies the proxy protocol) In connect mode, this option sets the protocol to be used to connect via proxy to the host specified in –proxy . In listening mode, this option causes Ncat to act as a proxy server using the specified protocol. The available protocols in connect mode are: http (CONNECT), socks4 (SOCKSv4), and socks5 (SOCKSv5). Currently the server only supports http. If this option is not used, the default protocol is http.
–proxy-auth user [:password] (Specifies proxy credentials) In connect mode, specifies the credentials to be used to connect to the proxy server. In listening mode, specifies the credentials that will be requested from connecting clients.
For use with –proxy-type http or –proxy-type socks5, the form must be username:password. For –proxy-type socks4 should be username only.
-e command, –exec command (Execute Command) Execute the specified command after the connection is established. The command must be specified as the full path to the file. All output from the remote client will be sent to the application and responses sent back to the remote client over the socket, making your command line application interactive over the socket. When combined with –keep-open , Ncat will handle multiple simultaneous connections to the port/application you specify as inetd. Ncat will only accept a certain maximum number of simultaneous connections, controlled by the -m option. By default, this value is 100 (60 on Windows).
-c command, –sh-exec command (Execute command via sh) Same as -e except it tries to execute the command via /bin/sh. This means that you don’t have to specify the full path to the command and shell features like environment variables are available.
–lua-exec file (Execute .lua script) After establishing a connection, runs the specified file as a Lua script using the built-in interpreter. Script standard input and standard output are redirected to connection data streams.
All exec options add the following variables to the child environment:
NCAT_REMOTE_ADDR, NCAT_REMOTE_PORT IP address and port number of the remote host. In connection mode, this is the target address, in listening mode, it is the client address.
NCAT_LOCAL_ADDR, NCAT_LOCAL_PORT IP address and port number of the local end of the connection.
NCAT_PROTO Protocol used: One of TCP, UDP, or SCTP.
–allow host[,host,…] (Allow all connections) Only hosts from the specified list will be allowed to connect to the Ncat process. All other access attempts will be disabled. If there is a conflict between –allow and –deny, –allow takes precedence. The host specifications have the same syntax that Nmap uses.
–allowfile file (Allow hosts to connect from file) Does the same as –allow except it allows hosts not specified directly on the command line, but those specified in a file, these hosts must be listed one at a time to each line.
–deny host[,host,…] (Deny connection) Starts Ncat with a list of hosts that will be allowed to connect to the Ncat listener. If they try to connect, the specified hosts will have their session silently terminated. If -allow and -deny conflict, -allow takes precedence. The syntax for specifying hosts is the same as in Nmap.
–denyfile file (Reject connections from hosts from a file) This option has the same functionality as –deny, except that the hosts are not specified on the command line, but are taken from a file, where they are listed in the format: each host on a separate line.
These options accept a time parameter. It defaults to seconds, although you can prefix ms, s, m, or h to interpret the values as milliseconds, seconds, minutes, or hours.
-d time, –delay time (Specifies delay time) Sets the delay interval for sent lines. This effectively limits the number of rows that Ncat will send in a given period. This can be useful for sites with low bandwidth or for other purposes such as dealing with annoying iptables –limit options
-i time, –idle-timeout time (Specify idle timeout) Sets a fixed timeout for idle connections. If the timeout is reached, the connection is terminated.
-w time, –wait time (Specifies timeout connection) Sets a fixed timeout for connection attempts.
-o file, –output file (saves session data) Saves (dumps) session data to a file.
-x file, –hex-dump file (Saves session data in hexadecimal format) Saves session data in hexadecimal format to a file.
–append-output Run Ncat with –append-ouput along with -o and/or -x and it will append the resulting output instead of truncating the specified output files.
-v, –verbose (Be Verbose) Run Ncat with -v and it will be verbose and display all sorts of useful connection information. Using more than once (-vv, -vvv…) will increase verbosity.
-C,–crlf (Use CRLF as EOL) This option tells Ncat to convert line endings from LF to CRLF when input is accepted from standard input. This is useful for talking to some strict servers directly from a terminal over one of the many plain text protocols that use CRLF as end-of-line.
-h, –help (Help) Shows a short help with popular options and options, then exits.
–recv-only If this option is passed, Ncat will only receive data and not try to send anything.
–send-only If this option is passed, then Ncat will only send data and ignore anything received. This option also causes Ncat to close the network connection and exit after receiving EOF standard input.
–no-shutdown (No shutdown and half-duplex mode) If passed, Ncat will not shutdown the socket after seeing EOF in stdin. This is done for backward compatibility with OpenBSD netcat, which exhibits this behavior when run with the ‘-d’ option.
-t, –telnet (Answer Telnet Negotiations) Handles Telnet DO/DONT WILL/WONT Telnet negotiations. This makes it possible to script Telnet sessions with Ncat.
–version (Show version) Show Ncat version number and exit.
The -U option (same as -unixsock) causes Ncat to use Unix domain sockets instead of network sockets. Unix domain sockets exist as entries in the file system. You must pass the name of the socket to connect or listen on. For example, to make a connection:
ncat -U ~/unixsock
To listen on a socket:
ncat -l -U ~/unixsock
The listener mode will create a socket if it does not exist. The socket will continue to exist after exiting the program.
Both streaming and datagram domain socket types are supported. Use -U for streaming sockets or combine it with –udp for datagram sockets. Datagram sockets require an output socket to connect to. By default, an output socket with an arbitrary filename will be created if required; it will be deleted when you exit the program. Use –source to specify a path to attract a socket with a specific name.
The exit code indicates whether the connection was completed successfully. 0 means that there were no errors, 1 means that a network error occurred, for example, “Connection refused” or “Connection reset”. 2 is reserved for other errors, such as an invalid option or a nonexistent file.
Connecting to example.org using TCP on port 8080:
ncat example.org 8080
Listen for incoming connections using the TCP protocol on port 8080:
ncat -l 8080
Forward TCP port 8080 on the local machine to the host on port 80:
ncat --sh-exec "ncat example.org 80" -l 8080 --keep-open
Listen on port 8081 and mount /bin/bash to execute the commands passed:
ncat --exec "/bin/bash" -l 8081 --keep-open
Bind the shell to TCP port 8081, restrict access to hosts from the local network, and limit the maximum number of simultaneous connections to three:
ncat --exec "/bin/bash" --max-conns 3 --allow 192.168.0.0/24 -l 8081 --keep-open
Connect to smtphost:25 via a SOCKS4 server on port 1080:
ncat --proxy socks4host --proxy-type socks4 --proxy-auth joe smtphost 25
Connect to smtphost:25 via a SOCKS5 server on port 1080:
ncat --proxy socks5host --proxy-type socks5 --proxy-auth joe:secret smtphost 25
Create HTTP proxy server localhost on port 8888:
ncat -l --proxy-type http localhost 8888
Send a file via TCP port 9899 from HOST2 (client) to HOST1 (server):
HOST1:
ncat -l 9899 > outputfile
HOST2:
ncat HOST1 9899 < inputfile
Send in the other direction (from HOST1 to HOST2), making Ncat a “single file” server:
HOST1:
ncat -l 9899 < inputfile
HOST2:
ncat HOST1 9899 > outputfile
Installation in Kali Linux
sudo dpkg --add-architecture i386 && sudo apt update
sudo apt install ncat
Installation in BlackArch
The program is installed in BlackArch.
sudo nmap -S nmap
Installation in Debian, Ubuntu, Linux Mint and their derivatives
sudo apt install nmap