Thursday, May 27, 2010

How Linux deals with Worm and Trojan Attacks

Understanding Linux Operations for Worms and Trojan type Attacks.


11. Exploits

The diversity of today's networks exposes your system to a wide variety of possible security-related incidents. In order to protect your systems, you must be aware of these exploits in order to protect yourself from them. While previous sections explained the types of people to protect against, and the reasons they attack, this section attempts to explain the types of exploits that are typically performed to break into a computer system.

There are several exploits that won't be mentioned here, such as Macro Code Attacks and Virus Infections, of which Linux and Unix itself in general is not susceptible. However, any Windows-based systems that connect to it will be suseptible, via shared filesystems, electronic mail, etc.

There are now several programs available to check your system for the most common exploits. The rootshell site, http://www.rootshell.com has several of these programs, and there is also the following available ftp://ftp.fu-berlin.de/unix/security/chkexploit/

11.1 Worm Attacks

Worms are problems which replicate themselves, but unlink viruses they do not modify other programs and are not triggered by user actions. Worms are self-contained programs that attack systems or other programs without changing them in any way, and that typically use networks to accomplish this. The Internet Worm, which reportedly gained access to more than 6,000 Unix systems, flooded the Internet with so many access requests that it became unusable. These are no where near as common as they once were.

11.2 Trojan Horse Programs

A trojan horse is a program that is an unauthorized, self-contained program that is not self-replicating. It is often hidden or given a misleading name to deter suspicion.

A Trojan Horse is named after the fabled ploy in Homer's great literary work. The idea is that you put up a program or binary that sounds great, and get other people to download it and run it as root. Then, you can compromise their system while they are not paying attention. While they think the binary they just pulled down does one thing (and it might very well), it also compromises their security.

You should take care of what programs you install on your machine. Red Hat provides MD5 checksums, and PGP signs RPM files so you can verify you are installing the real thing. Other distributions have similar methods. You should never run any binary you don't have the source for or a well known binary as root! Few attackers are willing to release source code to public scrutiny.

Although it can be complex, make sure you are getting the source for some program from it's real distribution site. If the program is going to run as root make sure either you or someone you trust has looked over the source and verified it.

11.3 Cracking Attacks

Cracking attacks are attacks perpetrated by network intruders, or crackers (formally known as hackers). These attacks take the form of network intrusions, which are break-ins into remote systems, or the use of the services they provide, without authorization. The number of cracker attacks is proliferating more rapidly than any other type of incident, in large part because the Internet provides broad connectivity without intrinsic security mechanisms.

Information security professionals have long accepted the premise that more incidents are caused by insiders (e.g., company employees and contractors) than by outsiders. Many feel this trend is now reversing, and news of organizations' incurring major financial losses as the result of network intrusions is becoming commonplace.

Obviously, neither type of exploit should be taken lightly.

11.4 Direct Physical Access

Users often log on to workstations and then leave them unattended for long periods of time. This allows unauthorized individuals physical access to the workstations and to the organization's systems. An attacker can enter the office and use the workstation to attack numerous systems at a commercial site.

Attacks involving direct physical access can be extremely costly, because the attacker is often an insider who knows exactly where valuable data and applications reside on the system.

See the section on physical security for more information on how to protect your system.

11.5 Spoofing

Spoofing is a complex technical attack that is made up of several components. It is a security exploit that works by tricking computers in a trust-relationship that you are someone that you really aren't. Spoofing of network connections involves forging an IP source address to trick the destination into thinking you are someone you really aren't. Spoofing of network services involves using poorly configured (or misconfigured) applications, typically SMTP, to trick the client, server, or receipient into thinking you are someone you are not.

Using the most recent implementations of the available service can help to protect against this ``masquerading''. Preventing internal IP addresses from seemingly entering your firewall from the outside is something that should be a mandatory addition to your rulebase. There is some information on preventing DNS spoofing available at http://www.sunworld.com/swol-11-1997/swol-11-bind.html

A general guide to securing DNS is available at http://www.psionic.com/papers/dns-linux.html

A great reference of spoofing information is available at http://www.unitedcouncil.org/text.html including the excellent article published in Volume Seven, Issue Forty-Eight of Phrack, available here http://www.unitedcouncil.org/spoof/IPSpoofing.txt This paper will help you understand the low-level TCP details.

11.6 Denial of Service Attacks

A Denial of Service (DoS) attack is one where the attacker prevents legimitate users from accessing a service. Denial of service attacks either try to make some resource too busy to answer legitimate service requests, or to deny legitimate users access to a machine.

Also of significant concern is a denial of service attack that is really intended to keep the victim busy while really the intruder is impersonating the host, preventing it from replying. These are typically referred to as ``man in the middle'' attacks.

Denial of service attacks have increased greatly in recent years. Some of the more popular and recent ones are listed below. Note that new ones show up all the time, so this is just a few examples.

  • SYN Flooding - SYN flooding is a network denial of service attack. It takes advantage of a "loophole" in the way TCP connections are created. The newer Linux kernels (2.0.30 and up) have several configurable options to prevent SYN flood attacks from denying people access to your machine or services. See the section on kernel security for proper kernel protection options.

  • Pentium "F00F" Bug - It was discovered in the summer of 1997 that a series of assembly codes send to a genuine Intel Pentium processor would reboot the machine. This affects every machine with a Pentium processor (not clones, not Pentium Pro or PII), no matter what operating system it's running. Linux kernel 2.0.32 and up contain a work around for this bug, preventing it from locking your machine. Kernel 2.0.33 has an improved version of the kernel fix, and is suggested over 2.0.32. If you are running on a Pentium, you should upgrade now!

  • Ping Flooding - Ping flooding is a simple brute force denial of service attack. The attacker sends a "flood" of ICMP packets to your machine. If they are doing this from a host with better bandwidth than yours, your machine will be unable to send anything on the network. A variation on this attack, called "smurfing", sends ICMP packets to a broadcast address with your machines return IP, allowing them to flood you less detectably. You can find more information about the "smurf" attack at http://www.quadrunner.com/~chuegen/smurf.txt

    If you are ever under a ping flood attack, use a tool like tcpdump available at ftp://ftp.ee.lbl.gov/tcpdump.tar.Z (although it should be part of your Linux vendor's distribution) and is used to determine where the packets are coming from (or appear to be coming from), then contact your provider with this information. Ping floods can most easily be stopped at the router level or by using a firewall.

  • Email Bombing and Spamming - Sending out large quantities of unsolicited email can clog networks, causing depletion of resources, and degradation of network bandwidth. The newer versions of sendmail have greatly improved support for eliminiating this problem.

  • Ping 'o Death - The Ping 'o Death attack is a result of incoming ICMP ECHO REQUEST packets being larger than the kernel data structures that store this information can hold. Because sending a single, large (65,510 bytes) "ping" packet to many systems will cause them to hang or even crash, this problem was quickly dubbed the "Ping o' Death." This one has long been fixed, and is no longer anything to worry about.

    Someone has put together a further discussion of the Ping 'o Death attack, and is available at http://www.sophist.demon.co.uk/ping/

  • Teardrop / New Tear - One of the most recent exploits involves a bug present in the IP fragmentation code on Linux and Windows platforms. It is fixed in kernel version 2.0.33, and does not require selecting any kernel compile-time options to utilize the fix. Linux is apparently not vulnerable to the 'newtear' exploit.

You can find most exploit code, and a more in-depth description of how they work at http://www.rootshell.com using their search engine. Keep in mind that exploits are found on a periodic basis, and this list just describes the most popular.

11.7 Program Code Exploits

Much work is being done in this area by some very capable people to proactively catch these problems before further exploits are discovered. The Linux Security Audit Group is working on auditing many of the stock packages that vendors ship with their distributions. You can follow their efforts, or even help evaluate programs by joining the security audit list, security-audit-subscribe@ferret.lmh.ox.ac.uk and using ``subscribe'' in the body of the message. You can find the mailing list archives at http://www.nas.nasa.gov/Pubs/Mail/archive/linux-security-audit/ This is strictly an auditing list. It does not discuss issues regarding configuring your system to be more secure, reporting an exploit, etc. Do not expect to find information here about steps to perform an exploit.

Be sure to keep your subscription information, as it is very distracting to see unsubscribe requests being sent to the list. You can unsubscribe from the list by sending ``unsubscribe security-audit'' in the body of the message to security-audit-unsubscribe@ferret.lmh.ox.ac.uk

Chris Evans is doing a fine job of maintaining the mailing list, as well as a list of outstanding security issues, specifically, those in Red Hat 5.1. You can find this list at http://www-jcr.lmh.ox.ac.uk/~chris/rhbugs.txt

Some of the types of exploits performed on flaws in programming consist of at least the following:

  • Exploits in Vendor Packages - Vendors frequently update the packages in their distribution to include security exploit fixes. It is important that you remain aware of these changes, and apply their fixes as they are distributed. Most vendors have mailing lists to notify users of changes as they happen, and you should subscribe to those lists.

    See the Web Links section for URLs to the most common Linux vendor security updates, and the Mail Links section for addresses for notification from most security vendors. Additionally, there are several user-contributed programs that will monitor particular ftp sites for changes, and either notify you when they change, or update automatically.

  • Buffer Overflow - Common coding style is never to allocate buffers ``large enough'' and not checking for overflows. When such buffers are overflows, the executing program (daemon or set-uid program) can be tricked in doing some other things. Generally this works by overwriting a function's return address on the stack to point to another location.

  • World Writable Directories - Directories such as /tmp are typically used for temporary files, such as are created by the line printer daemon, X11, accounting programs, etc. A potential for guessing the names of the files written to this directory exists. As a result, poorly coded programs may have the potential for being exploited by writing into a prexisting file. For a more complete explanation, see the Writing Secure Code section.

11.8 Misconfigured Services

Misconfigured, or unnecessary services pose a significant threat to both host and network security. Exportable filesystems, inherently insecure services, too lenient configuration of a service, can all lead to a compromise.

Be sure to turn off any service that is not being used, and remove any executables that are not used. See the Network Security and Host Security for further information.

11.9 Known Vulnerabilities

There is certainly nothing easier than gathering the latest exploits from http://www.rootshell.com and trying them out on a list of machines.

Typically by the time the exploits are available on the Internet, the vendor has distributed a patched version of the susecptible program. Be sure to install these updated versions, or at the least disable the service until you can do so. See the Contacts section of this document for the locations of vendors' updates.

11.10 WWW and CGI-BIN attacks

Please see the WWW Security FAQ http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html for more information.

You can also find information on further securing Apache at http://www.apache.org/docs/misc/security_tips.html


Implementing Kernal Security in Linux

Kernel Security administration in Linux


10. Kernel Security

This is a description of the kernel configuration options that relate to security, and an explanation of what they do, and how to use them.

As the kernel controls your computer's networking, it is important that the kernel is very secure, and the kernel itself won't be compromised. To prevent some of the latest networkworking attacks, you should try and keep your kernel version current. You can find new kernels at ftp://ftp.kernel.org

10.1 Securing Hosts with Many Users

Your terminal servers, or servers with many users, can be further protected by employing Solar Designer's experimental ``Secure Linux'' kernel patches. As this is still experimental, and not a guaranteed fix, this patch is typically only advisable for hosts with many users, and not servers such as web or email servers. His work states he has done the following:

  • Make user stack area non-executable
  • Restricted links in /tmp
  • Restricted pipes in /tmp
  • Further restrict accessibility to /proc

See the documentation that comes with the software for more information.

10.2 Securelevel, Capabilities and Linux-Privs

Much of the security work being done these days is to prevent someone from ``upgrading'' their normal user privileges, and becomming root. If we could remove that ability entirely, it may help to solve many of the exploits we currently see.

Andrew Morgan has written a series of kernel patches, called Linux-Privs works towards implementing POSIX.1e (formerly POSIX 6) security model under Linux. It is a scheme that more precisely defines device and application permissions. Andrew states, Typically, the user will have to authenticate himself to such an applciation before it will perform its privileged task. This new scheme for system privilege lends itself well to restricting privileged access to the system and reduces the risk of intruders or poorly written applications running amok on the system.

There is an introductory document available at http://www.kernel.org/pub/linux/libs/security/linux-privs/doc/linux-privs.html/linux-privs.html which discusses the features he has implemented, as well an outline for those which still need to be worked on. Some of the available abilities include Access Control Lists (ACL), Mandatory Access Control (MAC), and Kernel-level auditing.

To quote James T. Dennis in the July 1998, issue of Linux Gazette (available at http://www.ssc.com/lg/)

One approach would be the POSIX.1e ``capabilities'' (which are more like VMS style ``privileges'' than true ``capabilities''). There is a bit of preliminary work being done on this in the 2.1.x kernels --- but nothing is likely be usable in 2.2 (so you're looking at Linux 2.4 before there is "stable" support for any of that).

Another approach is to limit the damage that ``root'' can do using something like the BSD securelevel features. Last I heard on the Linux kernel mailing list they had dropped plans to put in simple ``securelevel'' support in favor of a ``more flexible'' approach --- which would mesh better with the eventual POSIX.1e (``Orange Book'') work.

His discussion is really based on further securing the chroot() function call using ``capabilities'', but has some generally useful descriptions as well. You can find this discussion at http://www.ssc.com/lg/issue30/tag_chroot.html

Briefly, it will allow you to disable access to functions such as mknod(), chroot(), mount(), etc, and move the privileges to the executable itself, rather than simply by being the root user.

There is further information in the Linux kernel 2.1.x sources, as well as the June 25 issue of Linux Weekly News available at http://www.lwn.net/980625/

10.3 Kernel Compile Options

  • IP: Drop source routed frames (CONFIG_IP_NOSR)

    This option should be enabled. Source routed frames contain the entire path to their destination inside of the packet. This means that routers the packet goes thru does not need to inspect the packet, and just forwards it on. This could lead to data entering your system that may be a potential exploit.

  • IP: Firewalling (CONFIG_IP_FIREWALL)

    This option is necessary if you are going to configure your machine as a firewall, do masquerading, or wish to protect your dial-up workstation from someone entering via your PPP dial-up interface.

  • IP: forwarding/gatewaying (CONFIG_IP_FORWARD)

    If you enable IP forwarding, your Linux box essentially becomes a router. If your machine is on a network, you could be forwarding data from one network to another, and perhaps subverting a firewall that was put there to prevent this from happening. Normal dial-up users will want to disable this, and other users should concentrate on the security implications of doing this. Firewall machines will want this enabled, and used in conjunction with firewall software.

    You can enable and disable IP forwarding dynamically using the following command:

            root#  echo 1 > /proc/sys/net/ipv4/ip_forward
    and disable it with the command:
            root#  echo 0 > /proc/sys/net/ipv4/ip_forward
    This file (and many other files in /proc) will always appear to be zero length, but in fact aren't. This is a newly introduced kernel feature, so be sure you are using a kernel 2.0.33 or later.

  • IP: firewall packet logging (CONFIG_IP_FIREWALL_VERBOSE)

    This option gives you information about packets your firewall received, like sender, receipient, port, etc.

  • IP: always defragment (CONFIG_IP_ALWAYS_DEFRAG)

    Generally this option is disabled, but if you are building a firewall or a masquerading host, you will want to enable it. When data is sent from one host to another, it does not always get sent as a single packet of data, but rather it is fragmented into several pieces. The problem with this is that the port numbers are only stored in the first fragment. This means that someone can insert information into the remaining packets for your connection that aren't supposed to be there. It could also prevent a teardrop attack against an internal host that is not yet itself patched against it.

  • IP: syn cookies (CONFIG_SYN_COOKIES)

    SYN Attack is a denial of service (DoS) attack that consumes all the resources on your machine, forcing you to reboot. We can't think of a reason you wouldn't normally enable this. In the 2.1 kernel series this config option mearly allows syn cookies, but does not enable them. To enable them, you have to do:

                        root@myhost# echo 1 > /proc/sys/net/ipv4/tcp_syncookies

  • Packet Signatures (CONFIG_NCPFS_PACKET_SIGNING)

    This is an option that is available in the 2.1 kernel series that will sign NCP packets for stronger security. Normally you can leave it off, but it is there if you do need it.

  • IP: Firewall packet netlink device (CONFIG_IP_FIREWALL_NETLINK)

    This is a really neat option that allows you to analyze the first 128 bytes of the packets in a userspace program, to determine if you would like to accept or deny the packet, based on its validity.

10.4 Kernel Devices

There are a few block and character devices available on Linux that will also help you with security.

The two devices /dev/random and /dev/urandom are provided by the kernel to retrieve random data at any time.

Both /dev/random and /dev/urandom should be secure enough to use in generating PGP keys, SSH challenges, and other applications where secure random numbers are requisite. Attackers should be unable to predict the next number given any initial sequence of numbers from these sources. There has been a lot of effort put in to ensuring that the numbers you get from these sources are random in every sense of the word random.

The only difference is that /dev/random runs out of random bytes and it makes you wait for more to be accumulated. Note that on some systems, it can block for a long time waiting for new user-generated entry to be entered into the system. So you have to use care before using /dev/random. (Perhaps the best thing to do is to use it when you're generating sensitive keying information, and you tell the user to pound on the keyboard repeatedly until you print out "OK, enough".)

/dev/random is high quality entropy, generated from measuring the inter-interrupt times etc. It blocks until enough bits of random data are available.

/dev/urandom is similar, but when the store of entropy is running low, it'll return a cryptographically strong hash of what there is. This isn't as secure, but it's enough for most applications.

You might read from the devices using something like:

               user@myhost# head -c 6 /dev/urandom | mmencode

This will print (approximately) six random characters on the console, suitable for password generation. You can find mmencode(1) (perhaps also known as mimencode on some systems) in the metamail mail package.

See /usr/src/linux/drivers/char/random.c for a description of the algorithm.

Thanks to Theodore Y. Ts'o, Jon Lewis, and others from Linux-kernel for helping me (Dave) with this.

Cryptography and Data Encription in Linux

How Cryptography works with Linux Systems?


9. Data Encryption, Cryptography and Authentication

An integral part of host and network security is data encryption. There are vast resources of information on the Internet available on the topic of data security. Various data encryption mechanisms are available for use with Linux.

This section attempts to discuss some of the encryption features that are available for use with Linux. For an overview of encryption and cryptography, be sure to consult the RSA Cryptography FAQ, available at http://www.rsa.com/rsalabs/newfaq/

9.1 Password Security

One of the most important security features used today are passwords. It is important for both you and all your users to have secure, unguessable passwords. Most of the more recent Linux distributions include password programs that do not allow you to set a easily guessable password. Make sure your passwd program is up to date and has these features.

Most UNIXs (and Linux is no exception) primarily use a one-way encryption algorithm, called DES (Data Encryption Standard) to encrypt your passwords. This encrypted password is then stored in (typically) /etc/passwd (or less commonly) /etc/shadow. When you attempt to login, whatever you type in is encrypted again and compared with the entry in the file that stores your passwords. If they match, it must be the same password, and you are allowed access. Although DES is a two-way encryption algorithm (you can code and then decode a message, given the right keys), the variant that most unicies use is one-way. This means that it should not be possible to reverse the encryption to get the password from the contents of /etc/passwd (or /etc/shadow).

Any entry in the password file with a user-ID of ``0'' (zero) is a root entry, regardless of what it's called.

Choose effective passwords. There is a great deal of information available on the Internet regarding choosing good passwords. A password minimum of 6 characters should be enforced, and 8 characters provides a significant improvement in security. You can find more information on improving password security at ftp://sunos-wls.acs.ohio-state.edu:/pub/security/Dan_Klein_password_security.ps.Z which is titled ``Foiling the Cracker: A Survey of, and Improvements, to Password Security''.

Brute force attacks, such as ``Crack'' or ``John the Ripper'' (see below) can often guess passwords unless your password is sufficiently random. PAM modules (see below) allow you to use a different encryption routine with your passwords (MD5 or the like).

You can go to http://consult.cern.ch/writeup/security/security_3.html for information on how to choose a good password.

There is also a quick list of things to keep in mind when choosing a password available at http://www.alw.nih.gov/Security/Docs/passwd.html and should be consulted when developing your security policy.

9.2 PGP and Public Key Cryptography

Public Key Cryptography, such as that which is used for PGP, involves cryptography that uses one key for encryption, and one key for decryption. Traditionally, cryptography involves using the same key for encryption that is used for decryption. This "secret key" must be known to both parties, and somehow transferred from one another securely.

Public key encryption alleviates the need to securely transmit the key that is used for encryption by using two separate keys, a public key and a private key. Each person's public key is available by anyone to do the encryption, while at the same time each person keeps his or her private key to decrypt messages encrypted with the correct public key.

There are advantages to both public key and private key cryptography, and you can read about those differences in the RSA Cryptography FAQ, listed at the end of this section.

PGP (Pretty Good Privacy) is well supported on Linux. Versions 2.6.2 and 5.0 are known to work well. For a good primer on PGP and how to use it, take a look a the PGP FAQ. http://www.pgp.com/service/export/faq/55faq.cgi

Be sure to use the version that is applicable to your country, as due to export restrictions by the US Government, strong-encryption is prohibited from being transferred in electronic form outside the country.

US export controls are now managed by EAR (Export Administration Regulations). They are no longer governed by the International Traffic in Arms Regulations (ITAR).

There is a good introductory guide explaning public key cryptography, that includes graphic illustrations, available at PC Magazine Online, available http://www8.zdnet.com/pcmag/features/inetsecurity/howencrypt.htm

There is also a step-by-step guide for configuring PGP on Linux available at http://mercury.chem.pitt.edu/~angel/LinuxFocus/English/November1997/article7.html It was written for the International version of PGP, but is easily adaptable to the United States version. You may also need a patch for some of the latest versions of Linux, which is available at ftp://sunsite.unc.edu/pub/Linux/apps/crypto.

More information on cryptography can be found in the RSA cryptography FAQ, available at http://www.rsa.com/rsalabs/newfaq/. Here you will find information on such terms as "Diffie-Hellman", "public-key cryptography", "Digital Certificates", etc.

An excellent 147-page publication written by the government describing practically all you'll need to know unless you're a cryptographer is available at http://csrc.nist.gov/nistpubs/800-2.txt

There is a project working on a free re-implementation of PGP with open source. See the GNU Privacy Guard web page for more information, available at http://www.d.shuttle.de/isil/crypt/gnupg.html

9.3 SSL, S-HTTP, HTTPS and S/MIME

Often times users ask about the differences between the various security and encryption protocols, and how to use them. While this isn't an encryption document, it is a good idea to explain briefly what each are, and where to find more information.

  • SSL: - SSL, or Secure Sockets Layer, is an encryption method developed by Netscape to provide security over the Internet. It supports several different encryption protocols, and provides client and server authentication. SSL operates at the transport layer, creates a secure encrypted channel of data, and thus can seamlessly encrypt data of many types. This is most commonly seen when going to a secure site to view a secure online document with Communicator, and serves as the basis for secure communications with Communicator, as well as many other Netscape Communications data encryption. More information can be found at http://www.consensus.com/security/ssl-talk-faq.html. Information on Netscape's other security implementations, and a good starting point for these protocols is available at http://home.netscape.com/info/security-doc.html.

  • S-HTTP: - S-HTTP is another protocol that provides security services across the Internet. It was designed to provide confidentiality, authenticity, integrity, and non-repudiability (cannot be mistaken for someone else, and I cannot deny my actions later) while supporting multiple key management mechanisms and cryptographic algorithms via option negotiation between the parties involved in each transaction. S-HTTP is limited to the specific software that is implementing it, and encrypts each message individually. [ From RSA Cryptography FAQ, page 138]

  • S/MIME: - S/MIME, or Secure Multipurpose Internet Mail Extension, is an encryption standard used to encrypt electronic mail, or other types of messages on the Internet. It is an open standard developed by RSA, so it is likely we will see it on Linux one day soon. More information on S/MIME can be found at http://home.netscape.com/assist/security/smime/overview.html.

9.4 IPSec and S/WAN and other IP Encryption Implementations

IPSec is an effort by the IETF to create cryptographically secure communications at the IP network level, which also provides authentication, integrity, access control, and confidentiality. IPsec is the basic host-to-host security mechanism. It is appropriate for use any time address-based protection would have been used, including with such programs as rsh and rlogin. If and when platforms support user-based keying, this scope may be expanded. Information on IPSec and Internet draft can be found at http://www.ietf.org/html.charters/ipsec-charter.html. You can also find links to other protocols involving key management, and an IPSec mailing list and archives.

A good starting point for Linux implementations of Virtual Private Networking is available at http://www.imib.med.tu-dresden.de/imib/Internet/index.html

One of the Linux implementations, which is being developed at the University of Arizona, uses an object-based framework for implementing network protocols called ``x-kernel'', and can be found at http://www.cs.arizona.edu/xkernel/hpcc-blue/linux.html. Most simply, the x-kernel is a method of passing messages at the kernel level, which makes for an easier implementation.

There is also an implementation of RSA's Secure Wide Area Networking, S/WAN, called FreeSWAN, available at http://www.xs4all.nl/~freeswan/

A description of S/WAN is available at http://www.sunworld.com/swol-06-1996/swol-06-swan.html

Microsoft Point-to-Point Tunneling Protocol is also available for Linux. You can find more information on this at http://www.pdos.lcs.mit.edu/~cananian/Projects/PPTP/. More information on this protocol is available from the Linux PPTP page.

An implementation of PPTP that works with Linux masquerading is available at http://bmrc.berkeley.edu/people/chaffee/linux_pptp.html as well as kernel patches, and a pointer to more information.

It is well known now that PPTP is insecure, and really should only be used in existing installations. Rhino9, the security research group, have put together an exploit, as well as more documentation on the protocols involved. You can find it at http://www.rhino9.ml.org/texts/pptp.doc

As with other forms of cryptography, it is not distributed with the kernel by default due to export restrictions.

9.5 The Secure Shell and Secure Telnet

SSH and stelnet are programs that allow you to login to remote systems and have a encrypted connection.

SSH is a suite of programs used as a secure replacement for rlogin, rsh and rcp. It uses public-key cryptography to encrypt communications between two hosts, as well as for user authentication. This can be used to securely login to a remote host or copy data between hosts, while preventing man-in-the-middle attacks (session hijacking) and DNS spoofing. It will perform data compression on your connections, and secure X11 communications between hosts. The SSH home page can be found at http://www.cs.hut.fi/ssh/

You can also use SSH from your Windows workstation to your Linux SSH server. There are several freely available Windows client implementations, including the one at http://guardian.htu.tuwien.ac.at/therapy/ssh/ as well as a commercial implementation from DataFellows, at http://www.datafellows.com.

There is also an open source implementation of SSH being developed. You can find more information about this at http://www.net.lut.ac.uk/psst/

SSLeay is a free implementation of Netscape's Secure Sockets Layer protocol, developed by Eric Young. It includes several applications, such as Secure telnet, a module for Apache, several databases, as well as several algorithms including DES, IDEA and Blowfish.

Using this library, a secure telnet replacement has been created that does encryption over a telnet connection. Unlike SSH, stelnet uses SSL, the Secure Sockets Layer protocol developed by Netscape. You can find Secure telnet and Secure FTP by starting with the SSLeay FAQ, available at http://www.psy.uq.oz.au/~ftp/Crypto/

An SSL-based POP3 daemon is also available at http://mike.daewoo.com.pl/computer/stunnel/

9.6 SKIP - Simple Key management for Internet Protocols

SKIP, which provides IP-Level cryptography, much like SSH, is available for Linux. A quick overview from http://www.skip.org states:

SKIP secures the network at the IP packet level. Any networked application gains the benefits of encryption, without requiring modification. SKIP is unique in that an Internet host can send an encrypted packet to another host without requiring a prior message exchange to set up a secure channel. SKIP is particularly well-suited to IP networks, as both are stateless protocols. Some of the advantages of SKIP include:
  • No connection setup overhead

  • High availability - encryption gateways that fail can reboot and resume decrypting packets instantly, without having to renegotiate (potentially thousands) of existing connections

  • Allows uni-directional IP (for example, IP broadcast via satellite or cable)

  • Scalable multicast key distribution

  • SKIP gateways can be configured in parallel to perform instant-failover

There is a wealth of information available at http://www.skip.org as well as the actual Linux implementation available at http://www.tik.ee.ethz.ch/~skip/

9.7 PAM - Pluggable Authentication Modules

Newer versions of the Red Hat Linux distribution ship with a unified authentication scheme called "PAM". PAM allows you to change on the fly your authentication methods, requirements, and encapsulate all local authentication methods without re-compiling any of your binaries. Configuration of PAM is beyond the scope of this document, but be sure to take a look at the PAM web site for more information. http://www.kernel.org/pub/linux/libs/pam/index.html

Just a few of the things you can do with PAM:

  • Use a non DES encryption for your passwords. (Making them harder to brute force decode)
  • Set resource limits on all your users so they can't perform denial of service attacks (number of processes, amount of memory, etc)
  • Enable shadow passwords (see below) on the fly
  • allow specific users to login only at specific times from specific places

Within a few hours of installing and configuring your system, you can prevent many attacks before they even occur. For example, use PAM to disable the system-wide usage of dot-rhosts files in user's home directories by adding these lines to /etc/pam.d/login:

                #
# Disable rsh/rlogin/rexec for users
#
login auth required pam_rhosts_auth.so no_rhosts

9.8 Cryptographic IP Encapsulation (CIPE)

The primary goal of this software is to provide a facility for secure (against eavesdropping, including traffic analysis, and faked message injection) subnetwork interconnection across an insecure packet network such as the Internet.

CIPE encrypts the data at the network level. Packets travelling between hosts on the network are encrypted. The encryption engine is placed near the driver which sends and receives packets.

This is unlike SSH, which encrypts the data by connection, at the socket level. A logical connection between programs running on different hosts is encrypted.

CIPE can be used in tunneling, in order to create a Virtual Private Network. Low-level encryption has the advantage that it can be made to work transparently between the two networks connected in the VPN, without any change to application software.

Summarized from the CIPE documentation:

The IPSec standards define a set of protocols which can be used (among other things) to build encrypted VPNs. However, IPSec is a rather heavyweight and complicated protocol set with a lot of options, implementations of the full protocol set are still rarely used and some issues (such as key management) are still not fully resolved. CIPE uses a simpler approach, in which many things which can be parameterized (such as the choice of the actual encryption algorithm used) are an install-time fixed choice. This limits flexibility, but allows for a simple (and therefore efficient, easy to debug...) implementation.

Further information can be found at http://www.inka.de/~bigred/devel/cipe.html

As with other forms of cryptography, it is not distributed with the kernel by default due to export restrictions.

9.9 Kerberos

Kerberos is an authentication system developed by the Athena Project at MIT. When a user logs in, Kerberos authenticates that user (using a password), and provides the user with a way to prove her identity to other servers and hosts scattered around the network.

This authentication is then used by programs such as rlogin to allow the user to login to other hosts without a password (in place of the .rhosts file). This authentication method can also used by the mail system in order to guarantee that mail is delivered to the correct person, as well as to guarantee that the sender is who he claims to be.

The overall effect of installing Kerberos and the numerous other programs that go with it is to virtually eliminate the ability of users to "spoof" the system into believing they are someone else. Unfortunately, installing Kerberos is very intrusive, requiring the modification or replacement of numerous standard programs.

You can find more information on kerberos at http://www.veritas.com/common/f/97042301.htm and the code can be found at http://nii.isi.edu/info/kerberos/

[From: Stein, Jennifer G., Clifford Neuman, and Jeffrey L. Schiller. "Kerberos: An Authentication Service for Open Network Systems." USENIX Conference Proceedings, Dallas, Texas, Winter 1998.]

9.10 Shadow Passwords.

Shadow passwords are a means of keeping your encrypted password information secret from normal users. Normally this encrypted password is stored in your /etc/passwd file for all to read. They can then run password guesser programs on it and attempt to determine what it is. Shadow passwords save this information to a /etc/shadow file that only privileged users can read. In order to run shadow passwords you need to make sure all your utilities that need access to password information are recompiled to support it. PAM (above) also allows you to just plug in a shadow module and doesn't require re-compilation of executables. You can refer to the Shadow-Password HOWTO for further information if necessary. It is available at http://sunsite.unc.edu/LDP/HOWTO/Shadow-Password-HOWTO.html It is rather dated now, and will not be required for distributions supporting PAM.

9.11 Crack and John the Ripper

If for some reason your passwd program is not enforcing non easily guessable passwords, you might want to run a password cracking program and make sure your users passwords are secure.

Password cracking programs work on a simple idea. They try every word in the dictionary, and then variations on those words. They encrypt each one and check it against your encrypted password. If they get a match they are in. Also, the "dictionary" may include usernames, Star Trek ships, foreign words, keyboard patterns, etc...

There are a number of programs out there...the two most notable of which are ``Crack'' and ``John the Ripper'' http://www.false.com/security/john/index.html . They will take up a lot of your CPU time, but you should be able to tell if an attacker could get in using them by running them first yourself and notifying users with weak passwords. Note that an attacker would have to use some other hole first in order to get your passwd (Unix /etc/passwd) file, but these are more common than you might think.

9.12 Cryptography and File Systems

Linux provides several mechanisms in which to encrypt data on a filesystem.

CFS is a way of encrypting entire directory trees and allow users to store encrypted files on them. It uses a NFS server running on the local machine. RPMs are avail at http://www.replay.com/Red Hat/ and more information on how it all works is at: ftp://ftp.research.att.com/dist/mab/

TCFS improves on CFS, adding more integration with the file system, so that it's transparent to any users using the file system that it's encrypted. more information at: http://edu-gw.dia.unisa.it/tcfs/

It also need not be used on entire filesystems. It works on directories trees as well.

There are two implementations of DES encryption on the loopback device also available. It is available at ftp://ftp.csua.berkeley.edu/pub/cypherpunks/filesystems/linux Patches to the 2.0 kernel and the mount executable are available at ftp://ftp.is.co.za/linux/local/kernel/crypto/loopback-device-berkeley-recent/ Patches to the 2.1 kernel, written by Andrew E. Mileski, aem@netcom.ca are available at ftp://ftp.is.co.za/linux/local/kernel/crypto/loopback-device-aem

Linux File and the File System Security Guide

How can we make Files and File System secure in Linux?


8. Files and File System Security

A few minutes of preparation and planning ahead before putting your systems online can help to protect your system, and the data that is stored on it.

This section discusses some of the methods in which you can use to secure the files on your system, some general guidelines for improving the overall security of the files on your system, and some ideas for preventing problems from occuring in the first place. It also discusses the commands to use to modify the permissions and ownership of files and directories on your system.

Before we discuss some of these methods of improving file system security, it is important to have an understanding of basic Linux file security, ownership, and what each of the fields from a file listing actually mean.

To display the ownership and permissions of a file on your system, use the long-listing option, as well as the display all files option to the ls(1) command. A typical /bin/ls -la command might show the following, with the first line being a field marker:

    |----1----|-2--|---3----|----4-----|---5--|-----6------|---7-----|
1. drwxrwxr-x 24 root users 1024 Aug 19 00:05 .
2. drwxr-xr-x 22 root root 1024 Aug 11 22:04 ..
3. drwxr-xr-x 3 root root 1024 Jun 19 03:40 Mail
4. -rw-rw-r-- 1 dave security 43244 Jul 20 14:11 README
5. drwxrwsr-x 17 dave security 1024 Jul 31 01:48 Security
[More not shown]

Each of these fields provide useful information to the security administrator. First, a description of each field (as shown from left to right), then a more in-depth explanation of the most important ones. The numbers down the left side represent the line numbers, which will be referred to later.

  • Field One: Permissions for this file or directory. The first nine positions from the right describe the user, group, and other permissions, in groups of three. Within each group of three, the first character denotes read access, the second denotes write access, and the last denotes execute, working from left to right. The tenth position describes the type of file, which can be either a regular file, directory, FIFO, symbolic link, or other type of special file.

  • Field Two: Number of hard links to this file or directory. These links can be directories, for example. In this case the current directory (line 1) most likely has 24 directories below it, of which only two are shown here (Security and Mail)

  • Field Three: Owner of the file or directory. This field is as important as the permissions themselves.

  • Field Four: The group to which the file belongs. This field, in conjunction with the owner field (field three) are necessary in order to set the permissions correctly.

  • Field Five: Size of file

  • Field Six: Modification time

  • Field Seven: File name

8.1 File Permissions and Ownership

Continuing where we left off in the previous section, we can now discuss some of the fields described above. Particularly, field one and fields three and four are the most exiciting.

Linux separates access control on files and directories according to three characteristics: owner, group, and other. There is always exactly one owner, any number of members of the group, and everyone else.

The files within each of these categories have specific permissions with which they are accessed. File permissions, including regular files, special files (such as FIFOs, sockets, etc), or symbolic links (which dereference the permissions to the file they point to) can have any one, or any, of the following:

  Symbol        Permission      Description
-------------------------------------------------------------------
r Read Can be opened to read the contents
w Write Can be modified, including appending
and deleting
x Execute Can execute the file if it is a
program or shell script
s Special Perm setuid or setgid permission
- Access Denied Cannot be read, written, or executed,
depending on the position of the `-'

The read, write, and execute permissions should be pretty clear as to their meaning. However, the ``s'' symbol may need to explanation. The next two sections address this symbol.

Set User Identification Attribute

When the set user ID access mode is set in the owner permissions, and the file is executable, processes which run it are granted access to system resources based on the owner of the file.

Be extremely careful when setting these permissions. Any user who runs that file assumes the permissions of the owner of the executable file, instead of the user who created the process. This is the cause of many ``buffer overflow'' exploits, typically resulting in superuser privileges.

The setuid permission is shown as an s in the file permissions. For example, the setuid permission on the /usr/bin/passwd command enables normal users to read and write an otherwise inaccessible /etc/passwd file:

user@myhost $ ls -l /etc/shadow /etc/passwd /usr/bin/passwd
-r-------- 1 root root 659 Jul 25 19:40 /etc/shadow
-rw-r--r-- 1 root root 711 Jul 25 19:40 /etc/passwd
-r-sr-xr-x 1 root bin 15613 Apr 27 12:29 /usr/bin/passwd

You will notice that the s takes the place of the execute bit in the example above. This special permission mode really has no meaning unless the file also has execute permission as well.

In the example we see the /etc/shadow file is only readable by root, yet the /usr/bin/passwd file enables us to write our password changes there. When either a normal user, a member of the bin group, or even anyone else executes /usr/bin/passwd, it is really run as root, due to the ``s'' bit set in the owner's permissions field.

Keep in mind that setuid has a different meaning when applied to directories. See the explanation for directories that follows.

It is advisable to keep setuid and setgid binaries on your system to a minimum, in order to reduce the possiblity of their being exploited. You should never execute an suid or sgid binary as a normal user, without knowing what it does. And certainly do not arbitrarily modify an otherwise non-setuid binary to have setuid permissions, simply for convience.

Set Group Identification Attribute

If set in the group permissions, this bit controls the ``set group ID'' status of a file. This behaves the same way as setuid, except the group is affected instead. The file must also be executable for this to have any effect. Upon execution of a file with this bit set, the effective group ID for the process is changed to the group owner of the file and a user is granted access based on the permissions given to that group. The wall(1) program, /usr/bin/wall, is used to ``write all'' users that are logged on to the system at the same time. It must be set group ID in order to have enough permission to write to terminals which do not belong to the user running the program:

user@myhost$ ls -l /usr/bin/wall
-r-xr-sr-x 1 root tty 5492 May 7 14:02 /usr/bin/wall
We see here that everyone has the ability to execute the binary. It is owned by root, and a member of the tty group. Having each user on the system a member of the tty is not practical, and neither is changing the group to which the wall program belongs.

It is advisable to keep setuid and setgid binaries on your system to a minimum, in order to reduce the possiblity of their being exploited. You should never execute an suid or sgid binary as a normal user, without knowing what it does. And certainly do not arbitrarily modify an otherwise non-setuid binary to have setuid permissions, simply for convience.

Keep in mind that setgid has a different meaning when applied to directories. See the explanation for directories that follows.

8.2 Directory Permissions and Ownership

You can protect the files in a directory, and its subdirectories, by denying access to the entire directory itself. The permissions of a directory typically have a slightly different meaning than the equivilent permissions on a file. Additional permissions are available on directories, including setuid, setgid, and the sticky bit. Directory entries can have any one, or any, of the following:

  Symbol        Permission      Description
---------------------------------------------------------------------
r Read List file contents
w Write Add, modify or remove files in the
directory
x Execute Open or execute files in the directory
- Access Denied Cannot be read, written, or executed,
depending on the position of the `-'
s Special Mode Set group ID bit is active (only in
``group'' section
t Special Mode Save text attribute

It is important to understand the meanings of each of these symbols, and how you can use them to protect your files. Many of these symbols may be clear as to its meaning, but perhaps the other modes deserve a more in-depth explanation.

The read symbol indicates the ability to list the contents within the directory, assuming you also have access to open the directory.

The write symbol indicates the ability to add, remove, or modify files within the directory, also assuming you have access to open the directory. It is important to note that write access on a file within a directory is not required to delete it!

Save Text Attribute (Sticky Bit)

The Save Text (also known as the sticky bit) is an option really only available to directories. If the sticky bit is set on a directory, then a user may only delete files that the user owns or for which he has explicit write permission granted, even when he has write access to the directory. This is designed for directories which are world-writable, but where it may not be desirable to allow any user to delete files at will. The sticky bit is seen as a ``t'' in a long directory listing.

For example, the /tmp directory is typically world-writable, so everyone has a place in which to write temporary files. The /tmp directory looks like this in a long-listing:

user@myhost$ ls -ld /tmp
drwxrwxrwt 3 root root 2048 Aug 23 16:25 /tmp
This shows that everyone can read, write, and access the directory. But the ``t'' shows us that only the user (and root, of course) that created a file there can delete that file.

The chmod(1) command controls the sticky bit permissions. For example, you can add the sticky bit to a directory using the following:

root@myhost# ls -ld spool
drwxrwxrwx 3 root root 2048 Aug 23 16:25 spool
root@myhost# chmod +t spool
root@myhost# ls -ld spool
drwxrwxrwt 3 root root 2048 Aug 23 16:25 spool

While you can use the sticky bit on files, it does not really serve a purpose on Linux systems, as it did on UNIX systems of yester-year.

Additionally, this option should not be used casually. Instead, create a directory in the user's home directory to which he or she can write temporary files. The TMPDIR environment variable can be set, and programs that use the tempnam(3) system call will look for this variable and use it, instead of /tmp See the section on Writing Secure Code for a further explanation why there are hidden security problems with /tmp

Set Group Identification Attribute

If you set the setgid bit on a directory, files created in that directory will have the same group ownership as the directory itself, rather than the primary group of the user that created the file.

This attribute is useful when multiple users need to access specific files, but still require isolation from other files. Having them work from a common directory with the setgid attribute set means that any files created there will obtain the permissions of that common directory. For example, Joe and Mary might be in different primary groups, but need to collaborate on a common project. In this case, creating a common directory can be used to which both have write access.

You can control the setgid attribute on a directory with the following command:

joe@myhost$ ls -ld common_dir
drwxrwxr-x 2 joe dev 1024 Aug 23 17:03 common_dir
joe@myhost$ chmod g+s common_dir
joe@myhost$ ls -ld common_dir
drwxrwsr-x 2 joe dev 1024 Aug 23 17:03 common_dir
We can see here that the ``s'' in place of the execute bit in the group permissions indicates all files written to the common_dir will now belong to group dev

8.3 Changing File and Directory Permissions

The chmod(1) command controls the changing of file and directory permissions. Only the owner (or superuser, of course) can change the permissions of a file or directory.

The chmod(1) command has two modes of operation. The first one, called absolute mode, works by explictly specifying the permissions using an octal value, such as 644 or 755. The second mode of operation, called symbolic mode, works by using combinations of letters and symbols to add or remove permissions.

Using the octal values method of changing permissions can be more difficult to use at first, but you'll find it is faster and easier, once you have made the inital time investment, and learned how to do it correctly.

Changing File Permissions Using Octal Values (Absolute Mode)

The octal value for specifying permissions works by specifying a numeric argument for the permissions for which you wish to change. These numbers are used in sets of three to set permissions for owner, group, and other (everyone else). The following table shows what each octal value means:

Value           Permissions     Description
---------------------------------------------------------------------
0 --- No permission
1 --x Execute only
2 -w- Write only
3 -wx Write and execute (shell scripts need
read permission to be executed)
4 r-- Read only
5 r-x Read and execute
6 rw- Read and write
7 rwx Read, write, and execute (full
control)

Using the table above, you can use chmod(1) to modify file and directory permissions. It helps to disect each of the sections, and explain one at a time. Given the following example:

user@myhost$ ls -l
-rwxrw-r-- 1 dave sysadmin 36012 Aug 21 01:06 run.pl

We see from this example that dave is the owner, and the file belongs to group sysadmin. From the information in the first field, we see this is a normal file, as shown by the - as the left-most character in the left-most field. The owner of this perl script, dave, has permission to read, write, and execute this file. The group, sysadmin has permission to read and write to it (including deleting it). Everyone else can only read this file. Using that information, we can look more closely at the permissions that file has:

Access Class    user    group   other
Symbolic Mode r w x r w - r - -
Binary Mode 1 1 1 1 1 0 1 0 0
Octal Equiv 7 6 4

The octal equivilent of the binary number is generated using powers of two. Each position that is enabled, as shown by a 1 instead of a 0, represents a power of two. Specifically, from right to left, we have 2^0, or 1, then 2^1, or 2, then 2^2, or 4. Adding the enabled values corresponding to the bits that are enabled gives the octal number we use with chmod(1).

One might decide to remove the ability for other to read this file. You can do this using chmod(1) as follows:

user@myhost$ ls -l run.pl
-rwxrw-r-- 1 dave sysadmin 36012 Aug 21 01:06 run.pl
user@myhost$ chmod 760 run.pl
user@myhost$ ls -l run.pl
-rwxrw---- 1 dave sysadmin 36012 Aug 21 01:06 run.pl

We see here that run.pl has now been modified to deny read access (as well as all other types of access) to users other than those in group sysadmin, and the owner (dave in this case)

Changing Directory Permissions Using Octal Values (Absolute Mode)

Using the same format as used to describe file permissions shown above, we will continue, and explain how changing directory permissions using octal values work.

The octal value for specifying permissions works by specifying a numeric argument for the permissions for which you wish to change. These numbers are used in sets of three to set permissions for owner, group, and other (everyone else).

The primary difference between permissions on files and permissions on directories is access control. Permissions on directories typically indicate accessibility. Hint: You cannot execute a directory ;->

The following table shows what each octal value means, as well as what access control is given for the corresponding permissions:

Value   Permissions     Description
---------------------------------------------------------------------
0 --- No permission
1 --x Access - gives ability to work with programs
and files in the directory that they already
know the name of, but hides all others
2 -w- Write - really has no meaning on its own
3 -wx Write and execute - ability to write to files
you already know the name of
4 r-- Read only - really has no meaning on its own
5 r-x Read and execute - gives ability to enter
directory, and list contents, but cannot write
or delete
6 rw- Read and write - really has no meaning on its
own
7 rwx Read, write, and access - ability to list
contents of directory, as well as read and
write in it

Using the table above, you can use chmod(1) to modify file and directory permissions. It helps to disect each of the sections, and explain one at a time. Given the following example:

user@myhost$ ls -l
drwxr-x--- 1 dave sysadmin 1024 Aug 21 01:06 games

We see from this example that dave is the owner, and the directory belongs to group sysadmin. From the information in the first field, we see this is a directory, as shown by the d as the left-most character in the left-most field. The owner of this directory, dave, has permission to read, write, and access this directory. The group, sysadmin has permission to access the directory, as well as list its contents. Files within this directory with the appropriate read permission would also be able to be read. Other users are not allowed to access this directory at all. Using that information, we can look more closely at the permissions that directory has:

Access Class            User    Group   Other
Symbolic Mode r w x r - x - - -
Binary Mode 1 1 1 1 0 1 0 0 0
Octal Equivilent 7 5 0

The octal equivilent of the binary number is generated using powers of two. Each position that is enabled, as shown by a 1 instead of a 0, represents a power of two. Specifically, from right to left, we have 2^0, or 1, then 2^1, or 2, then 2^2, or 4. Adding the enabled values corresponding to the bits that are enabled gives the octal number we use with chmod(1).

One might decide to give other users the ability for other to access this file, and list the contents within it. You can do this using chmod(1) as follows:

user@myhost$ ls -ld games
drwxr-x--- 1 dave sysadmin 1024 Aug 21 01:06 games
user@myhost$ chmod 755 games
user@myhost$ ls -ld games
drwxr-xr-x 1 dave sysadmin 1024 Aug 21 01:06 games

We see here that games has now been modified to permit access to users other than those in group sysadmin, and the owner (dave in this case)

Changing Permissions Using Symbols (Symbolic Mode)

The symbolic mode is perhaps the easier of the two methods to use to change file permissions. It is probably the one you should work with first if you are just learning this. This section discusses the basic means in which one can change the permissions of a file or directory, using chmod(1)

The symbolic mode of chmod(1) works on the concept of access classes. These classes consist of (u)ser, which is the owner of the file, (g)roup, of which the user is a member, and (o)ther, which is those users not a member of the group, or the owner of the file. The final mode is (a)ll, which consists of all three of the previous modes.

Using these modes, in conjunction with the desired permissions, you can modify the access to a particular file or directory. The permissions are one or more of (r)ead, (w)rite, and e(x)ecute.

Combining the access class and the new permissions desired, with an operator, gives you the ability to change the permissions on a file or directory. The available operators are +, which means to add to the existing permissions, -, which means to subtract from the existing permissions, and =, which means set the new permissions equal to those provided.

For example, ``a+rw'' means to add read and write permission to all three groups of users. Using ``go=r'' means to set the group and other fields to only have read access, regardless of what they had previously.

A more complete example is as follows:

dave@myhost$ ls -l nsmail
drwxr-xr-x 2 dave dave 1024 Aug 7 00:17 nsmail
dave@myhost$ chmod go=rx nsmail
dave@myhost$ ls -l nsmail
drwx------ 2 dave dave 1024 Aug 7 00:17 nsmail

To remove write access for everyone from a file, use the minus sign:

dave@myhost$ chmod a-w myfile
dave@myhost$ ls -l myfile
-r--r--r-- 1 dave dave 424 Aug 23 23:10 myfile

You can control the setuid and setgid on files and directories, as well as the sticky bit, using the symbolic mode with chmod(1). Such an example might be as follows:

1.    root@myhost# ls -l
2. drwxr-xr-x 2 root sysadmin 1024 Aug 24 01:18 groupdir
3. -rwxr-x--- 1 root sysadmin 8077 Aug 24 01:19 myprog
4. drwxr-xr-x 2 root root 1024 Aug 24 01:18 spool
5. root@myhost# chmod g+ws groupdir
6. root@myhost# chmod u+s myprog
7. root@myhost# chmod o+t,a+w spool
8. root@myhost# ls -l
9. drwxrwsr-x 2 root sysadmin 1024 Aug 24 01:18 groupdir
10. -rwsr-x--- 1 root sysadmin 8077 Aug 24 01:19 myprog
11. drwxrwxrwt 2 root root 1024 Aug 24 01:18 spool

This is an interesting example which uses many of the features of chmod(1). Lines 1 through 4 show the long-list of the file and two directories before any changes were made. We see here that groupdir and myprog are members of group sysadmin. Another point of interest is that no one but the owner of these files (root in all these cases) is able to write to the file or directories.

Line 5 shows how to add both group write permission, and setgid access to the groupdir directory. This will enable members of group sysadmin to write files there, and retain the sysadmin group.

Line 6 shows how to add the setuid bit to the myprog binary. This means that any user in the sysadmin group that executes this binary is granted access based on the owner of the file, in this case root, rather than the user who executed it.

Line 7 shows how to add the sticky bit to the spool directory, as well as add write permission for all users. This is a publicy-accessible directory, and writable by all. However, only those who actually own the files can delete them.

Lines 8 through 11 show the directories and file after the modifications have been made.

8.4 Changing File Ownership

This section discusses the methods in which an administrator can change the owner and group to which a file belongs. Use the chown(1) command to change a files owner (can only be done by root), and chgrp to change the group to which a file or directory belongs.

As with any security-related task, you should use caution when changing the ownership of a file or directory. Most times you can add a user to a group without having to change the ownership. You should also re-evaluate the permissions of the file or directory after you have made the change.

To use the chown(1), supply the new username and the files you wish to change:

root@myhost# ls -l myfile
-r--r--r-- 1 fred sysadmin 424 Aug 23 23:10 myfile
root@myhost# chown root myfile
root@myhost# ls -l myfile
-r--r--r-- 1 root sysadmin 424 Aug 23 23:10 myfile

You can also change ownership of files recursively by using the chown -R option. When you use the -R option, the chown command descends through the directory and any subdirectories below that one, changing the ownership.

If a symbolic link is encountered, the group ownership is changed on the file to which the link points.

8.5 Changing Group Ownership

This section is very similiar to the previous section. It discusses the methods in which an administrator can change the groups to which a file belongs. Use the chgrp(1) command to change group ownership. In order for a normal user to change a file's group from one to another, the user must be a member of both groups.

To use the chgrp(1), supply the new group name and the files you wish to change:

root@myhost# ls -l myfile
-r--r--r-- 1 fred sysadmin 424 Aug 23 23:10 myfile
root@myhost# chgrp root myfile
root@myhost# ls -l myfile
-r--r--r-- 1 fred root 424 Aug 23 23:10 myfile

You can also change group ownership of files recursively by using the chgrp -R option. When you use the -R option, the chgrp command descends through the directory and any subdirectories below that one, changing the ownership.

You can also use the chown(1) command to change both the owner and group at the same time. Use a colon between the desired new owner and group. For example:

root@myhost# ls -l myfile
-r--r--r-- 1 fred sysadmin 424 Aug 23 23:10 myfile
root@myhost# chown root:root myfile
root@myhost# ls -l myfile
-r--r--r-- 1 root root 424 Aug 23 23:10 myfile

Notice the permissions do not change simply because you have changed the ownership. Use caution here to be sure you are not inadvertantly giving permission to someone that should not have it.

If a symbolic link is encountered, the group ownership is changed on the file to which the link points.

8.6 Umask Settings

The umask command can be used to determine the default file creation mode on your system. It is the octal complement of the desired file mode. If files are created without any regard to their permissions settings, a user could inadvertently give read or write permission to someone that should not have this permission.

The umask for the creation of new executable files is calculated as follows:

        777 Default Permissions
-022 Subtract umask value, for example
-----
755 Allowed Permissions

So in this example we chose 022 as our umask. This shows us that new executables that are created are given mode 755, which means that the owner can read, write, and execute the binary, while members of the group to which the binary belongs, and all others, can only read and execute it.

The umask for the creation of new text files is calculated as follows:

        666 Default Permissions
-022 Subtract umask mask, for example
-----
644 Allowed Permissions

This example shows us that given the default umask of 666, and subtracting our sample umask value of 022, new text files are created with mode 644, which states that the owner can read and write the file, while members of the group to which the file belongs, and everyone else can only read the new file.

Typically umask settings include 022, 027, and 077, which is the most restrictive. Normally the umask is set in /etc/profile, so it applies to all users on the system. The file creation mask must be set while keeping in mind the purpose of the account. Permissions that are too restrictive may cause users to start sharing accounts or passwords, or otherwise compromise security. For example, you may have a line that looks like this:

        # Set the user's default umask
umask 033

Be sure to make root's umask to at least 022, which will disable write and execute permission for other users, unless explicitly changed using chmod(1).

If you are using Red Hat Linux, and adhered to their user and group ID creation scheme (User Private Groups), it is only necessary to use 002 for a umask with normal users. This is due to the fact that the default configuration is one user per group.

In addition to setting the user's default umask, you should be sure you are aware of the umask value that is set in startup scripts as well. Any files that are created during the boot process may be created with the default umask of 666 if it is not explictly specified.

Additionally, any servers that are started at boot time, such as inetd(8), may inherit the umask at boot time, which in turn will be passed down to the services, and servers, that it controls.

The umask value that the FTP server, spawned by inetd(8) uses, for example, can be easily overlooked, allowing the potential for too lenient permissions on files.

In this specific example, the FTP server has command-line options for controlling umask values. Many do not, however. For this reason, you might consider creating a file that gets run at system boot time, before any others, that simply explictly sets the umask to a known value.

8.7 Monitoring Files with Special Permissions

You should regularly monitor your systems for any unauthorized use of the setuid or setgid permissions to gain superuser privileges.

setuid and setgid files on your system are a potential security risk, and should be monitored closely. Because these programs grant special privileges to the user who is executing them, it is necessary to ensure that insecure programs are not installed. A favorite trick of crackers is to exploit ``setuid root'' programs, then leave a setuid program as a back door to get in the next time, even if the original hole is plugged.

Find all setuid and setgid programs on your system, and keep track of what they are, so you are aware of any changes which could indicate a potential intruder. Use the following command to find all setuid and setgid programs on your system:

        root@myhost#  find / -type f -perm +6000 -ls

You can discriminately remove the setuid or setgid permissions on a suspicious program with chmod(1), then change it back if you absolutely feel it is necessary.

World-writable files, particularly system files, can be a security hole if a cracker gains access to your system and modifies them. Additionally, world-writable directories are dangerous, since they allow a cracker to add or delete files as he wishes. To locate all world-writable files on your system, use the following command:

        root@myhost# find / -perm -2 ! -type l -ls
and be sure you know why those files are writable. In the normal course of operation, several files will be writable, including some from /dev.

Unowned files may also be an indication an intruder has accessed your system. You can locate files on your system that do not have an owner, or belong to a group with the command:

        root@myhost# find / -nouser -o -nogroup

8.8 General Guidelines

The following is a list of general guidelines you should be aware of when configuring the files on your hosts.

  • There should never be a reason for user's home directories to allow setuid and setgid programs to be run from there. Use the nosuid option in /etc/fstab for partitions that are writable by others than root. You may also wish to use nodev and noexec on user's home partitions, as well as /var, which prohibits execution of programs, and creation of character or block devices, which should never be necessary anyway.

  • User files can introduce system vulnerabilities. Some of the things you should watch for include:
    • Installation of Trojan horse programs

    • Protect personal start-up files from modification by others

    • Do not specify personal or shared directories before system-provided directories in executable search paths. (This invites the installation of Trojan horses.)

    • Default protections assigned at file creation should meet system standards

    • Limit write access in a user's personal file space (by appropriate protection of user directories).

  • System files are a crucial component in preventing a security incident. Some of the things to watch for here include:

    • The system configuration files and shared binaries must be protected against Trojan horses

    • Audit trails must be protected against undesired modification

    • Restrict modification privileges for system binaries to systems staff

    • Review the content of system binaries for unexpected changes

    • Restrict modification of system start-up scripts to systems staff

    • Review content of system start-up scripts to ensure that secure defaults are specified and programs executed are not candidates for Trojan horse conversion

    • Protect audit trail log files from unauthorized modification

  • If you are mounting filesystems using a network filesystem such as NFS, be sure to configure /etc/fstab with suitable restrictions. Typically, using nodev, nosuid, and perhaps noexec, are desirable.

  • Set filesystem limits instead of allowing unlimited as is the default. You can control the per-user limits using the resource-limits PAM module and /etc/pam.d/limits.conf. For example, limits for group `users' might look like this:

                    @users     hard  core    5000
    @users hard nproc 50
    @users hard rss 5000

    This says to limit the creation of core files, restrict the number of processes to 50, and restrict memory usage per user to 5 Meg.

  • The /var/log/wtmp and /var/run/utmp files contain the login records for all users on your system. Its integrity must be maintained because it can be used to determine when and from where a user (or potential intruder) has entered your system. These files should also have 644 permissions, without affecting normal system operation.

  • System configuration files (usually in /etc) are usually mode 644 (-rw-r--r--), and owned by root. Depending on your sites security requirements, you might adjust this. Never leave any system files writable by a group or everyone. Some configuration files, including /etc/shadow, should only be readable by root, and directories in /etc should at least not be accessible by others.

  • setuid shell scripts are a serious security risk, and for this reason the kernel will not honor them. Regardless of how secure you think the shell script is, it can be exploited to give the cracker a root shell.
Finally, before changing permissions on any system files, make sure you understand what you are doing. Never change permissions on a file because it seems like the easy way to get things working. Always determine why the file has that permission before changing it. And removing permissions from files is typically a good idea, but it is not always practical. Change permissions slowly, and watch carefully for undesired results.

Intrusion Detection in Linux Systems

How Linux deals with Intrusion Detection


7. Intrusion Detection

Intruders are constantly attempting different mechanisms to attack your system. You must be able to detect these varying attempts, and know what to do when they happen. You should also be able to distinguish the normal operating conditions from an actual attack.

You must be able to determine things like whether or not there really was an intrusion, to what extent the attack occured.

7.1 What is Intrusion Detection?

Intrusion Detection is the method in which a security administrator uses to detect the presence of an unauthorized intruder. An Intrusion Detection System (IDS) are the combination of tools that a security administrator uses to detect the intrusion. Briefly, the available types of intrusion detection include:

  • Network Based Intrusion Detection - These mechanisms typically consist of a black box that sits on the network in promiscious mode, listening for patterns indictive of an intrusion.

  • Host Based Intrusion Detection - These mechanisms typically include auditing for specific events that occur on a specific host. These are not as common, due to the overhead they incur by having to monitor each system event.

  • Log File Monitoring - These mechanisms are typically programs that parse log files after an event has already occured, such as failed login attempts, etc.

  • File Integrity Checking - These mechanisms typically check for trojan horses, or files that have otherwise been modified, indicating an intruder has already been there. The Red Hat Package Manager, RPM, has this capability, as does the well-known Tripwire package.

7.2 General Indications of Intrusion

Being capable of detecting an intrusion is as important as being able to stop it once it happens. It is important that you are able to detect the subtle signs left by an intruder during his attack of your system.

Suspicious signs of intrusion include at least the following:

User Indications

  • Failed log-in attempts
  • Log-ins to accounts that have not been used for an extended period of time
  • Log-ins during hours other than non-working hours
  • The presence of new user accounts that were not created by the system administrator
  • su entries or logins from strange places, as well as repeated failed attempts

System Indications

  • Modifications to system software and configuration files
  • Gaps in system accounting that indicate that no activity has occurred for a long period of time
  • Unusually slow system performance
  • System crashes or reboots
  • Short or incomplete logs
  • Logs containing strange timestamps
  • Logs with incorrect permissions or ownership
  • Missing logs
  • Abnormal system performance
  • Unfamiliar processes
  • Unusual graphic displays or text messages.

File System Indications

  • The presence of new, unfamiliar files or programs
  • Changes in file permissions
  • Unexplained changes in file size. Be sure to analyize all your system files, including those in your $HOME/ directory such as $HOME/.bashrc for modified $PATH entries, as well as changes in system configuration files in /etc
  • Rogue suid and sgid files on the system that do not correspond to your master list of suid and sgid files
  • Unfamiliar file names in directories
  • Missing files

Network Indications

  • Repeated probes of the available services on your machines
  • Connections from unusual locations
  • Repeated login attempts from remote hosts
  • Arbitrary log data in log files, indicating attempt at creating either Denial of Service, or crash service

7.3 General Methods for Detecting Intrusions

In order to determine if an intruder has violated your system, you must be familiar with the normal system administration tools, and be able to use them to find the ``footprint'' a cracker may have left behind. This procedure can be relatively easy, or practically impossible, depending on how much preparation you have done, as well as the stage you've detected the intruder, and how skilled the intruder is.

There are pointers throughout this document that list the various tools available. Some of the tools and methods you should become familiar with include:

  • Log file analysis. Be sure to see the User Security section for information on syslog(8) which is responsible for logging many system events that are helpful in tracking connections to your system, as well as local system events.

  • Become familiar with the last(1), lastcomm(1), and netstat(8) commands. These are available to show valuable information about the users, commands, and connections on your system. More information on these commands are available in the User Security section.

  • Look for signs of physical intrusion.

  • Ensure that the software you are using to search for the intruder hasn't itself been compromised. Do not place all your trust in the tools you are using, and the output they produce. Consider placing a set of secure binaries on external media that can be used later, with confidence. See the http://www.txdirect.net/users/mdfranz/trinux.html package for a starting point.

  • Follow the guidelines provided by CERT in this document ftp://info.cert.org/pub/tech_tips/UNIX_configuration_guidelines

  • Check other local systems that may have been used to attack at yours

  • Check for systems at remote sites that may be involved or affected

  • Investigate unauthorized hardware attached to the network

  • Observe your systems for anything unusual, and certainly investigate anything you find

  • Notify your incident response team if you find something that could have been performed by an unauthorized user

  • Use the network monitoring tools. There are also several nifty network monitoring tools there that are also very helpful. It is important to keep aware of the status of your network, so you know when to be alerted to a specific event. See the Network Monitoring section for more information.

7.4 Intrusion Detection Tools

There are many intrusion detection tools available for Linux, and many new tools are constantly becomming available. While the majority of the tools are host-based intrusion detection tools, there are a number of network-based tools as well.

Host Based Detection Tools

  • Tripwire
  • Make use of the available tools. There are several tools available to detect when someone is portscanning your network. Start with http://www.psionic.com/abacus/abacus_sentry.html which is the Sentry intrusion detection tool.

There are also several intrusion detection tools available at http://www.eng.auburn.edu/users/doug/second.html including a tool called klaxton which basically sets a trap for an intruder, then notifies you when some is ``doorknob rattling''.

7.5 Integrity Checking

A very good way to determine if you have an unwanted visitor is to check your local files for possible trojan horses, missing files, files that are larger or smaller than they are supposed to be, etc.

Fortunately, there are several tools that can verify the file integrity. Many Linux distributions use RPM for their package management, which inherently has integrity checking. Also available is the well-known program called tripwire.

7.6 Using tripwire

Tripwire runs a number of checksums on all your important binaries and config files and compares them against a database of former, known-good values as a reference. Thus, any changes in the files will be flagged.

It's a good idea to install tripwire onto a floppy, and then physically set the write protect on the floppy. This way intruders can't tamper with tripwire itself or change the database. Once you have tripwire setup, it's a good idea to run it as part of your normal security administration duties to see if anything has changed.

You can even add a crontab entry to run tripwire from your floppy every night and mail you the results in the morning. Something like:

                # set mailto
MAILTO=kevin
# run tripwire
15 05 * * * root /usr/local/adm/tcheck/tripwire
will mail you a report each morning at 5:15am.

Tripwire can be a godsend to detecting intruders before you would otherwise notice them. Since a lot of files change on the average system, you have to be careful what is cracker activity and what is your own doing, which is a solid reason to keep track of the status of the binaries on your system.

A company called Visual Computing Corporation now apparently has been given exclusive rights to continue development of tripwire, originally developed at Purdue University. It looks to be so-far-so-good, as there is still a working version for Linux. You can find more information from them at http://www.visualcomputing.com

7.7 Using The Red Hat Package Mangaer

The Red Hat Package Manager (RPM) program includes the ability to verify all packages that it has installed on the system.

RPM has facilities for verifying that a package is not corrupt or has components missing. A program added or removed by a cracker will not match the original and RPM will generally report a verification failure.

Now, when your system is compromised, you can use the command:

                        root# rpm -Va
to verify each file on the system. See the RPM man page, as there are a few other options that can be included to make it less verbose. Keep in mind you must also be sure your RPM binary has not been compromised. RPM can also be combined with PGP to check a package's signature. Typical output might look like the following:

                          ..5....T /bin/login
should sound alarm bells. RPM produces the following useful output fields:

  • S - file size changed
  • M - file mode changed
  • 5 - MD5 checksum failed
  • U - file owner changed
  • G - group changed

This means that every time a new RPM is added to the system, the RPM database will need to be re-archived. You will have to decide the advantages versus drawbacks. Also, keep in mind that it won't verify programs that RPM did not install.

Specifically, the files /var/lib/rpm/fileindex.rpm and /var/lib/rpm/packages.rpm most likely won't fit on a single floppy. Compressed, each should fit on a separate floppy. Consider storing this (as well as the actual /bin/rpm executable!!) on a Zip cartrige.

7.8 File System Guidelines

Intruders often either modify, delete, or replace existing files in order to either cover their tracks, assist them in gaining access, or to gather further information.

Ensuring the integrity of the files and programs on your system is vital in intrusion detection. Several means can be used to determine if files have been tampered with on your system:

  • Look for suspicious files on your system, or even system files that may have been tampered with, or missing. You can find the list of the most recently modified files with the following command:
                        user@host# /usr/bin/find / -ctime -1 -print
    Read the File System Security section for tips on scanning your filesystem for changed files, as well as setuid and sgid files.

  • Verify the integrity of the files. If you are prepared, you can use your Red Hat RPM database, or Tripwire database stored on external media at this time to verify the integrity of the most important files on your system.

7.9 Physical Intrusion Detection

Intruders may attempt to breach your network's by physical infitration as well as via the network. Keep in mind that one system can be used to penetrate many others, so securing one machine is as important as securing another.

The first thing to always note is when your machine was rebooted. Since Linux is a robust and stable OS, the only times your machine should reboot is when YOU take it down for OS upgrades, hardware swapping, or the like. You should always investigate machine reboots.

Check for signs of tampering on the case and computer area. Although many intruders clean traces of their presence out of logs, it's a good idea to check through them all and note any discrepancy.

7.10 Packet Sniffers

One of the more common ways intruders gain access to multiple systems on your network is by employing a packet sniffer on a already compromised host. This software-based ``sniffer'' just listens on the Ethernet port for things like ``password'' and ``login'' and ``su'' in the packet stream and then logs the traffic after that. This way, attackers gain passwords for systems they are not even attempting to break into. Clear text passwords are very vulnerable to this attack.

An attacker doesn't even need to compromise a system to do this, they could also bring a laptop or PC into your building and tap into your net.

Using SSH, or other encrypted password methods, thwarts this attack. Things like APOP for POP email accounts also prevents this attack. (Normal POP logins are very vulnerable to this, as is anything that sends clear text passwords over the wire.)

If you are using syslog to send your data to a central log server, consider that the data is sent in clear text, and much information can be gathered from this data. Consider using a secure implementation of syslog, which encrypts and compresses the data before it is sent. See the Using Syslog section for more information on configuring syslogd(8) securely.