Ncat Ncat: Your General-Purpose Network Connector Ncat is a general-purpose command-line tool for reading, writing, redirecting, and encrypting data across a network. It aims to be your network Swiss Army knife, handling a wide variety of security testing and administration tasks. Ncat is suitable for interactive use or as a network-connected back end for other tools. Ncat can: Act as a simple TCP/UDP/SCTP/SSL client for interacting with web servers, telnet servers, mail servers, and other TCP/IP network services. Often the best way to understand a service (for fixing problems, finding security flaws, or testing custom commands) is to interact with it using Ncat. This lets you you control every character sent and view the raw, unfiltered responses. Act as a simple TCP/UDP/SCTP/SSL server for offering services to clients, or simply to understand what existing clients are up to by capturing every byte they send. Redirect or proxy TCP/UDP/SCTP traffic to other ports or hosts. This can be done using simple redirection (everything sent to a port is automatically relayed somewhere else you specify in advance) or by acting as a SOCKS or HTTP proxy so clients specify their own destinations. In client mode, Ncat can connect to destinations through a chain of anonymous or authenticated proxies. Run on all major operating systems. We distribute Linux, Windows, and Mac OS X binaries, and Ncat compiles on most other systems. A trusted tool must be available whenever you need it, no matter what computer you're using. Encrypt communication with SSL, and transport it over IPv4 or IPv6. Act as a network gateway for execution of system commands, with I/O redirected to the network. It was designed to work like the Unix utility cat, but for the network. Act as a connection broker, allowing two (or far more) clients to connect to each other through a third (brokering) server. This enables multiple machines hidden behind NAT gateways to communicate with each other, and also enables the simple Ncat chat mode. These capabilities become even more powerful and versatile when combined. Ncat is our modern reinvention of the venerable Netcat (nc) tool released by Hobbit in 1996. While Ncat is similar to Netcat in spirit, they don't share any source code. Instead, Ncat makes use of Nmap's well optimized and tested networking libraries. Compatibility with the original Netcat and some well known variants is maintained where it doesn't conflict with Ncat's enhancements or cause usability problems. Ncat adds many capabilities not found in Hobbit's original nc, including SSL support, proxy connections, IPv6, and connection brokering. The original nc contained a simple port scanner, but we omitted that from Ncat because we have a preferred tool for that function. This guide starts with examples of basic Ncat usage, then moves on to more advanced features. Those are followed by practical sections which use examples to demonstrate how Ncat can solve common real-world problems. A few neat Ncat tricks are covered as well. Basic usage Ncat always operates in one of two basic modes: connect modeconnect mode and listen mode.listen mode In connect mode, Ncat initiates a connection (or sends UDP data) to a service that is listening somewhere. For those familiar with socket programming, connect mode is like using the connect function. In listen mode, Ncat waits for an incoming connection (or data receipt), like using the bind and listen functions. You can think of connect mode as client mode and listen mode as server mode. To use Ncat in connect mode, run ncat host port host may be a hostname or IP address, and port is a port number. Listen mode is the same, with the addition of the (Ncat option> option (or its (Ncat option) alias): ncat --listen host port ncat -l host port In listen mode, host controls the address on which Ncat listens; if you omit it, Ncat will bind to all local interfaces (INADDR_ANY). If the port number is omitted, Ncat uses its default port 31337.default port of Ncat Typically only privileged (root)privileged users users may bind to a port number lower than 1024.portsreservedreserved ports A listening TCP server normally accepts only one connection and will exit after the client disconnects. Combined with the (Ncat option) option, Ncat accepts multiple concurrent connections up to the connection limit. With (or for short), the server receives everything sent by any of its clients, and anything the server sends is sent to all of them. By default, Ncat uses TCP. The option (Ncat option) or (Ncat option) enables UDP instead, and (Ncat option) enables SCTP.SCTPin Ncat Ncat listens on both IPv4 and IPv6, and connects to either address family as well. The (Ncat option) option forces IPv6-only, and (Ncat option) forces IPv4-only. See for more details. The rest of this guide documents all the Ncat options through descriptions and examples. For a quick summary of options at any time, run ncat --help (Ncat option) or man ncat. A Connect Mode Example A good way to start learning about Ncat (and network protocols in general) is to connect to a network service and talk with it. In this case we use Ncat to manually retrieve a web page from an HTTP server, just as web browsers do in the background when you visit a web site. shows a (truncated) sample session. Try it yourself! Text in bold is what you type; everything else is what comes back. The blank line after the GET line is required—just hit enter twice. Ncat as a web browser GET HTTP method (Ncat option)example of $ ncat -C scanme.nmap.org 80 GET / HTTP/1.0 HTTP/1.1 200 OK Date: Thu, 05 Feb 2009 15:31:40 GMT Server: Apache/2.2.2 (Fedora) Last-Modified: Mon, 19 May 2008 04:49:49 GMT ETag: "fc8c91-2e3-44d8e17edd540" Accept-Ranges: bytes Content-Length: 739 Connection: close Content-Type: text/html; charset=UTF-8 <html> <head> <title>Go ahead and ScanMe!</title> </head> Here we have instructed Ncat to connect to the host scanme.nmap.orgscanme.nmap.org on port 80, the port for HTTP. The option turns on CRLFCRLF replacement, which replaces any line endings you type with CRLF. CRLF line endings are required by many protocols, including HTTP, though many servers will accept a plain newline (LF) character. GET / HTTP/1.0 requests the root document of the server; we are retrieving the same document named by the URL http://scanme.nmap.org:80/. The web server responds with a status code (HTTP/1.1 200 OK), followed by the HTTP header and the text of the web page. If you try this with other web servers, note that many of them are actually virtual hosts and you will need to send the Host header field. See RFC 2616RFC 2616 for more information about HTTP. A Listen Mode Example So much for using Ncat as a web browser. What about a web server? That's possible too; it just takes a bit of preparation. The first step is to create the document to serve. Create a text file called hello.http with these contents:

Hello, world!

]]>
Now run the command ncat -l localhost 8080 < hello.http. This instructs Ncat to listen on the local port 8080 and read hello.http on its input. Ncat is now primed to send the contents of the file as soon as it receives a connection. Now open a web browser and type in the address http://localhost:8080/. shows a sample of what will appear.
Web page served by Ncat
In the terminal where you ran Ncat, you will see everything the web browser sent to request the page. You should see a GETGET HTTP method line like the one you sent in the connect mode example. This shows that Ncat by default both sends and receives. If you try to refresh the page, it won't work. That's because Ncat ran out of input; it won't re-send what has already been sent. For more information on making a server that continually responds to requests, see the examples in . More HTTP server tricks can be found here in .
Protocols TLSSSL Transport Layer Security (TLS)SSL Ncat can use TCP, UDP, SCTP, SSL, IPv4, IPv6, and various combinations of these. TCP over IPv4 is the default. TCP,TCPin Ncat the Transmission Control Protocol, is the reliable protocol that underlies a great deal of Internet traffic. Ncat makes TCP connections by default. TCP may be combined with SSL. UDP,UDPin Ncat the User Datagram Protocol, is an unreliable protocol often used by applications that can't afford the overhead of TCP. Use the (Ncat option) option to make Ncat use UDP. UDP may be secured using the option, which enables Datagram TLS (DTLS)DTLSDatagram TLS. SCTP,SCTPin Ncat the Stream Control Transmission Protocol, is a newer reliable protocol. It is selected with the (Ncat option) option. Ncat uses a TCP-compatible subset of SCTP features, not including multiple streams per connection or message boundaries. SCTP may be combined with SSL. SSLSSLin Ncat (Secure Sockets Layer) or TLS (Transport Layer Security) provides security to network traffic when used properly. Use the (Ncat option) to turn SSL on; it works with TCP or SCTP. See for instructions and caveats. IPv4,IPv4in Ncat the Internet Protocol version 4, is the most popular version of the Internet Protocol in use. Using the puts Ncat into IPv4-only mode; only IPv4 addresses will be used even if, for example, as hostname resolves to IPv6 addresses as well. IPv6IPv6in Ncat is the lesser-used successor to IPv4. Use (Ncat option) to put Ncat into IPv6-only mode. By default, Ncat will listen on both IPv4 and IPv6, and will connect to resolved addresses in the order they are returned by the operating system. Connection Brokering One of Ncat's most useful and unique abilities is called connection brokering. A listening Ncat in broker mode accepts connections from multiple clients. Anything received from one of the clients is sent back out to all the others. In this way an Ncat broker acts like a network hub, broadcasting all traffic to everyone connected. Activate broker mode with the option, which must be combined with . It wouldn't make sense for a client to be a broker. See for details on using brokering to transfer files through restrictive firewalls, and for using brokering to set up multi-user chat rooms. SSL Ncat can encrypt its traffic using SSL. In connect mode, simply add the (Ncat option) option. works with TCP (the default) and SCTPSCTPin Ncat ( (Ncat option) option). Here is the syntax for connecting to an HTTPS server: ncat -C --ssl server 443 Sometimes an SSL server will require a client certificate for authentication. When this is the case, use the (Ncat option) and (Ncat option) options to give the locations of PEM-encoded files containing the certificate and private key, respectively. The certificate and key may be in the same file. certificate verification trustcertificate verification By default the client will not do any server certificate verification, so it will not be detected if the server has the wrong certificate or no certificate at all. Use the option to require verification of the certificate and matching of the domain name. (Ncat option) ncat -C --ssl-verify server 443 Verification is done using the ca-bundle.crtca-bundle.crt certificate bundle shipped with Ncat, plus whatever trusted certificates the operating system may provide. If you want to verify a connection to a server whose certificate isn't signed by one of the default certification authorities, use the to name a file containing certificates you trust. The file must be in PEM format. (Ncat option) ncat -C --ssl-verify --ssl-trustfile custom-certs.pem server 443 Verification should be done whenever it is feasible. Even with encryption, an unverified connection is vulnerable to a man-in-the-middle attack. Ncat does not do certificate revocationcertificate revocationCRLcertificate revocation checking. SSL ciphersin Ncat SSL connections depend on the client and server agreeing on a common ciphersuite: a combination of key exchange, symmetric cipher, and message integrity mechanism. The choice of which ciphersuites to offer (as a client) or accept (as a server) is a matter of choice between the greatest compatibility and the greatest security. The default set, expressed as an OpenSSL cipherlist, is ALL:!aNULL:!eNULL:!LOW:!EXP:!RC4:!MD5:@STRENGTH, a reasonable balance between the two ends of the spectrum. To set a different priority or initial choice, use the option. (Ncat option) ncat --ssl-ciphers HIGH:!aNULL:!eNULL server 443 (Ncat option) SSLin Ncat certificateautomatic generation of certificate keys, cryptographic Ncat can act as an SSL server as well. The server must provide a certificate that clients can verify if they choose. If you start an SSL server without using the and options, Ncat will automatically generate a certificate and 2,048-bit RSA key. The certificate will of course not be trusted by any application doing certificate verification. In verbose mode, the key's fingerprint will be printed so you can do manual verification if desired. shows sample output. Automatic certificate generation (Ncat option)example of $ ncat -v --listen --ssl Ncat ( https://nmap.org/ncat ) Generating a temporary 2048-bit RSA key. Use --ssl-key and --ssl-cert to use a permanent one. SHA-1 fingerprint: F0:13:BF:FB:2D:AA:76:88:22:60:3E:17:93:29:3E:0E:6B:92:C0:2F Using an existing certificate and key is recommended whenever possible because it allows for robust server authentication. Use the and options to pass in PEM-encoded files. For testing purposes you can generate a self-signed certificate and private key. If you have OpenSSLOpenSSL installed, use this command: openssl req -new -x509 -keyout test-key.pem -out test-cert.pem. For purposes of certificate verification, the commonNamecommonName in the certificate should match the fully qualified domain namefully qualified domain name of the host that will run the server. After generating the files, start the server: ncat --listen --ssl --ssl-cert test-cert.pem --ssl-key test-key.pem. To make a verified client connection, copy the test-cert.pem file somewhere where the client can access it, then run ncat --ssl-verify --ssl-trustfile test-cert.pem. Command Execution Ncat can execute an external command after establishing a connection. The command's standard input and outputstandard inputstandard output streams are redirected to use Ncat's network connection. Anything received over the connection is given to the command's stdin, and anything the command writes to stdout is sent back out over the connection. This feature makes almost any terminal application accessible over a network (with some caveats). There are three ways of running a command: (Ncat option) runs a command without shell interpretation. (Ncat option) runs a command by passing a string to a system shell. (Ncat option) runs a Lua program using Ncat's built-in Lua interpreter.Luain Ncat The (Ncat option) option (alias ) (Ncat option) takes the full pathname of a command to execute, along with its arguments. The command is executed directly; Ncat does not interpret the given string beyond splitting the command and its arguments. shows an example of usage. Running a command with <option>--exec</option> ncat -l --exec "/bin/echo Hello." The (Ncat option) option () (Ncat option) works the same as , except that it executes the command by passing it to /bin/sh -c on Unix or cmd.exe /C on Windows. You don't have to use the full pathname of the command if the command is in the PATH.PATH Additionally you have access to shell facilities such as pipelines and environment variable expansion. shows a command run with . This server, when connected to, sends back the name of its working directory. Running a command with <option>--sh-exec</option> ncat -l --sh-exec "echo `pwd`" The (Ncat option) option takes the filename of a Lua program to run. Ncat runs the program using its built-in interpreter and redirects its input and output streams. Anything the program writes to standard output (for example with print or io.write) is written to the connection, and any reads from standard input come from the connection. A nice thing about running programs written in Lua is that the same interpreter is used on all platforms, in comparison with shells that operate differently. That means that the default Ncat build is all you need to run a simple network service. To write a program, the standard text editor (even a Windows "notepad") is enough; to learn how to create programs in Lua, have a look at "Programming in Lua" book available for free at Lua.org website. shows how to run a program stored in a file called hello-luaexec.lua. You can find this script - and some other ones - in Nmap's source code package, in ncat/scripts directory - the latest versions of the scripts can be found in the Nmap project public SVN repository. Here are the contents of the hello-luaexec.lua file, if you would prefer to create the file yourself: --This is a --lua-exec "Hello world" example. In order to send to a client, --all you need to do is output it to the standard output. print("Hello, world!") Running a command with <option>--lua-exec</option> ncat -l --lua-exec hello-luaexec.lua Now, anyone that connects to our server will see the "Hello, world" message. For a script with a bit more capabilities, have a look at conditional.lua. It shows how to create a simple menu, receive some data from the user repeatedly and react according to her decisions. You might want to start off your experiments with Lua by making changes to this script. Also see for information on how to run a simple HTTP server in Lua. The exec options can be used in connect mode and listen mode. In listen mode, Ncat accepts one connection, runs the command, and then quits, just like listen mode without exec. But when listen mode is combined with ,with Ncat will accept multiple connections, forking off a new handler for each. The server will keep running until you press ctrlC or otherwise terminate it externally. In this way Ncat can work much like inetd.inetd Many examples of the use of and in listen mode are found in . Running an inetd-like server ncat -l --keep-open --exec "/bin/echo Hello." Whatever the exec mode, Ncat sets environment variables in the spawned program's environment that describe the connection. NCAT_REMOTE_ADDRNCAT_REMOTE_ADDR> environment variable NCAT_REMOTE_PORTNCAT_REMOTE_PORT> environment variable The IP address and port number of the remote host. In connect mode, it's the target's address; in listen mode, it's the client's address. NCAT_LOCAL_ADDRNCAT_LOCAL_ADDR> environment variable NCAT_LOCAL_PORTNCAT_LOCAL_PORT> environment variable The IP address and port number of the local end of the connection. NCAT_PROTONCAT_PROTO> environment variable The protocol in use: one of TCP, UDP, and SCTP. shows the output of a Lua program that reads these variables. You can see these environment variables in action by running this Exec environment variables The contents of the program env.lua: function env(v) print(string.format("%s %q", v, os.getenv(v))) end env("NCAT_REMOTE_ADDR") env("NCAT_REMOTE_PORT") env("NCAT_LOCAL_ADDR") env("NCAT_LOCAL_PORT") env("NCAT_PROTO") The output of running the program: $ ncat -l --lua-exec env.lua & $ ncat localhost NCAT_REMOTE_ADDR "127.0.0.1" NCAT_REMOTE_PORT "60179" NCAT_LOCAL_ADDR "127.0.0.1" NCAT_LOCAL_PORT "31337" NCAT_PROTO "TCP" --lua-exec portability When writing your own --lua-exec script, keep in mind that while Lua is very portable, there is a caveat related to running your Lua scripts written on Windows to Unix systems. For technical reasons, --lua-exec on Windows reloads the script every time it is run. Do not rely on this behavior on other systems though - on POSIX-compatible systems, the script is only loaded once and any modifications to its code will not be visible until you restart Ncat. Any program that takes input and produces output can be executed by Ncat, but not all programs are suited to this kind of interaction. Many programs buffer their input and output,bufferingeffect on Ncat of so if they receive some bytes, they many not process those bytes and write output until their input buffer is full, or the output may be deferred until the output buffer is full. If another program sends a few bytes and then waits for a response, it may hang indefinitely. Buffers are flushed when input or output ends, so even those programs that don't work interactively will work when run on an entire file at a time. Be careful when using the various exec options. It can be dangerous to connect a new application to a network, especially one that wasn't written with potentially hostile input in mind. Any local vulnerabilities in an application may become remote vulnerabilities when you execute it through Ncat. Output Options verbosityof Ncat Like any proper pipeline utility, Ncat reads from standard inputstandard input and writes to standard outputstandard output so you can redirect I/O to or from any program or file. The only exception is when Ncat is run with the or options, in which case it communicates with the subprocess instead. Nothing in the streams is added, removed, or altered, unless you specifically ask for it with an option such as (Ncat option) (CRLF processing) or (Ncat option) (Telnet negotiation). If Ncat prints any diagnostic messages, they are sent to standard errorstandard error so as not to interfere with the data stream. By default Ncat does not print any such messages, but you can enable them with the (Ncat option) () (Ncat option) option. Use more than once for even more output. hex dump transcript log fileof Ncat Use the (Ncat option) option or its alias (Ncat option) to record a transcript of everything sent and received to a file: ncat -C --output smtp-debug.log mail.example.com 25 The log contains everything sent and received without differentiation. Sometimes a hex dump is more useful than a plain text log; for that use (Ncat option) or . (Ncat option) Let's see what happens if we accidentally speak SMTP to an SSH server: $ ncat -C --hex-dump ssh-hex.log scanme.nmap.org 22 SSH-2.0-OpenSSH_4.3 HELO example.com Protocol mismatch. The log file for this session: [0000] 53 53 48 2D 32 2E 30 2D 4F 70 65 6E 53 53 48 5F SSH-2.0- OpenSSH_ [0010] 34 2E 33 0A 4.3. [0000] 48 45 4C 4F 20 65 78 61 6D 70 6C 65 2E 63 6F 6D HELO exa mple.com [0010] 0D 0A .. [0000] 50 72 6F 74 6F 63 6F 6C 20 6D 69 73 6D 61 74 63 Protocol mismatc [0010] 68 2E 0A h.. Each transmission is dumped separately. There is a break and the counter at the left starts over each time there is a new send. access control Access Control A listening Ncat may control which hosts connect to it with the (Ncat option) and (Ncat option) options. Each of these takes a comma-separated list of host specifications. The syntax is almost identical to that recognized by Nmap for targets (see the section called Target Specification). This includes IPv4 and IPv6 addresses, hostnames, IPv4 octet ranges, and CIDR netmasks. In Ncat (unlike Nmap), CIDR netmasks are supported for IPv6 addresses. With , any hosts matching one of the listed specifiers are allowed and all others are denied. With , those hosts matching the list are denied and all others are accepted. If a host matches both the and lists, it is denied. Use (Ncat option) and (Ncat option) to allow or deny a list of host/network specifiers stored in a file. Each line of the file contains a specification in one of the forms listed above. Any file acceptable to Nmap's and options is suitable for and . The following example commands demonstrate various kinds of access control. Allow one host, deny all others ncat -l --allow 192.168.0.125 ncat -l --allow 2001:db8::7d ncat -l --allow trusted.example.com Deny one host, allow all others ncat -l --deny 192.168.0.200 ncat -l --deny 2001:db8::c8 Allow hosts on a local network, deny all others ncat -l --allow 192.168.0.0/24 ncat -l --allow 192.168.0.0-255 ncat -l --allow 2001:db8::/32 Allow or deny hosts from a file ncat -l --allowfile trusted-hosts.txt ncat -l --denyfile external-hosts.txt Be aware that host-based access control is susceptible to spoofing attacks and various other possible failures. These mechanisms should not be relied on for complete security. Another kind of access control is simply limiting the maximum number of connections a listening Ncat will accept. Use the (Ncat option) option or its alias to do that. The default maximum number of connections is 100, or 60 on Windows. ncat -l --max-conns 5 Proxying HTTP proxyproxy proxyNcat as Ncat can route its connections through a SOCKS 4SOCKS proxy, SOCKS 5 or HTTPHTTP proxy proxy. A basic connection looks like (Ncat option) (Ncat option) ncat --proxy proxyhost:proxyport --proxy-type httpsocks4socks5 host port may be omitted; it defaults to http. If proxyport is omitted, it defaults to the well-known port for the chosen proxy type: 1080 for SOCKS and 3128 for HTTP. An exception to this rule is when the proxy host is given by a IPv6 address; in this case the port is required because otherwise it would be ambiguous whether the digits after the last colon are the port number or part of the address. If the proxy server requires authentication, use the (Ncat option) option. Use --proxy-auth username:password for HTTP and SOCKS5 proxies and --proxy-auth username for SOCKS4 proxies. Ncat can act as a proxy server itself in listen mode. The only proxy type supported in this case is http. ncat -l 3128 --proxy-type http ncat -l 3128 --proxy-type http --proxy-auth user:pass In listen mode the proxy port number is not automatically set and will be the default of 31337 unless specified. The proxy supports the GET,GET HTTP method HEAD,HEAD HTTP method and POSTPOST HTTP method methods used in web browsing, as well as the CONNECTCONNECT HTTP method method that allows tunneling arbitrary TCP connections. (When Ncat connects as a client, it uses CONNECT.) Use to make the server require authentication with a specific username and password. For HTTP, both the BasicBasic authentication (HTTP) and DigestDigest authentication (HTTP) authentication schemes are supported, as both a client and a server. Digest is more secure, so the Ncat client will use that in preference to Basic when it is available. The server offers both schemes to its clients. See RFC 2617,RFC 2617 section 4 for security considerations of HTTP authentication. Basic sends credentials in the clear and Digest does not. Ncat's implementation of Digest authentication allows replay attacks for up to 10 seconds (replay and other attacks are always possible with Basic). open proxy Ncat's HTTP proxy is designed to stay out of your way and help you make temporary network connections. It shouldn't be used as an everyday proxy exposed to the Internet. You can limit who connects using , , and , but these are not strong forms of authentication. An unauthenticated proxy is dangerous because it may enable others to perform attacks or help them evade detection. The CONNECTCONNECT HTTP methoddanger of capability is especially dangerous because it enables any kind of traffic, not just HTTP. Other Options This section contains descriptions of all options that haven't been discussed so far. The (Ncat option) option (and its short form ) (Ncat option) instructs Ncat never to resolve names into addresses. All hosts must appear as IPv4 or IPv6 addresses. Ncat can be used as a Telnet client or server with the (Ncat option) option (). (Ncat option) This simply causes Ncat to respond negatively to any questions asked by the other host in the binary Telnet protocol, removing such negotiations from the stream seen by the user. The primary use of this option is to allow running canned Telnet scripts. The (Ncat option) and (Ncat option) options do what their names imply, turning Ncat into a one-way communications channel instead of its default two-way channel. A usage example is gathering data from a server without the possibility of accidentally sending something typed at the keyboard. in both connect and listen modes causes Ncat to quit when its input runs out. Normally it will not quit until the network connection is closed because the remote side may still send something, but in the case of there's no reason to receive anything more. Source Options In connect mode, you may set the source address and port used for the connection with the (Ncat option) () (Ncat option) and (Ncat option) (). (Ncat option) The option only works for locally configured addresses; it doesn't work like Nmap's option. The value of is that sometimes firewalls will allow traffic that comes from certain source ports (such as 20 or 53). source routingin Ncat The (Ncat option) option allows hops selection for IPv4 loose source routing. List the hops in order by giving multiple times or by separating the hops with commas. By default the source routing pointer is 4 in the packets sent, indicating the first hop in the list. You may set the pointer to another value with the (Ncat option) option. The pointer value must be a multiple of 4 between 4 and 28, but some operating systems only support 4. Timing Ncat offers various options to control timing. Each of them take an argument that is assumed to be in seconds, unless followed by ms for milliseconds, s for seconds, m for minutes, or h for hours. 30s means 30 seconds. This format should already be familiar to Nmap users. The (Ncat option) option and its short form (Ncat option) make Ncat wait the given amount of time between each discrete read or write operation. For example, --delay 500ms enforces a delay of half a second. The (Ncat option) option and it synonym (Ncat option) allow setting a timeout for reads and writes in connect mode. If the client fails to read or write for the given time period, the connection is dropped. These options do not work in listen mode. The (or for short) (Ncat option) option sets how long Ncat will wait for a connection to be established in connect mode. The default is 10 seconds. File Transfer file transfer with Ncat There is no shortage of ways to transfer a file over a network. Most file transfers are ably handled by email, network file systems, HTTP, SFTP, or other protocols. What do you do, though, when that file is too big to email, the transfer is between two machines not connected to the Internet, or you just need to do one quick file transfer without having to set up and tear down a file server? In these and other situations Ncat can be the right tool for the job. Some tricky file transfer scenarios can really make you appreciate the flexibility of a raw network pipe. As you know, Ncat by default sends all its traffic without encryption, so it is possible for someone to intercept files in transit. See for one method of encrypting traffic. By default, Ncat doesn't close its connection until it is closed by the remote end, even after it has exhausted its input. That is because (as far as Ncat knows) the remote server may still have data to send back. The (Ncat option) option, when applicable, changes this behavior to close the connection and quit at the end of input. This is normally what you want when doing a one-way file transfer. A basic file transfer is very simple: Start Ncat in listen mode on one end, start Ncat in connect mode on the other end, and pipe the file over the connection. There are two ways to do this that differ only in which end listens, the sender or the receiver. Sometimes you can't create a listening socket on one end of the transfer because of a lack or permissions, NAT, or filtering. As long as you can listen on at least one end, though, you can use this technique. These examples show how to transfer inputfile on host1 to outputfile on host2. Here no port number was specified so Ncat will use its default portdefault port of Ncat of 31337. To use a different port just list it on the command line. Transfer a file, receiver listens (Ncat option)example of (Ncat option) host2$ ncat -l > outputfile host1$ ncat --send-only host2 < inputfile Transfer a file, sender listens host1$ ncat -l --send-only < inputfile host2$ ncat host1 > outputfile Note the order of the commands. The listener must be started first, regardless of the direction of transfer, or else the client will not have anything to connect to. The above technique works fine for sending a single file. One way to send multiple files is to bundle them up with tar or zip and send the archive file. But there's an even easier way. Just pipe the output of tar directly into Ncat on the sending side, and pipe Ncat's output into tar on the receiving side. This is especially useful when the sending computer doesn't have enough free disk space to hold the archive file. Here's how to transfer files using the receiver listens method, though of course the sender listens method works just as well. Transfer a bundle of files host2$ ncat -l | tar xzv host1$ tar czv files | ncat --send-only host2 Not only tar files but any stream of bytes can be transferred in this way. Here is an example of transferring an entire disk image from host1 to host2. Naturally, the disk should be unmounted or mounted read-only. Transfer a disk image host2$ ncat -l > host1-hda.image host1$ ncat --send-only host2 < /dev/hda Disk images are typically large files that take a long time to transfer. You can compress the image on the fly while sending and decompress it on the other end. Whether this makes an improvement depends on the speed of the network and the compression program. Transfer a disk image with compression host2$ ncat -l | bzip2 -d > host1-hda.image host1$ cat /dev/hda | bzip2 | ncat --send-only host2 The basic file transmission technique described at the beginning of this section fails if neither participating host is capable of listening, or the two hosts can't communicate directly. This situation has become common with the prevalence of network address translation. A way to work around it is to use a third host as an intermediary. The intermediate host listens in connection brokering mode and the other two hosts connect to it. Recall from that in connection brokering mode any input received on one socket is copied and sent out to all other sockets. With just two hosts connected this is especially simple: anything coming from one host gets forwarded to the other. This example shows host1 sending inputfile to outputfile on host2, using host3 as an intermediary. Transfer a file through an intermediary (Ncat option)example of host3$ ncat -l --broker host2$ ncat host3 > outputfile host1$ ncat --send-only host3 < inputfile Note that it's important for host2 (the receiving host) to connect to the broker before host1 (the sending host) does. The broker does not buffer received data to send to hosts that connect later. After the file is transferred, it is necessary to forcibly disconnect the Ncat on host2 with ctrlC. The broker never disconnects any of its clients. Chatting In its most basic form, Ncat simply moves bits from one place to another. This is all that is needed to set up a simple chat system. By default, Ncat reads from standard inputstandard input and writes to standard output,standard output meaning that it will send whatever is typed at the keyboard and will show on the screen whatever is received. Two-user chat host1$ ncat -l host2$ ncat host1 With this setup, two users can communicate with each other. Whatever one types will appear on the screen of the other. Be aware that standard input is probably line-buffered so it may be necessary to press enter before a line is sent. Which side listens and which side connects is not important in this situation, except that the listener must start ncat first. The above technique is limited to one-on-one conversations. If more users connect to the server, each one will effectively create a new chat channel with the server; none of the connecting users will hear each other. Multi-user chatting is easily supported using connection brokering with the option (see ). In broker mode, anything received on one connection is sent out to all other connections, so everyone can talk with everyone else. chat mode (Ncat) When many users are chatting through a connection broker, it can be hard to know who is saying what. For these cases Ncat provides a simple hack to tell users apart. When the (Ncat option) option is given, connection brokering is automatically enabled. Each message received is prefixed with an ID before being relayed to all other clients. The ID is unique for each client connection, and therefore functions something like a username. Also, in chat mode any control characters are escaped so they won't mess up your terminal. The server is started with server$ ncat -l --chat Once the server is started, this is how the chat appears to one of the connected users. The lines that begin with <usern> are from other connected users. The line beginning with <user0> was sent by the listening broker. client$ ncat server <user6> Is anyone there? I'm here. <user5> Me too. <user0> Go away, all of you. The user IDs generated by Ncat are based on the file descriptor for each connection, and must be considered arbitrary. There is no way to choose a particular ID or make one persist across sessions. Nevertheless, can come in handy for those quick multi-user conversations. Neat Tricks Send Mail It is great fun to interact with text-based network protocols with nothing more than Ncat and a keyboard. Here's a short example showing how to send email by talking to an SMTP server. SMTP is described in RFC 5321,RFC 5321 but you don't need to know much about the protocol to send a simple message. The service's assigned port number is 25, and we use because it requires CRLF line endings. contains a transcript of a session. Ncat as mail client (Ncat option)example of $ ncat -C mail.example.com 25 220 mail.example.com ESMTP HELO client.example.com 250 mail.example.com Hello client.example.com MAIL FROM:a@example.com 250 OK RCPT TO:b@example.com 250 Accepted DATA 354 Enter message, ending with "." on a line by itself From: a@example.com To: b@example.com Subject: Greetings from Ncat Hello. This short message is being sent by Ncat. . 250 OK QUIT 221 mail.example.com closing connection To make this example work for you, change mail.example.com to your SMTP server and client.example.com to your domain name. Naturally you'll want to change the email addresses and message too. It will likely only work when using your normal mail server with your real email address, or when using the recipient's mail server (look up the MX record for the domain name in their email address). Obviously this technique can be used for more than just sending mail. Ncat is a great interactive debugging tool for any text-based protocol. Such debugging is sometimes done with the telnet command, because it provides something like a raw text stream. Ncat offers a few advantages over telnet, though. Ncat doesn't print anything except what is sent by the remote host. Telnet isn't suitable for arbitrary binary data because it reserves some bytes as control characters. The telnet command quits when its input runs out, so you may not see what the other end sends. And finally, telnet doesn't do UDP. Turn Ncat into a simple web server Continuing the example from , we can create a simple HTTP server that serves the index.html file using the following command: ncat -lk -p 8080 --sh-exec "echo -e 'HTTP/1.1 200 OK\r\n'; cat index.html" Or, if you're a Windows user: ncat -lk -p 8080 --sh-exec "echo HTTP/1.1 200 OK& echo(&type index.html" This will start the HTTP server, serving the index.html file from your current working directory. To try it out, visit http://localhost:8080/ using your web browser. You can also skip :8080 from the URL if you specified -p 80 instead of -p 8080 in the command above. Note that it will send this file regardless of the entered URL - to change the file being sent, you need to change the Ncat command or use the httpd.lua script (see below). Since Ncat v6.40, it is possible to use --lua-exec feature to run a Lua script turning Ncat into a web server. In order to do that, need the httpd.lua script which is bundled with the Ncat source in the ncat/scripts/ directory. With the httpd.lua script in your working directory, run Ncat in listening mode: ncat --lua-exec httpd.lua --listen 8080 --keep-open This will spawn a HTTP server on TCP port 8080. Unlike the previous example though, the httpd.lua script works without modification on all POSIX-compatible systems and also on Windows. Moreover, you can specify in the URL any other file from the current directory or one of its subdirectories and it will be sent to the user, unlike the --sh-exec example. Ncat HTTP server on production The Ncat HTTP server examples shown above are very simple and may be not as powerful as complete HTTP servers, such as Apache HTTPD. It is not advised to use them in production environments (such as public website hosting). It might be useful, though, if you need to quickly spawn a HTTP server to copy some files or for educational purposes. Chain Ncats Together Ncat is designed to work within a pipeline, so naturally the output of one instance of Ncat can be fed into the input of another. Here is one way to send a log file from host1 to host3 by way of host2: host3$ ncat -l > log.txt host2$ ncat -l | ncat host3 host1$ ncat --send-only host2 < log.txt A possible problem with this technique is that it is one-way: host1 can send to host3 but there is no way for host3 to send anything back to host1. In this case it doesn't matter, but it can be done with a small change. Consider this: host3$ ncat -l > log.txt host2$ ncat -l --sh-exec "ncat host3" host1$ ncat --send-only host2 < log.txt The Ncat listening on host2, upon receiving a connection, creates a new Ncat to speak to host3 and connects the inputs and outputs of the programs running on host1 and host3 together. The same trick can be used on the local host too. This example forwards the local port 8080 to the web server on example.org: ncat -l localhost 8080 --sh-exec "ncat example.org 80" Unwrap SSL Suppose you need to connect to an IMAPIMAP server that requires SSL, but your mail reader doesn't support SSL. Ncat can act as the encrypted bridge to connect the client and server. You will connect the mail client to a local port and Ncat will forward the traffic, encrypted, to the server. Here's how to connect IMAP (port 143) on the local host to IMAP over SSL (port 993)IMAPS on imap.example.com. ncat -l localhost 143 --sh-exec "ncat --ssl imap.example.com 993" Once this is in place, instruct the mail client to connect to the IMAP server on localhost. This trick works for protocols that pass traffic strictly between two hosts. It doesn't work well for HTTPHTTP because HTTP is usually aware of hostnames and often involves multiple hosts. Use SSH Through an Ncat Tunnel With Ncat and OpenSSHOpenSSH you can SSH to a host behind a NATnetwork address translation router without having to forward ports on the router. The router must have Ncat installed. Here is how to SSH to host through router: ssh -o ProxyCommand="ssh -q router ncat %h %p" host The ProxyCommand option of ssh tells how to open the SSH connection to host. It does this by opening another SSH session to router and connecting it to host with Ncat. If your SSH server administrator did not disable tunneling (which is enabled in most default configurations), you can use the proxy server built into SSH. Use the following command to spawn a proxy server on TCP port 8080 of your local machine that tunnels the traffic through the SSH connection: ssh router -D 8080 Now you can make connections inside the network using Ncat's proxy client capabilities. For example, to connect to host with IP address 192.168.1.123 that is behind the router, you can use the following command if you spawned the tunnel: ncat --proxy localhost:8080 --proxy-type socks4 192.168.1.123 Watch What Nmap's Version Detection is Doing Ncat can show you at a low level what's going on when Nmap version-scans a service. We'll make a service that only listens and instruct Nmap to use every version probe in the book. Set up Ncat to listen and record a hex dump log. The (Ncat option) option will make Ncat keep listening and accepting more connections after the first one is finished, contrary to the normal listen mode behavior of quitting when the first connection ends. Some version probes are binary so redirect standard output to /dev/null/dev/null to avoid writing them to the screen. (Ncat option)example of (Ncat option)example of ncat -l --keep-open 5200 --hex-dump vscan.log > /dev/null Now scan the open port you made: example of nmap -d -sV --version-all localhost -p 5200 An except of the hex dump is shown in . Hex dump of Nmap version detection At the beginning, Nmap would have sent its NULL probeNULL probe, which isn't shown in the log file because the NULL probe doesn't send anything. At the top of the log is the GenericLines probe (0D 0A 0D 0A, or \r\n\r\n). After that is our old friend the HTTP GETGET HTTP method request. Then come all the other probes in the nmap-service-probesnmap-service-probes file. In this excerpt are shown probes designed to get a response from RPC, DNS, and SMTP. Emulating Diagnostic Services There are a number of simple Internet protocols intended for testing and measurement purposes. Because they deal with simple, fundamental network operations they are a good match for Ncat's capabilities. This section shows how to to emulate services of increasing complexity: discard, echo, daytime, qotd, and chargen. These particular commands assume you are on a UNIX system such as Linux or Mac OS X, and using a /bin/sh compatible shell, such as Bash. The discard service,discard service defined in RFC 863,RFC 863 simply ignores anything sent to it. It runs on TCP or UDP port 9. By default, Ncat doesn't send any information unless instructed to, so nothing special is needed to emulate discard. Send Ncat's output to /dev/null/dev/null to avoid filling the screen with characters received, or just let it write to the terminal if you're curious to see what's there. Use the (Ncat) option to prohibit sending any characters that might be entered at the terminal. TCP discard server (Ncat option)example of (Ncat option)example of ncat -l --keep-open 9 --recv-only > /dev/null UDP discard server ncat --udp -l --keep-open 9 --recv-only > /dev/null Ncat in UDP mode uses all the same options as TCP. The caveat here is that connections can't be closed, only timed out, so you will eventually run out of sockets if you do not use a timeout. Currently, none of the timeout options do the appropriate thing in this instance. The echo serviceecho service is defined in RFC 862.RFC 862 It runs on TCP or UDP port 7. One step more advanced than discard, it sends back any data received until the connection is closed. How do you instruct Ncat to return what it receives? One easy way is to run everything through /bin/cat. TCP echo server (Ncat option)example of ncat -l 7 --keep-open --exec "/bin/cat" UDP echo server (Ncat option)example of ncat -l 7 --keep-open --udp --exec "/bin/cat" The daytime service,daytime service defined in RFC 867,RFC 867 sends a human-readable date and time string over TCP or UDP port 13. It ignores any input. The format of the date and time string is left unspecified, so we are free to use the output of /bin/date. Because we are not interested in anything sent by the client we use the (Ncat option) option. TCP daytime server (Ncat option)example of (Ncat option)example of ncat -l 13 --keep-open --send-only --exec "/bin/date" UDP daytime server (Ncat option)example of ncat -l 13 --keep-open --udp --send-only --exec "/bin/date" Nmap comes with a daytime.nsedaytime.nse script script that works with the daytime service. Here is its output running against Ncat daytime servers on TCP and UDP. <filename>daytime.nse</filename> against an Ncat daytime server example of # nmap -sSU -p 13 --script=daytime localhost Starting Nmap ( https://nmap.org ) Nmap scan report for localhost (127.0.0.1) PORT STATE SERVICE 13/tcp open daytime |_daytime: Mon Jan 19 17:43:18 MST 2009 13/udp open daytime |_daytime: Mon Jan 19 17:43:18 MST 2009 Nmap done: 1 IP address (1 host up) scanned in 0.31 seconds The qotdqotd service (quote of the day) service is defined in RFC 865.RFC 865 When a connection is made to TCP or UDP port 17, it sends back a short message, ignoring any input. Ncat can do this by invoking a program that generates messages. A traditional choice is /usr/games/fortune, though there are many possibilities. /usr/bin/uptime, for example, could be useful. TCP qotd server (Ncat option)example of ncat -l 17 --keep-open --send-only --exec "/usr/games/fortune" UDP qotd server (Ncat option)example of do ncat -l 17 --keep-open --udp --send-only --exec "/usr/games/fortune" In this example it's instructive to consider the difference between ncat -l 17 --exec "/usr/games/fortune" and /usr/games/fortune | ncat -l 17. Think about why the second command stops working after the first connection. The chargen servicechargen service from RFC 864RFC 864 rounds out our tour of diagnostic services. It runs on TCP and UDP port 19. With TCP, chargen ignores any input and sends a never-ending stream of data. Never-ending, that is, until the connection is closed by the user, who the RFC suggests may have had enough. There are many ways of generating the characters; reading from /dev/zero/dev/zero and running yes come to mind. TCP chargen server yes "chargenchargenchargen" | ncat -l --keep-open 19 --send-only Notice that in this case the program pipes its output into ncat rather than being invoked with . For chargen either method would work, because the output of yes never changes. Using a pipe requires only one process other than ncat, but all users connected simultaneously will see the same output stream in synchrony. If the contents must be independent for each stream, then use the method, with the understanding that a new process will be started for each connection. The UDP chargen protocol is a little different. When a datagram is received, it sends back one datagram containing a random number of characters. Implementing this is starting to get away from Ncat, but one way it could be done with the Bash shellBash shell is this: UDP chargen server (Ncat option)example of (Ncat option)example of (Ncat option) ncat -l 19 --keep-open --udp --send-only --sh-exec \ "yes chargenchargenchargen | dd count=1 bs=$(($RANDOM % 512)) 2> /dev/null" Notice the use of (Ncat option) rather than (Ncat option) to allow the use of the shell's environment variables and arithmetic evaluation. Standard errorstandard errorin Ncat subprocesses is redirected to /dev/null/dev/null to avoid including dd's summary lines (1+0 records out), which would otherwise be included by Ncat. This completes the tour of simple diagnostic services. These have been easy to implement with Ncat because (with the exception of UDP chargen) they all map directly onto a familiar command-line program. As services become more complex it gets harder to do everything in the shell. For complicated services it's better to write a separate program and have Ncat exec it directly.