Red Hat Linux 7 Unleashed

Red Hat Linux 7 Unleashed

By William Ball

Network Security Tools

There are several tools that help you secure your networks. First of all, you must have a firewall to separate your internal network from the Internet and to prevent hackers from getting in. Then there is the problem of getting into your network from the outside, and from your network to the outside world, without leaving a wide-open door for hackers.

You must remember that the most important factor in security is usually the human one. You might have the best firewall in the world, perfectly configured, and an employee might simply copy confidential information to a floppy disk and hand it to a competitor. Security starts with people and with a good security policy. This particular subject cannot be discussed in depth here, however. If you want to learn more (and you should!), an excellent reference is Maximum Security, Second Edition: A Hacker's Guide to Protecting Your Internet Site and Network, (ISBN 0-672-31341-3, Sams Publishing).

Firewalls

A firewall is a computer that stands between a trusted network (such as your internal network) and an untrusted network (such as the Internet), and controls what traffic passes between them. It is an essential piece of the information security puzzle.

There are two general types of firewalls (which may be combined): application-level firewalls (known as proxies), and packet-filtering firewalls. A packet-filtering firewall simply allows or disallows packets depending on their content. Most packet-filtering firewalls determine what packets to allow or disallow based on the source or destination addresses, source or destination port, and whether the packet is part of an ongoing conversation.

An application-level firewall or proxy acts as an intermediary between client and server programs. Instead of connecting directly to the server, a client application connects to the proxy and asks it for the information. The proxy opens a connection to the server, sends the request, and continues to pass information back and forth between server and client (see Figure 20.9).

20fig09.gif

Figure 20.9 Packet-filtering versus application-level firewalls.

Both types of firewalls have advantages and disadvantages, and many sites implement both. A proxy-based firewall is regarded as being more secure than a packet-filtering firewall, because it does not have complete knowledge of the protocol used by the application.

Another advantage of proxies is that sometimes they may be used to reduce bandwidth usage. For example, an organization may implement a proxy on its firewall that stores the Web pages requested by users. If another user requests the same page again, the proxy can grab it from its local storage and send the page to the user without having to connect to the origin server again. If you multiply this by tens or hundreds of users, you can appreciate the bandwidth savings.

On the other hand, an application-level firewall must be built for each protocol. Thus, there are HTTP proxies, FTP proxies, Telnet proxies, SMTP proxies, and so on. This brings up the problem of unsupported applications--applications whose protocols don't have a proxy yet. There are generic proxies available, but applications must be modified and recompiled to use them. Since they work on single packets, packet filters are transparent to applications.

A packet-filtering firewall can use additional authentication measures, aside from using just the IP addresses. And a packet-filtering firewall may also do what is known as network-address translation or masquerading. This means that the firewall converts the source addresses on outgoing packets so the other host thinks it's connecting to the firewall itself, and to the destination addresses on incoming packets so they go to the host that requested the connection initially. This has several advantages. For example, a whole network may connect to the Internet using a single IP address. Also, because internal addresses aren't visible to the outside, hosts on the internal network are more secure against attacks from the outside. The downside to this is that any hosts that provide services to the outside must be outside the firewall; otherwise, the firewall must be specifically configured to pass some packets straight to a particular host.

Linux Firewalling Concepts

The Linux kernel itself contains support for packet filtering and masquerading. This support is provided by the package called IP chains. Installing and configuring IP chains is highly recommended for reasons of security. There is always the danger of some unscrupulous individual breaking into your computer from the Internet or even from within your corporate network. If you take the time to install and configure IP chains properly, you can minimize the danger of this happening. It is widely argued that there is no such thing as a totally secure computer system or network. This may or may not be true. There are merits to each side of the case. Security experts will tell you, however, that the more protection you provide for your system, the more you reduce the chances of your system falling prey to crackers. Providing firewall protection for your system will significantly reduce the likelihood of your system being violated. It's like installing an alarm system on your car. This will not keep your car from being stolen by an individual who is a professional car thief and who has decided he is going to steal your car. What it will do is make the other unprotected cars in the parking lot much more attractive to the thief because they are unprotected and thus much easier to steal. There are also several packages available for proxy-based firewalls, such as the Squid HTTP/FTP proxy cache and the SOCKS proxy.

To determine whether your kernel supports IP chains, look for the file /proc/net/ip_fwchains. If the file exists, your current kernel has support for IP chains. If the file doesn't exist, you need to enable the kernel firewall. To do this, you must configure the kernel and enable Network Firewalls and IP: Firewalling. You might also want to enable IP: Always Defragment, IP: Masquerading, and ICMP: Masquerading if you're doing masquerading. After that, recompile and install the kernel and reboot.

Starting with version 2.2 of the Linux kernel, the packet filter is based on the concept of chains, which are configured using the /usr/sbin/ipchains utility. If your system doesn't contain this utility, you have to install the ipchains-1.3.9-17.rpm from the CD-ROMs.

The ipchains tool inserts and deletes rules from the kernel's packet filtering section. Every rule in the kernel's packet filter belongs to a group of rules known as chains. Initially, the kernel contains three default chains:

When a packet enters a chain, it is tested to determine if it matches each of the rules on the chain. If it does, it is passed to the target of that rule. If it reaches the end of a chain, it is passed to the chain's default target.

A target specifies what to do with a packet that matches a particular rule or, in the case of the default targets, that reaches the end of a chain. There are six system targets; they are presented in Table 20.6.

Table 20.6. ipchains System Targets

Name Function
ACCEPT Lets the package through.
DENY Drops the package silently.
REJECT Drops the package, notifying the sender.
MASQ Valid only in the forward chain or chains called from it. Masquerades the package.
REDIRECT Valid only in the input chain or chains called from it. Sends the package to a port on the firewall host itself, regardless of its real destination. May be followed by a port specification to redirect the package to a different port regardless of its destination port.
RETURN Transfers immediately to the end of the current chain; the package will be handled according to the chain's default target.

A target may also be another chain, including a user-defined chain. You may create your own chains at any time, and attach them to any of the predefined chains. The default target of a user-defined chain is always the rule following the one in which the chain is called, so a user-defined chain can be used as a sort of subroutine; you may reuse its rules in several chains. This is useful to reduce the total number of rules and to better document what is happening, since you may name chains after what they do. For example, if a firewall has different rules for two departments (call them the bosses and the masses), you might define different chains called bosses and masses, and then simply apply each chain depending on where the packet is coming from.

Building a Firewall with ipchains

Consider the network shown in Figure 20.10. There is an internal network using private addresses connected to the public Internet. You want to allow all hosts in the internal network to access the Internet, while providing protection from external hackers. No one needs to access the internal hosts from the outside (thus, this kind of firewall is known as a one-way firewall).

20fig10.gif

Figure 20.10 Network setup where all hosts in the internal network have access to the Internet while providing protection from external crackers.

Listing 20.2 shows a shell script that sets up a basic one-way packet-filtering and masquerading firewall using ipchains.

Example 20.2. A Basic Firewall Using ipchains

#!/bin/sh -x
# To enable logging if necessary
#LOG=-l

# Constants
ANYWHERE=0.0.0.0/0
EXT_IF=eth0
INT_IF=eth1

# Networks
INTERNAL_NET=10.0.1.0/24
EXTERNAL_ADDR=205.142.24.1/32

# Disable packet forwarding while we set up the firewall
echo 0 > /proc/sys/net/ipv4/ip_forward

# Flush all rules
/sbin/ipchains -F input
/sbin/ipchains -F output
/sbin/ipchains -F forward

# Deny all packets by default - this is a mostly-closed firewall
/sbin/ipchains -P input DENY
/sbin/ipchains -P output DENY
/sbin/ipchains -P forward DENY

# Accept anything to/from localhost
/sbin/ipchains -A input -j ACCEPT -p all -s localhost -d localhost -i lo $LOG
/sbin/ipchains -A output -j ACCEPT -p all -s localhost -d localhost -i lo $LOG

# Spoofing protection - deny anything coming from the outside with an internal
# address
/sbin/ipchains -A input -j RETURN -p all -s $INTERNAL_NET -d $ANYWHERE –I $EXT_IF $LOG

# Accept TCP packets belonging to already-established connections
/sbin/ipchains -A input -j ACCEPT -p tcp -s $ANYWHERE -d $ME -i $EXT_IF \! -y $LOG

# Accept and masquerade all packets from the inside going anywhere
/sbin/ipchains -A input -j ACCEPT -p all -s $INTERNAL_NET -d $ANYWHERE –I $INT_IF $LOG

/sbin/ipchains -A forward -j MASQ -p all -s $INTERNAL_NET -d $ANYWHERE –I $INT_IF $LOG

# Accept all TCP packets going to the outside net
/sbin/ipchains -A output -j ACCEPT -p all -s $ME -d $ANYWHERE -i $EXT_IF $LOG

# Accept type 3 ICMP queries (Destination Unreachable)
/sbin/ipchains -A input -j ACCEPT -p icmp -s $ANYWHERE -d $ME -i $EXT_IF --icmp-type destination-unreachable $LOG
/sbin/ipchains -A output -j ACCEPT -p icmp -s $ME -d $ANYWHERE -i $EXT_IF --icmp-type destination-unreachable $LOG

# Catch-all rules to provide logging
/sbin/ipchains -A input -j DENY -l
/sbin/ipchains -A output -j DENY -l
/sbin/ipchains -A forward -j DENY -l

# Enable packet forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

First, you should define a few shell variables to help keep your script readable and manageable. Next, for safety, disable packet forwarding in the kernel now while building the firewall rules. This is important because the first step in actually building the firewall is flushing the system chains, so the system might be left in an insecure state.

There are two broad ways of thinking about firewall policies: mostly-open and mostly-closed. In a mostly-open firewall, your system lets everything through except the packets you specify. A mostly-closed firewall does the reverse, denying or rejecting everything except that which you specifically allow. This second kind of firewall is usually regarded as more secure, because you know exactly what is going through and won't be subject to future attacks based on now-unused protocols. As you can see in Listing 20.2, to build a mostly-closed firewall you first set the default target of all chains to DENY or REJECT and then add rules to ACCEPT those packets you want to let through. A mostly-open firewall, obviously, is just the opposite: You set the default target to ACCEPT and then add rules to DENY or REJECT those packets you don't want to let through.

You should now add rules for each of the packets you want to let through. Rules are added by executing the ipchains program with parameters that specify the packet characteristics and the action to take. Tables 20.7 and 20.8, respectively, show the commands ipchains will take and its most common options.

Table 20.7. ipchains Commands

Command Action
-A chain Adds rule to chain.
-D chain [ rulenum ] Deletes rule number rulenum from chain. If rulenum is omitted, the default is the first rule (number 1).
-I chain [ rulenum ] Inserts rule into chain before rule number rulenum.
-R chain [ rulenum ] Replaces rule number rulenum in chain.
-F chain Flushes chain. Equivalent to using -D on all rules one by one.
-L chain Lists the rules in chain.
-N chain Creates new user-defined chain.
-X chain Deletes user-defined chain.
-P chain target Sets default target for chain to target.

Table 20.8. Most Common ipchains Options

Option Specifies
-s [!] address [/ mask ] [!] [ port [: port ]] Source address and port of the packet.
-d [!] address [/ mask ] [!] [ port [: port ]] Destination address and port of the packet.
-i [!] interface Interface the packet is arriving on (in the input chain) or leaving on (in the output and forward chains).
-p [!] protocol Packet protocol. It may be any protocol specified in the /etc/protocols file.
-j target [ port ] Target to send the packet to.
[!] -y Packet is a SYN packet; only for rules that specify -p tcp.
--icmp-type type ICMP type is type ; only for rules that specify -p icmp.
-l Log the packet to syslog.-n or --numeric. Used with the -L option. Displays numeric host and port addresses instead of names.

Some of these options allow the use of the ! (short for not) sign. The not sign can be used to negate or reverse the condition. For example, specifying -p ! icmp in a rule will match packets whose protocol is not ICMP to the conditions of this rule.

The source and destination addresses can be specified in several ways. To specify a particular host, you may use its IP address or its hostname. To specify a network, you can either use the CIDR notation, or its normal expanded dotted-quad format. Thus, 1.1.1.0/24 is equivalent to 1.1.1.0/255.255.255.0. Source and destination port numbers can be specified numerically or by service name (mapped from /etc/services). You may also specify a range of ports by using a colon (:) to separate the beginning and ending ports.

The -y option is used when you want to allow TCP connections in one direction only. When building a firewall, for example, you may want to allow your internal hosts to connect to the outside without letting outside agents connect to the internal hosts. Because a connection needs packets going both ways, blocking packets coming from the outside is a naive approach.

The solution is to block just those packets used to initiate a connection. These packets are called SYN packets because they have the SYN flag set in their headers and the FIN and ACK flags cleared. (The flags are specific bits set in the packet's header.) If you block any packets with the SYN bit set, your hosts can talk to hosts on the outside without allowing the outside hosts to initiate the connections to your hosts.

The Internet Control Message Protocol (ICMP) is used for control messages, such as host not found or ping responses. It is usually most secure to disable most ICMP messages. However, some message types are needed by various utilities or other parts of the system. The --icmp-type option matches those packets with a specific ICMP message type. For example, ICMP messages such as destination unreachable are used extensively by TCP and UDP. You might also want to allow your internal users to use other utilities such as ping or traceroute. Table 20.9 shows the most common ICMP message types.

Table 20.9. The Most Common ICMP Message Types

Number Name Required By
     
0 echo-reply ping
3 destination-unreachable Any TCP/UDP traffic
5 redirect Routing if not running routing daemon
8 echo-request ping
11 time-exceeded traceroute

You can find more detailed information on ipchains and its options in the /usr/doc/ipchains-1.3.9/HOWTO.txt file (make sure you installed the HOWTOs).

Proxies

As mentioned, there are two kinds of firewalls: packet-filtering and proxy-based. A basic packet-filtering firewall may be complemented with a proxy to enhance its security and, in some cases, cache data to reduce network bandwidth usage.

The most common kind of proxy on the Internet today is the Web-caching proxy. Linux includes a Web-caching proxy called Squid. Run the rpm -q squid command to see whether it is installed. If the package isn't installed, you must install the squid-2.2. STABLE1-1.i386.rpm file included on the CD-ROMs.

To configure Squid, go to the /etc/squid directory and copy the squid.conf.default file to squid.conf. Edit squid.conf to suit your site. The file is extensively commented, so most of its options are self-documenting. They also typically have sensible defaults that you can leave unmodified unless you want to tune the cache. Table 20.10 shows the options you should modify before starting Squid.

Table 20.10. Options You Should Modify in /etc/squid/squid.conf

Option Meaning
cache_dir dirname mbytes level1 level2 The cache is stored in dirname. It occupies at most mbytes megabytes of disk space. dirname contains level1 first-level directories, each of which contain level2 second-level directories. The default values are, respectively, 100, 16, and 256. You should change only the first value to reflect the amount of disk space you want to use for the cache; the second and third values are used for tuning.
pid_filename filename Create filename to store the Squid process ID, which is used by the /etc/rc.d/init.d/squid script to kill the process when called with the stop parameter. You should uncomment this line and leave the value unchanged.
logfile_rotate nfiles When rotating logs, keep nfiles archived copies. Although the Squid installation will create a /etc/logrotate.d/squid file to handle log rotations, the number of archived copies is modified here.
ftp_user user@domain.name Some FTP sites require that you pass a valid email address as a password. You should modify this parameter so that it contains a valid user ID (usually the site administrator).
cache_mgr user@domain.name Email address of the site administrator. This person is emailed if a problem arises with the cache.
cache_effective_user username Squid is usually started from /etc/rc.d/ init.d/squid, which is run as root at startup. It is unsafe to run Squid as root, so you must create a new user in /etc/passwd and add its username and group name to the squid.conf file. Squid will set its effective user and group IDs to the ones configured here.
cache_effective_group groupname See cache effective user
err_html_text html_text This should be modified to contain HTML code including the cache administrator's email address. It is added to the end of all error pages presented by Squid to the users.

Once you have configured Squid, you may start it by running /etc/rc.d/init.d/squid start. The first time Squid starts, it will take a long time to create its cache directory hierarchy. Be patient. Squid will log its errors to the /var/log/squid/squid.out, so you can do a tail -f on this file to check whether there are any startup errors.

Secure Remote Access—SSH, the Secure SHell

You have just completely secured your site. You have an airtight firewall in place and have set up your proxy. You have a good security policy and your users have been educated on it. You can sit at your console basking in the feeling of a job well done and use Telnet to log in to one of your servers to start a backup.

What if a few days later you discover your server has been compromised? Someone logged in as root and played amateur sysadmin on it. What could have happened?

This scenario is more common than you might think, and it has bitten many a sysadmin. What happened here was that someone on the internal network was using a sniffer, a program that captures all traffic on the LAN. It saw your complete Telnet session, including the server's root password, and reported it to whoever was running the sniffer. That user, armed with the password, went into your server.

The problem with most Internet protocols is that the Internet was initially created without security being a main goal. Most companies today use these same Internet protocols on their internal networks. Even if your network isn't visible from the Internet, don't undervalue the importance of good networkwide security. It has been reported that over 70% of system compromises originate within the firewall, by disgruntled employees, by curious employees who want to see how systems work, or by competitors' spies.

What is a sysadmin to do? Use only the console? What about remote sites that are only connected via the Internet?

Enter the Secure SHell, also known as SSH. SSH is a suite of programs that allow you to log on to remote servers and transfer files in a secure manner. It is meant to be a replacement for rlogin, rsh, telnet, and rcp, which are insecure because they don't encrypt the data they transfer as it moves from one host to another. SSH, on the other hand, scrambles the data that goes through the network so it is indecipherable to someone using a sniffer. A full discussion of security and encryption technologies is beyond the scope of this book; however, an excellent reference is Internet Security Professional Reference, Second Edition (New Riders Publishing, ISBN 1-56205-760-X).

With SSH, each host and user has a private key and a public key. The public key is stored on the server, whereas the private key is kept on the client. Data encrypted with one key can only be decrypted with the other, and vice versa. This means that SSH can be used both for secure communications and for strong authentication, where you need to be sure that the host on the other side of the connection is actually who it claims to be.

Because SSH contains encryption technology, it is illegal to export it from the U.S. ssh-server must be installed on the servers (the hosts you are logging on to), ssh-clients on the clients (the hosts you are logging on from), and ssh on both; ssh-extras can be optionally installed on either or both. It is often best to install all packages on all hosts.

The ssh-server package contains default /etc/ssh/sshd_config and /etc/ssh/ssh_config files that work well for most purposes. It also contains an /etc/rc.d/init.d/sshd script for starting the sshd daemon when you boot the host. To start the sshd daemon manually, run /etc/rc.d/init.d/sshd start. If you want to start it automatically when the server boots, create an appropriate softlink in the /etc/rc.d/rc?.d directory that corresponds to your server's initdefault runlevel.

The ssh and ssh-clients packages contain several programs. The most useful are ssh and scp. ssh allows you to log on to a remote host, execute remote programs, and redirect ports from the local host to the remote host and vice versa. scp, which allows you to copy files securely from one host to another, is a replacement for the rcp program.

The ssh Command

The ssh command is used to log on to a remote server and execute a command. It has the following syntax:

ssh options host options command

ssh also handles X connection forwarding. Whenever you log on to a remote host using ssh from a host that is running X Windows, sshd creates a dummy X server and sets the DISPLAY variable to point to it. All X traffic going to this dummy server is actually forwarded to the X server on your local host. X authentication is automatically taken care of via xauth. That way, the X traffic is also encrypted and secure. You don't have to do anything to make this happen, just log on to the remote server from an X session.

There are many options to the ssh command that can be included either before or after the hostname. The most common options to ssh are listed in Table 20.11.

Table 20.11. Most Common ssh Options

Option Meaning
-f Send process to background after authentication. Useful when you need to enter a password.
-l user Log in as user to the remote server.
-o ' option' Set option in the same format as the configuration file. Useful for some options that don't have command-line switch equivalents.
-v Activate verbose mode. Useful for debugging connections.
-C Compress. All data in the connection will be compressed. Useful especially over modem lines. The compression algorithm used is the same one used by gzip.
-L port:host:hostport Forward TCP port port to hostport on remote host host. What this does is open a local server socket on port and a socket on the remote host that connects to port hostport on host. All connections to port on the localhost will be forwarded to port hostport on host.
-R port:host:hostport The reverse of -L. Forward TCP port port on the remote host to port hostport on host.

Port Forwarding

The -R and -L options deserve special mention. They are useful especially in cases where you need to make a secure "tunnel" through an insecure network (such as the Internet). Consider a case where you have a Web server in California and a database server in Florida. You want the Web server to access the database, but for security purposes you want the communication to be encrypted. Suppose the database listens by default to port 3306. You might run the following shell script on the Web server:

#!/bin/sh
while /bin/true
do
  ssh dbserver -L 3306:localhost:3306 sleep 87600
done

The while loop is needed because the ssh command (and thus the port forwarding) will run only as long as the command given on the ssh command line specifies. In this case, the sleep 87600 command simply waits for 87,600 seconds (24 hours) before exiting. This command forwards port 3306 of the Web server (where you're running the command) to port 3306 on the localhost of the database server.

If you want to run this script on the database server, you would use the -R option and invert the two port numbers. Since they are the same, the command would be identical except for the option name.

Authentication

This scheme poses a problem, though. The ssh command will ask for the password of the remote user. There are only two ways to automate the password login process:

To use .rhosts authentication, you create a .rhosts file in the home directory of the remote user, just as if you were using the rsh command. The difference here is that the remote host will be authenticated by its public key, instead of just by its IP address. Assuming that the command was run by the admin user and that the Web server host is called webserver, the .rhosts file should contain the following line:

webserver  admin

If you don't like the idea of using a .rhosts file or you are sitting behind a firewall, the only option left is to use private/public keys. What you need to do follows:

  1. Log on to the local server.
  2. Run the /usr/bin/ssh-keygen program to generate the private and the public keys. They are saved under the user's home directory as .ssh/identity and .ssh/identity.pub, respectively. ssh-keygen asks you for a passphrase, which is used to encrypt the keys and has to be keyed in every time you want to log on remotely. Because the purpose of this is precisely to avoid having to use a password, leave the passphrase blank.
  3. Copy the .ssh/identity.pub file to the /tmp directory of the remote server:
    
             cp $HOME/.ssh/identity.pub remoteserver:/tmp.
    
          
  4. Log on to the remote server:
    
             ssh remoteserver.
    
          
  5. Append the /tmp/identity.pub file to the .ssh/authorized_keys file under the remote user's home directory:
    cat /tmp/identity.pub >> .ssh/authorized_keys.
    
  6. Log off the remote server and log back on using ssh. This time ssh shouldn't ask for a password.

The ssh_config and .ssh/config Files

The SSH client programs read their configuration from the /etc/ssh/ssh_config and the $HOME/.ssh/config files. There are many options that can be placed in these files. The most common are shown in Table 20.12.

Table 20.12. ssh_config Options

Option Meaning
Host hostname Introduces a new section. The hostname is matched against the hostname given on the command line. The options that follow apply to this host until the next Host directive. The ? and * characters may be used as wildcards. You may use Host * to set defaults that apply to all hosts.
HostName hostname The connection is made to hostname. This is useful to create aliases for particular connections (such as with different usernames or for port forwarding).
BatchMode { yes|no} When set to yes, ssh never asks for a password. It fails if it can't log in without a password.
Compression { yes|no} When set to yes, ssh compresses all data transferred to this host. The compression algorithm is the same one used by gzip. Equivalent to the -C command-line option.
CompressionLevel { 1-9} Specifies how much to compress the data. A CompressionLevel of 1 provides the least and fastest compression, whereas a level of 9 provides the most and slowest compression. The default value is 6 and is appropriate for most applications.
User username Log in as username. Equivalent to the -l command-line option.
LocalForward port host:hostport Forward local port to remote hostport on host. Equivalent to the -L command-line option.
RemoteForward port host:hostport Forward remote port to local hostport on host. Equivalent to the -R command-line option.

Share ThisShare This

Informit Network