Locking Down Security - Ubuntu Linux Toolbox: 1000+ Commands for Power Users (2013)

Ubuntu Linux Toolbox: 1000+ Commands for Power Users (2013)

Chapter 14

Locking Down Security

IN THIS CHAPTER

· Adding user accounts and changing user settings with useradd

· Changing user accounts with usermod

· Deleting users with userdel

· Adding, changing, and managing passwords with passwd

· Managing groups with groupadd, groupmod, and groupdel

· Seeing who’s logged in with last, lastb, and who

· Configuring firewalls with iptables

· Checking out advanced security with SELinux, tripwire, and APT

Securing your Linux system means first restricting access to the user accounts and services on that system. After that, security means checking that no one has gotten around the defenses you have set up.

Ubuntu, Debian, and other systems based on those Linux distributions are designed to be secure by default. That means that there are no user accounts with blank passwords, and that most network services (web, FTP, and so on) are off by default (even if their software is installed).

Although many of the commands covered in this book can be used to check and improve the security of your Linux system, some basic Linux features are particularly geared toward security. For example, secure user accounts with good password protection, a solid firewall, and consistent logging (and log monitoring) are critical to having a secure Linux system. Commands related to those features, plus some advanced features, such as SELinux and tripwire, are covered in this chapter.

Working with Users and Groups

During most Linux installation procedures, you are asked to assign a password to the root user (for system administration). Then you might be asked to create a username of your choice and assign a password to that as well (for everyday computer use). We encourage you to always log in as a regular user and only su or sudo to the root account when necessary. Once Linux is installed, you can use commands or graphical tools to add more users, modify user accounts, and assign and change passwords.

Ubuntu enhances security by disabling logins as root, by default. Instead, during installation, you set up a user, with a password, who can perform administrative functions. On Ubuntu, use the sudo command to perform individual commands as the root user. The sudo command prompts for the administrative password, typically your password. This way, you avoid most issues of performing some command as root that you did not intend.

Managing Users the GUI Way

For an Ubuntu desktop system with X, you can manage users and groups with the User Manager window (System ⇒ Administration ⇒ Users and Groups).

When managing user accounts for servers, one option is to use web-based GUIs. The most commonly used general-purpose tool is Webmin (www.webmin.com). Make sure you do not run Webmin on its default port (10000) for security reasons. You can also use special-purpose web interfaces. For example, there are many web hosting automation GUIs, such as cPanel (www.cpanel.com), Plesk (www.swsoft.com/plesk), and Ensim (www.ensim.com).

Adding User Accounts

To add new users, you can use the useradd command. The only option that is required to add a new user is the username you are adding. You can see some of the default settings for adding a new user by entering the -D option:

$ useradd -D Show useradd default values

GROUP=100 Set group ID to 100 (users)

HOME=/home Set base home directory to /home

INACTIVE=-1 Password expiration is disabled (-1)

EXPIRE= Don’t set date to disable user account

SHELL=/bin/sh Set the default shell to /bin/bash

SKEL=/etc/skel Copy config files from /etc/skel to $HOME

CREATE_MAIL_SPOOL=no Create a mail spool directory

Ubuntu and other Debian systems override the default group (100) and create a new group for every user. By default, the user ID assigned to the first user created is 1000 and the group ID is also 1000. The group name is the same as the username. The home directory is the username appended to /home. So, for example, if you created the first regular user account on the system as follows:

$ sudo useradd -m willz

The result would be a new user account with a willz username (UID 1001) and willz group name (GID 1001). The -m option tells useradd to create a home directory of /home/willz, and copy a set of configuration files (each beginning with a “.”) to the home directory from /etc/skel. The account would remain active indefinitely (no expiration date). Add a password as follows, and in most cases that’s all you need to do to have a working user account.

$ sudo passwd horatio

Changing password for user horatio

New UNIX password: ********

Retype new UNIX password: ********

passwd: all authentication tokens updated successfully.

Note Remember to use strong, non-dictionary-based passwords.

There are many options you can enter to override the defaults when you create a user. Combine the different options as you choose. Here are some examples:

$ sudo useradd -u 1101 -g 60 -m skolmes Use specific UID and GID

$ sudo useradd -m -d /home/jj jones Create /home/jj home directory

$ sudo useradd -m -G games,man timd Add user to games and man groups

$ sudo useradd -c “Tom G. Lotto” tlot Add full name to comment field

$ sudo useradd -s /bin/sh joeq Assign a new default shell (tcsh)

$ sudo useradd -e 2014-04-01 jerry New account expire April 01, 2014

$ sudo useradd -f 0 jdoe Create a disabled account

$ sudo useradd -s /sbin/nologin billt Keep user from shelling in

$ sudo useradd billyq Prevent creation of home directory

Before you can add a user to a group, that group must exist (see the groupadd command in the “Adding Groups” section later in this chapter). The one exception is that, if no group is indicated, a group is created with the same name of the new user and the user is assigned to it. A user must belong to one initial group that can be overridden with -g and can also belong to supplementary groups, defined with -G.

To list the group(s) that a user belongs to, use the groups command:

$ groups timd List the groups that a user belongs to

timd : timd man games

The -e example, sets an expiration date for a user account that you know to be temporary. Change the default shell to /usr/sbin/nologin when you want a user to be able to access the computer (via FTP, POP3, and so on), but you don’t want to allow access to a regular Linux login shell. Likewise, the last example, with no -m to create a home directory, might allow a user to access a machine but not have a home directory. Note that in all the examples, unless you provide the -m option, the useradd command will not create the home directory for the user.

Changing useradd Defaults

The default values you get when you create a new user account with useradd (default shell, GID, expiration dates, and so on) are set by values in the /etc/login.defs and /etc/default/useradd files. You can edit those files to change defaults or run the useradd command with the -D option to list or selectively change values:

$ useradd -D List default useradd settings

$ sudo useradd -D -b /home2 -s /bin/csh Set default base dir and shell

$ sudo useradd -D -e 2014-01-01 Set all new users to expire in 2014

As noted earlier, files and directories from the /etc/skel directory are copied to the new user’s home directory when the account is created when you pass the -m option. Those files include some bash shell files and a link to an example directory. You can add other files and directories to /etc/skel so that each new user gets them. For example, if you are configuring a web server, you might create public_html and public_ftp directories for users to add web pages and files they want to share.

Modifying User Accounts

After a user account is created, you can change values for that account with the usermod command. Most options are the same ones you would use with useradd. For example:

$ sudo usermod -c “Thomas Lotto” tlot Change user name in comment field

$ sudo usermod -s /bin/sh joeq Change default shell to sh

$ sudo usermod -L swanson Lock the swanson user account

$ sudo usermod -U travis Unlock user account named travis

Note that the last two examples lock and unlock a user account, respectively. Locking a user account does not remove the user’s account from the system or delete any of the user’s files and directories. However, it does keep the user from logging in. Once unlocked, the user's password is also restored, so a new password doesn't have to be assigned if the same user is to resume using the account.

Locking an account can be useful if an employee is leaving the company, but the work in that employee’s files needs to be passed to another person. Under those circumstances, locking the user instead of deleting it prevents the files owned by that user from appearing as belonging to an unassigned UID.

Because a regular user can’t use the useradd or usermod command, there are special commands for changing personal account information. Consider the following examples:

$ chsh -s /bin/sh Change current user’s shell to /bin/sh

$ sudo chsh -s /bin/sh chris Change a user’s shell to /bin/sh

$ sudo chfn \

-h “212-555-1212” \ Change home phone number

-w “212-555-1957” Change office phone number

$ finger chris

Login: chris Name: Chris Negus

Office Phone: 919-555-1957 Home Phone: 919-555-1212

Directory: /home/chris Shell: /bin/bash

On since Sat Mar 9 14:43 (EST) on pts/0 from :0

10 seconds idle

(messages off)

Mail last read Sat Mar 9 16:26 2013 (EST)

No Plan.

The information changed with the previous chfn command (home and office phone numbers) and displayed with finger are stored in the fifth field of the /etc/password file for the selected user. (The /etc/passwd file can only be edited directly by the root user, and should only be edited using the vipw command and with extreme caution.)

On other versions of Linux, you can use the -f option to chfn to change your real or full name. On Ubuntu, the permission to do this is turned off by default. You can change this by editing /etc/login.defs. Look for the following line:

CHFN_RESTRICT rwh

and change this to:

CHFN_RESTRICT frwh

Deleting User Accounts

With the userdel command, you can remove user accounts from the system as well as other files (home directories, mail spool files, and so on) if you choose. Consider the following examples:

$ sudo userdel jimbo Delete user, not user’s home directory

$ sudo userdel -r lily Delete user, home directory, and mail spool

Keep in mind that removing a user's home directory with userdel does not remove other files owned by that user in other locations on the system. Keep in mind the following issues:

· When you do a long listing of files that were owned by a deleted user (ls -l), the former user's UID and GID appear as the owners of the file.

· If you were to add a new user that was assigned to that UID and GID, the new user would become the owner of those files.

You can run the command find / -nouser -ls to find files anywhere on the system that are not owned by any user.

Managing Passwords

Adding or changing a password is usually done quite simply with the passwd command. However, there are additional options available with passwd that let an administrator manage such things as user account locking, password expiration, and warnings to change passwords. In addition to passwd, there are commands such as chage, chfn, and vipw for working with user passwords.

Regular users can change only their own passwords, whereas the root user can change the password for any user. For example:

$ passwd Change regular user’s password

Changing password for user chris.

Changing password for chris.

(current) UNIX password: ********

New UNIX password: *

BAD PASSWORD: it’s WAY too short

New UNIX password: *********

Retype new UNIX password: *********

passwd: password updated successfully

$ sudo passwd joseph Root can change any user password

Changing password for user joseph.

New UNIX password: *

Retype new UNIX password: *

passwd: password updated successfully

In the first example, a regular user (chris) changes his own password. Even while logged in, the user must type the current password before entering a new one. Also, passwd keeps a regular user from setting a password that is too short, based on a dictionary word, doesn’t have enough different characters, or is otherwise easy to guess. In the second example, the root user can change any user password without the old password.

Passwords should be at least eight characters, be a combination of letters and other characters (numbers, punctuation, and so on), and not include real words. Make passwords easy to remember but hard to guess.

A system administrator can use passwd to lock and unlock user accounts. For example:

$ sudo passwd -l carl Lock the user account (carl)

Locking password for user carl.

passwd: Success

$ sudo passwd -u carl Unlock a locked user account (carl)

Unlocking password for user carl.

passwd: Success

$ sudo passwd -u jordan Unlock fails with blank password

Unlocking password for user jordan.

passwd: Warning: unlocked password would be empty.

passwd: Unsafe operation (use -f to force)

Locking a user account with passwd causes an exclamation mark (!) to be placed at the front of the password field in the /etc/shadow file (where user passwords are stored). When a user account is unlocked, the exclamation mark is removed and the user’s previous password is restored.

An administrator can use the passwd command to require users to change passwords regularly, as well as warn users when passwords are about to expire. To use the password expiration feature, the user account needs to have had password expiration enabled. The following examples use passwd to modify password expiration:

$ sudo passwd -n 2 vern Set minimum password life to 2 days

$ sudo passwd -x 300 vern Set maximum password life to 300 days

$ sudo passwd -w 10 vern Warn of password expiration 10 days before

$ sudo passwd -i 14 vern Days after expiration account is disabled

In the first example, the user must wait at least two days (-n 2) before changing to a new password. In the second, the user must change the password within 300 days (-x 300). In the next example, the user is warned 10 days before the password expires (-w 10). In the last example, the user account is disabled 14 days after the password expires (-i 14).

To view password expiration, you can use the chage command as follows:

$ sudo chage -l vern View password expiration info

Last password change : Mar 04, 2013

Password expires : May 31, 2014

Password inactive : Jun 14, 2014

Account expires : never

Minimum number of days between password change : 2

Maximum number of days between password change : 300

Number of days of warning before password expires : 10

As system administrator, you can also use the chage command to manage password expiration. Besides being able to set minimum (-m), maximum (-M), and warning (-W) days for password expiration, chage can also set the day when a user must set a new password or a particular date the account becomes inactive:

$ sudo chage -I 40 frank Make account inactive in 40 days

$ sudo chage -d 5 perry Force user password to expire in 5 days

Instead of five days (-d 5), you can set that option to 0 and cause the user to have to set a new password the next time he or she logs in. For example, the next time the user perry logs in, if -d 0 has been set, perry will be prompted for a new password as follows:

login: perry

Password: ********

You are required to change your password immediately (root enforced)

Changing password for perry.

(current) UNIX password:

New UNIX password: *********

Retype new UNIX password: *********

Adding Groups

Each new user is assigned to one or more groups. You can create groups at any time and add users to those groups. The permissions that each group has to use files and directories in Linux depend on how the group permission bits are set on each item. Assigning users to a group allows you to attach ownership to files, directories, and applications so that those users can work together on a project or have common access to resources.

Commands similar to those for working with users are available for managing your groups. You can add groups (groupadd), change group settings (groupmod), delete groups (groupdel), and add and delete members from those groups (groupmems). Here are some examples for adding new groups with the groupadd command:

$ sudo groupadd marketing Create new group with next GID

$ sudo groupadd -g 1701 sales Create new group with GID of 1701

$ sudo groupadd -o -g 74 mysshd Create group with existing GID

With the groupmod command, you can change the name or group ID of an existing group. Consider the following examples:

$ sudo groupmod -g 491 myadmin Modify myadmin to use GID 491

$ sudo groupmod -n myad myadmin Change name of myadmin group to myad

To remove an existing group, use the groupdel command. Here is an example:

$ sudo groupdel myad Remove existing myad group

Keep in mind that removing a group or user doesn’t remove the files, directories, devices, or other items owned by that group or user. If you do a long listing (ls -l) of a file or directory assigned to a user or group that was deleted, the UID or GID of the deleted user or group is displayed.

Checking on Users

After you have created user accounts, and let those users loose on your computer, there are several different commands you can use to keep track of how they are using your computer. The following commands for checking on user activity on your Linux system are covered in other chapters:

· Use the find command (see Chapter 4) to search the system for files anywhere on the system that are owned by selected users.

· Use the du command (see Chapter 7) to see how much disk space has been used in selected users’ home directories.

· Use commands such as fuser, ps, and top (see Chapter 9) to find out which processes users are running.

Aside from the commands just mentioned, there are commands for checking such things as who is logged into your system and getting general information about the users with accounts on your system. The following are examples of commands for getting information about people logging into your system:

$ last List the most recent successful logins

greek tty3 Tue Mar 5 18:05 still logged in

chris tty1 Mon Mar 4 13:39 still logged in

root pts/4 thompson Tue Mar 5 14:02 still logged in

chris pts/1 :0.0 Mon Mar 4 15:47 still logged in

jim pts/0 10.0.0.50 Sun Mar 3 13:46 - 15:40 (01:53)

james pts/2 Sat Mar 2 11:14 - 13:38 (2+02:24)

$ last -a Makes it easier to read the remote client hostname

$ sudo lastb List the most recent unsuccessful logins

julian ssh:notty ritchie Wed Mar 6 12:28 - 12:28 (00:00)

morris ssh:notty thompson Thu Feb 28 13:08 - 13:08 (00:00)

baboon ssh:notty 10.0.0.50 Thu Feb 8 09:40 - 09:40 (00:00)

james ssh:notty 000db9034dce.cli Fri Jun 22 17:23 - 17:23 (00:00)

$ who -u List who is currently logged in (long form)

greek tty3 2013-08-05 18:05 17:24 18121

jim pts/0 2013-08-06 12:29 . 20959 (server1.example.com)

root pts/3 2013-08-04 18:18 13:46 17982 (server2.example.com)

james pts/2 2013-07-31 23:05 old 4700 (0a0d9b34x.example.com)

chris pts/1 2013-08-04 15:47 old 17502 (:0.0)

$ users List who is currently logged in (short form)

chris james greek jim root

With the last command, you can see when each user logged in (or opened a new shell) and either how long they were logged in or a note that they are “still logged in.” The tty1 and tty3 terminal lines show users working from virtual terminals on the console. The pts lines indicate a person opening a shell from a remote computer (thompson) or local X display (:0.0). We recommend you use the -a option for improved readability. The lastb command shows failed login attempts and where they are from. The who -u and users commands show information on currently logged-in users.

Here are some commands for finding out more about individual users on your system:

$ id Your identity (UID, GID and group for current shell)

uid=1000(chris) gid=1000(chris)

groups=4(adm),20(dialout),24(cdrom),25(floppy),

29(audio),

30(dip),44(video),46(plugdev),104(scanner),112(netdev),

113(lpadmin),

115(powerdev),117(admin),1000(chris)

$ who am i Your identity (user, tty, login date, location)

chris pts/0 Mar 3 21:40 (:0.0)

$ finger -s chris User information (short)

Login Name Tty Idle Login Time Office Office Phone

chris Chris Negus tty1 1d Mar 4 13:39 A-111 555-1212

$ finger -l chris User information (long)

Login: chris Name: Chris Negus

Directory: /home/chris Shell: /bin/bash

Office: A-111, 555-1212 Home Phone: 555-2323

On since Mon Mar 4 13:39 (CDT) on tty1 2 days idle

New mail received Wed Mar 6 13:46 2013 (CDT)

Unread since Mon Mar 4 09:32 2013 (CDT)

No Plan.

In addition to displaying basic information about the user (login, name, home directory, shell, and so on), the finger command will also display any information stored in special files in the user’s home directory. For example, the contents of the user’s ~/.plan and ~/.project files, if those files exist, are displayed at the end of the finger output. With a one-line .project file and multi-line .plan file, output can appear as follows:

$ finger -l chris User information (long, .project and .plan files)

...

Project:

My project is to take over the world.

Plan:

My grand plan is

to take over the world

by installing Linux on every computer

Configuring the Built-In Firewall

A firewall is a critical tool for keeping your computer safe from intruders over the Internet or other network. It can protect your computer by checking every packet of data that comes into, out of, or through your computer’s network interfaces, and then making a decision about what to do with that packet based on the parameters you set.

The firewall facility built into the current Linux kernel is netfilter, although it is more commonly referred to by the name of the command and service that represents it: iptables. When you install Ubuntu, the iptables command is installed and iptables features are built into the kernel. So you are ready to immediately begin creating firewall rules for your sytem.

The iptables facility (www.netfilter.org) is extraordinarily powerful, yet complex to use from the command line. For that reason, many people set up their basic firewall rules using a graphical interface. To get a graphical interface, install the firestarter package (sudo apt-get install firestarter).

Firestarter provides a wizard to configure and set up your firewall. To run Firestarter, type the following from a Terminal window on your desktop:

# sudo firestarter

You can also try add-on packages such as FWBuilder (fwbuilder package) and Shorewall (shorewall package) for graphically configuring firewalls.

Note Before you go much further, read the IpTables HowTo document for Ubuntu, at https://help.ubuntu.com/community/IptablesHowTo. This document provides a lot of useful information for using iptables on Ubuntu, as this usage differs a lot from other versions of Linux such as Fedora.

Understanding iptables Firewalls

The iptables facility works by examining every packet that traverses your Linux system's network interfaces and acting on those packets based on rules you set up. Rules are added to one of the tables associated with iptables. Available tables are filter, nat, and mangle.

The filter table is, by far, the one you will work with the most. Based on attributes you choose (such as the port requested, the host that sent the packet, or network interface receiving the packet) an action is taken. The action may be to allow (ACCEPT), deny (REJECT or DROP), or log and continue (LOG) the request from each packet.

Within each table, each rule is also assigned a particular chain. The filter table has three chains:

· INPUT—For packets coming into the system

· OUTPUT—For packets leaving the system

· FORWARD—For packets being forwarded through the system

Probably most of your packet filter rules will be created for the INPUT chain. The INPUT chain filters packets coming into your system, essentially blocking or allowing access to services on your system. A common practice is to allow access to packets coming from your local system (lo interface), associated with established connections, and requesting one of a handful of services (such as ssh or http). Then the system might drop all other packets destined for the system.

Besides the filter table, you have the nat table which is used to do such things as network address translation and packet forwarding. There is also the mangle table, which can be used to change packet information (such as to appear to come from a different address than it is actually from).

The steps for configuring a firewall are basically the following:

· Create rules that can be injected into the running kernel using the iptables command.

· Save those rules to a file.

· Load those rules before your network interfaces come up.

The iptables examples shown in this section illustrate a good sample set of filter firewall rules you can start with on a system that allows access to a few services on the local system but blocks all other access.

Note The order of the rules is important. Rules are read in order. When a packet matches a rule, it leaves the chain (being accepted, dropped, or rejected). Using -A adds a rule to the end of the chain. With -I # you insert a rule into a particular line number (#) in the chain.

First, flush all the current iptables rules in the kernel:

$ sudo iptables -F

This rule allows any packets coming into the system that are associated with existing connections (for example, to return data from a web page requested from a local browser):

$ sudo iptables -A INPUT -m state \

--state ESTABLISHED,RELATED -j ACCEPT

This allows ICMP requests (such as ping requests):

$ sudo iptables -A INPUT -p icmp -j ACCEPT

This allows any requests from the local system:

$ sudo iptables -A INPUT -i lo -j ACCEPT

This allows outside requests to TCP port 22 (SSH service) to enable such things as remote login and remote copy services (repeat this command with other port numbers to allow access to other services):

$ sudo iptables -A INPUT -m state --state NEW \

-m tcp -p tcp --dport 22 -j ACCEPT

These two rules allow printing service requests (port 631) for both TCP and UDP protocols:

$ sudo iptables -A INPUT -m state --state NEW \

-m udp -p udp --dport 631 -j ACCEPT

$ sudo iptables -A INPUT -m state --state NEW

-m tcp -p tcp --dport 631 -j ACCEPT

This rule drops any packet that is not already explicitly accepted:

$ sudo iptables -A INPUT -j REJECT \

--reject-with icmp-host-prohibited

This command saves the current rules from the kernel to a file:

$ sudo iptables-save > /root/myiptables

This command restores rules from a file to the kernel:

$ sudo iptables-restore /root/myiptables

You can add this command to a startup script, as described in the section "Saving and Reloading Firewall Rules," to load the iptables firewall rules before network interfaces are started.

Listing iptables Rules

To check how the firewall is set up on your system, use the -L option of iptables. Here is how to list the current rules set on your Linux system’s firewall (for the default filter table):

$ sudo iptables -L

Chain INPUT (policy ACCEPT)

target prot opt source destination

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT icmp -- anywhere anywhere

ACCEPT all -- anywhere anywhere

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh

ACCEPT udp -- anywhere anywhere state NEW udp dpt:ipp

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ipp

REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)

target prot opt source destination

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

Add a -v option to see a more verbose output of rules. Notice here that -v shows that the "all anywhere anywhere" rule actually accepts all packets from the local system (lo). You can also see the port numbers instead of names and the number of packets and bytes that have matched each rule:

$ sudo iptables -vnL Verbose, numeric services, packet counts

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)

pkts bytes target prot opt in out source destination

85 6514 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0

state RELATED,ESTABLISHED

0 0 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0

0 0 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0

0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0

state NEW tcp dpt:22

24 5144 ACCEPT udp -- * * 0.0.0.0/0 0.0.0.0/0

state NEW udp dpt:631

0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0

state NEW tcp dpt:631

The example illustrates the filter iptables firewall table. It shows that for packets coming into the computer’s network interfaces, packets for Internet Printing Protocol (ipp) on udp and tcp protocols are allowed. Likewise, tcp packets matching the Secure Shell (ssh) are accepted. Packets are also accepted if they are associated with an established connection. Next you can look at the nat table:

$ sudo iptables -t nat -L Display current iptables nat table

Chain PREROUTING (policy ACCEPT)

target prot opt source destination

DNAT tcp -- 0.0.0.0/0 11.22.33.44 tcp dpt:8785 to:10.0.0.155:22

DROP tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:135

DROP udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:135

Chain POSTROUTING (policy ACCEPT)

target prot opt source destination

MASQUERADE all -- 0.0.0.0/0 0.0.0.0/0

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

The nat table just shown applies to a feature called Network Address Translation. The nat table allows you to do such things as use private IP addresses behind your firewall. As the packets from internal LAN machines exit the firewall, the source private address is rewritten with the IP address of the firewall’s external interface. The firewall keeps track of these sessions in order to allow the return traffic through to the LAN machines. All this is configured with the MASQUERADE line on the POSTROUTING chain.

In the preceding example, the DNAT line in the PREROUTING chain causes any requests to port 8785, at IP address 11.22.33.44, to be forwarded to the internal LAN IP address 10.0.0.155 on port 22 (a trick to let someone ssh into a computer behind the firewall through a non-standard port).

The following are other examples for listing information about your firewall.

$ sudo iptables -L --line-numbers Show line number for each rule

$ sudo iptables -nvL --line-numbers Add numeric (-n) and verbose (-v)

You can stop or flush all iptables rules on an Ubuntu system as follows:

$ sudo iptables -F Flush all iptables rules

This command removes all the rules, so be careful when running it. You’ll want to immediately add new rules.

Setting Other Firewall Rules

Here are some more examples of how the iptables command can be used to change rules on an active firewall:

$ sudo iptables -A INPUT -p TCP \ Add filter input rule for TCP

-i eth0 \ on the first Ethernet interface

--destination-port 25 \ destined for mail service port (25)

-j ACCEPT accept the packets when encountered

$ sudo iptables -t nat \ Add nat rule

-A POSTROUTING \ POSTROUTING chain

-o eth1 \ packets received on eth1 interface

-j SNAT \ jump to network address translation

--to-source 11.22.33.1 using outgoing address 11.22.33.1

Of the two examples shown, the first example creates a rule that allows new incoming requests to your system on port 25. This is presumably because you have configured your computer as a mail server (with sendmail, postfix, or other SMTP service). The second example creates a nat table rule to allow the firewall to do Source Network Address Translation (SNAT). The SNAT feature lets you have private IP addresses behind your firewall that can communicate to the public Internet using the firewall’s external IP address.

To use SNAT or any other form of network address translation, you must also enable IP forwarding on the machine. This can be done by editing the /etc/sysctl.conf file and uncommenting the following variable:

net.ipv4.ip_forward=1

In cases where you have an Internet-facing service offered on a machine behind your firewall, you can instruct the firewall to forward requests for that service to that machine. The following example uses a feature called port forwarding to pass requests for a service through the firewall to the destination machine behind the firewall:

$ sudo iptables -t nat -A PREROUTING \ Add nat PREROUTING rule

-p tcp -d 11.22.33.1 \ tcp requests on 11.22.33.1

--dport 80 \ for port 80 (Web service)

-j DNAT \ jump to the DNAT target

--to-destination 10.0.0.2 forward the packets to 10.0.0.2

There are many other types of rules you can create to change how your firewall behaves. Refer to the iptables man page or the Netfilter website (www.netfilter.org) for further information on using the iptables facility.

After making the preceding changes, you’ll see the following rules defined:

$ sudo iptables -t nat -L

Chain PREROUTING (policy ACCEPT)

target prot opt source destination

DNAT tcp -- anywhere 11.22.33.1 tcp dpt:www to:10.0.0.2

Chain POSTROUTING (policy ACCEPT)

target prot opt source destination

SNAT 0 -- anywhere anywhere to:11.22.33.1

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

Saving and Reloading Firewall Rules

All of the changes to the iptables rules that you simply type into the shell apply only to the current kernel session. Without somehow saving those rules, when you next reboot Ubuntu all the rules you entered will be erased, which is probably not what you want. To preserve your iptables rules, run iptables-save:

$ sudo iptables-save > iptables.rules Save rules to a file in the current directory

$ sudo cp iptables.rules /etc Copy the saved rules to /etc

The two-step process is required because of the restrictions on the /etc directory. (You can change those restrictions, but that probably isn’t a good idea.) Thus far, the rules are saved for later usage.

Next, you can configure Ubuntu to load these saved rules each time it enables an Ethernet interface (this is specific to each network card or interfaces on your system). Edit the /etc/network/interfaces file. After the ifaceconfiguration for an Ethernet interface, such as eth0, make a call to iptables-restore, as shown in this snippet:

auto eth0

iface eth0 inet dhcp

pre-up iptables-restore < /etc/iptables.rules

This addition to the interface files calls iptables-restore to restore the rules saved previously to the file /etc/iptables.rules.

Using Advanced Security Features

A dozen or so pages covering security-related commands are not nearly enough to address the depth of security tools available to you as a Linux system administrator. Beyond the commands covered in this chapter, here are descriptions of some features you may want to look into to further secure your Linux system:

· Security Enhanced Linux (SELinux)—The SELinux feature provides a means of securing the files, directories, and applications in your Linux system in such a way that exploitation of one of those areas of your system cannot be used to breach other areas. For example, if intruders were to compromise your web daemon, they wouldn’t necessarily be able to compromise the rest of the system.

SELinux was developed by the U.S. National Security Agency (NSA), which hosts a related FAQ at www.nsa.gov/selinux/info/faq.cfm. You need to install SELinux as separate packages. See https://wiki.ubuntu.com/SELinuxfor details.

· Central logging—If you’re managing more than a couple of Linux servers, it becomes preferable to have all your systems log to a central syslog server. When you implement your syslog server, you may want to explore using syslog-ng. Also, if you outgrow logwatch, you should consider using a log parser such as Splunk.

· Tripwire—Using the tripwire package, you can take a snapshot of all the files on your system, and then later use that snapshot to find if any of those files have been changed. This is particularly useful to find out if any applications have been modified that should not have been. First, you take a baseline of your system file. Then at regular intervals, you run a tripwire integrity check to see if any of your applications or configuration files have been modified.

· APT database—Another way to check if any of your applications have been modified is by using the APT commands to validate the applications and configuration files you have installed on your system. See Chapter 2 for information on using the APT and dpkg commands to verify the contents of installed packages.

· chkrootkit—If you suspect your system has been compromised, download and build chkrootkit from www.chkrootkit.org. This will help you detect rootkits that may have been used to take over your machine. We recommend you run chkrootkit from a LiveCD or after mounting the suspected drive on a clean system.

Summary

While many tools are available for securing your Linux system, the first line of security starts with securing the user accounts on your system and the services that run on your system. Commands such as useradd, groupadd, and password are standard tools for setting up user and group accounts.

Because most serious security breaches outside your organization can come from intruders accessing your systems on public networks, setting up secure firewalls is important for any system connected to the Internet. The iptables facility provides the firewall features that are built into the Linux kernel.