Chapter 20

Securing Your Machines

No computer with a connection to the Internet is 100 percent safe. If this information does not concern you, it should. Although there is no way to guarantee the ability to stop patient, creative, and serious crackers who are intent on getting into your computer or network, there are ways to make it harder for them and to warn you when they do. This chapter discusses all aspects of securing your Linux machines. You might have wondered why we did not spread this information around the book wherever it is appropriate, and the reason is simple: If you ever have a security problem with Linux, you know you can turn to this page and start reading without having to search or try to remember where you saw a tip. Everything you need is here in this one chapter, and we strongly advise you to read it from start to finish.

Built-In Protection in the Kernel

A number of networking and low-level protective services are built in to the Linux kernel. These services can be enabled, disabled, or displayed by using the sysctl command or by echoing a value (usually a 1 or a 0 to turn a service on or off) to a kernel process file under the /proc directory. See the discussion of setting a variable with echo in Chapter 11, “Command-Line Master Class, Part 1,” or the man pages for sysctl and echo for more.

Understanding Computer Attacks

There are many ways to classify computer attacks. Perhaps the easiest way is to characterize attacks as internal, or computer attacks done by someone with access to a computer on the local network, and external, or attacks by someone with access to a computer through the Internet. This might sound like a trivial separation to make, but it is actually important: Unless you routinely hire talented computer crackers or allow visitors to plug computers into your network, the worst internal attack you are likely to encounter is from a disgruntled employee.

Hacker Versus Cracker

In earlier days, a distinction was made between the words hacker and cracker. A hacker was someone who used technology to innovate in new or unusual ways, whereas a cracker was someone who used technology to attack another’s computers and cause harm. So, by the original definitions, hackers did good or cool things, and crackers did bad things.

This distinction was lost on the general public, and the term hacker has now regretfully come to mean the same thing as cracker for most people. However, we recognize the distinction and use the term cracker to mean a malicious person using a computer to cause problems for others. In your real-world conversations, realize that most people do not make a distinction, and so be prepared to define your terms if you call yourself a hacker.

Although you should never ignore internal threats, you should arguably be more concerned with the outside world. The big bad Internet is a security vortex. Machines connected directly to the outside world can be attacked by people around the world, and invariably are, sometimes even only a few minutes after getting connected.

This situation is not a result of malicious users lying in wait for your IP address to do something interesting. Instead, canny virus writers have created worms that exploit vulnerability, take control of a machine, and then spread to other machines around them. As a result, most attacks today result from these autocracking tools; only a handful of true clever crackers are around, and, to be frank, if one of them ever actually targets you seriously, it will take a mammoth effort to repel the cracker, regardless of what operating system you run.

Autocracking scripts also come in another flavor: prewritten code that exploits vulnerability and gives its users special privileges on the hacked machine. These scripts are rarely used by their creators; instead, they are posted online and downloaded by wannabe hackers, who then use them to attack vulnerable machines.

So, the external category is itself made up of worms, serious day job crackers, and wannabe crackers (usually called script kiddies). Combined, they will assault your Internet-facing servers, and your job is to make sure your boxes stay up, happily ignoring the firefight around them.

On the internal front, things are somewhat more difficult. Users who sit inside your firewall are already past your primary source of defense and, worse, might even have physical access to your machines. Those with malicious intent and physical access to a machine are nearly impossible to stop unless they are simply inept. The situation is only slightly better if they don’t have physical access but do have access to your internal network.

Regardless of the source of the attack, you can follow a five-step checklist to help secure your box:

  1. Assess your vulnerability. Decide which machines can be attacked, which services they are running, and who has access to them.

  2. Configure the server for maximum security. Install only what you need, run only what you must, and configure a local firewall.

  3. Secure physical access to the server.

  4. Create worst-case-scenario policies.

  5. Keep up to date with security news.

These steps are covered in the following sections, and all of them are equally important.

Assessing Your Vulnerability

A common mistake people make is to assume that switching on a firewall makes them safe. This is not the case and, in fact, has never been the case. Each system has distinct security needs, and taking the time to customize its security layout will give you the maximum security and the best performance.

The following list summarizes the most common mistakes:

Installing every package—Do you plan to use the machine as a DNS server? If not, why have BIND installed? Go through and ensure that you have only the software you need.

Enabling unused services—Do you want to administer the machine remotely? Do you want people to upload files? If not, turn off SSH and FTP because they just add needless attack vectors. Do the same for all other unused services.

Disabling the local firewall on the grounds that you already have a firewall at the perimeter—In security, depth is crucial: The more layers someone has to fight through, the greater the likelihood the cracker will give up or get caught.

Letting your machine give out more information than it needs to—Many machines are configured to give out software names and version numbers by default, which gives crackers a helping hand.

Placing your server in an unlocked room—If you do, you might as well just turn it off now and save the worry. Even if all the employees at your company are happy and trustworthy, why take the risk?

Plugging your machine into a wireless network—Unless you need wireless, avoid it, particularly if your machine is a server. Never plug a server into a wireless network because doing so is just too fraught with security problems.

After you have ruled out these potential issues, you are on to the real problem: Which attack vectors are open on your server? In Internet terms, this comes down to which services are Internet-facing and which ports they are running on.

Nmap scans your machine and reports on any open TCP/IP ports it finds. Any service you have installed that responds to Nmap’s query is pointed out, which enables you to ensure that you have locked everything down as much as possible.

Nmap is available to install from the Ubuntu software repositories. Although you can use Nmap from a command line, it is easier to use with the front end—at least until you become proficient. To run the front end, open a terminal and run nmapfe. If you want to enable all Nmap’s options, you must have administrator privileges and run sudo nmapfe.

When you run Nmap (by clicking the Scan button), it tests each port on your machine and checks whether it responds. If a port does respond, Nmap queries it for version information and then prints its results onscreen. The output lists the port numbers, service name (what usually occupies that port), and version number for every open port on your system. Hopefully, the information Nmap shows you will not be a surprise. If there is something open that you do not recognize, it could be that a cracker placed a back door on your system to allow easy access, and you should check into it further.

Use the output from Nmap to help find and eliminate unwanted services. The fewer services that are open to the outside world, the more secure you are. Only use Nmap on systems that you own. Scanning other people’s servers is impolite, and you may also be accused of doing so in preparation for illegal activity.

Protecting Your Machine

After you have disabled all the unneeded services on your system, what remains is a core set of connections and programs that you want to keep. However, you are not finished yet: You need to clamp down your wireless network, lock your server physically, and put in place scanning procedures (such as Tripwire and promiscuous mode network monitors).

Securing a Wireless Network

Wireless networking has some unique security issues, and those issues deserve a separate discussion.

Wireless networking, although convenient, can be very insecure by its very nature because transmitted data (even encrypted data) can be received by remote devices. Those devices could be in the same room; in the house, apartment, or building next door; or even several blocks away. You must use extra care to protect the frequency used by your network. Great progress has been made in the past couple of years, but the possibility of a security breach is increased when the attacker is in the area and knows the frequency on which to listen. It should also be noted that the encryption method used by many wireless NICs is weaker than other forms of encryption (such as SSH), and you should not consider using wireless NIC encryption alone as part of your security plan.

Tip

Always use OpenSSH-related tools, such as ssh or sftp, to conduct business on your wireless LAN. Passwords are not transmitted as plain text, and your sessions are encrypted. See Chapter 19, “Remote Access with SSH and VNC,” to see how to connect to remote systems using ssh.

The better the physical security around your network, the more secure the network will be. (This applies to wired networks as well.) Keep wireless transmitters (routers, switches, and so on) as close to the center of your building as possible. Note or monitor the range of transmitted signals to determine whether your network is open to mobile network sniffing—a geek sport known as war driving. Wireshark is an example of a program that is useful for analyzing wireless traffic (as well as all other network activity). An occasional walk around your building not only gives you a break from sitting at your desk but can give you a chance to notice any people or equipment that should not be in the area.

Keep in mind that it takes only a single rogue wireless access point hooked up to a legitimate network hub to open access to your entire system. These access points can be smaller than a pack of cigarettes, and the best way to spot them is to scan for them with another wireless device.

Passwords and Physical Security

The next step toward better security is to use secure passwords on your network and ensure that users use them as well. For somewhat more physical security, you can force the use of a password with the GRUB bootloader, remove bootable devices such as DVD-ROM drives or USB boot options from the BIOS, or configure a network-booting server for Ubuntu.

Also keep in mind that some studies show that as many as 90 percent of network break-ins are done by current or former employees. If a person no longer requires access to your network, lock out access or, even better, remove the account immediately. A good security policy also dictates that any data associated with the account first be backed up and retained for a set period of time to protect against loss of important data. If you are able to do so, remove the terminated employee from the system before the employee leaves the building.

Finally, be aware of physical security. If a potential attacker can get physical access to your system, getting full access becomes trivial. Keep all servers in a locked room and ensure that only authorized personnel are given access to clients. Laptops and other mobile devices should be configured with only what is needed, and any truly sensitive data should be kept on machines that are physically secured. When machines containing any sensitive data must be used outside a secure environment, you should use hard drive encryption, such as that available when installing Ubuntu.

Something that you may find useful for laptops and other mobile devices is Prey. Prey has a basic version that is open source, free software that will help you track down a missing device, provided that Prey was installed on the device before it was lost. There is also a paid version with a few more features. You can learn about Prey at https://preyproject.com.

Configuring and Using Tripwire

Tripwire is a security tool that checks the integrity of normal system binaries and reports any changes to syslog or by email. Tripwire is a good tool for ensuring that your binaries have not been replaced by Trojan horse programs. Trojan horses are malicious programs inadvertently installed because of identical filenames to distributed (expected) programs, and they can wreak havoc on a breached system.

There are two versions of Tripwire: an open source version and a commercial product. The free version of Tripwire is available in the Ubuntu repositories. You can find out about the differences at www.tripwire.org.

To initialize Tripwire, use its -init option, like this:

matthew@seymour~:$ sudo tripwire -init
Please enter your local passphrase:
Parsing policy file: /etc/tripwire/tw.pol
Generating the database...
*** Processing Unix File System ***
....
Wrote database file: /var/lib/tripwire/shuttle2.twd
The database was successfully generated.

Note that not all the output is shown here. After Tripwire has created its database (which is a snapshot of your file system), it uses this baseline along with the encrypted configuration and policy settings in the /etc/tripwire directory to monitor the status of your system. You should then start Tripwire in its integrity checking mode, using a desired option. (See the tripwire man page for details.) For example, you can have Tripwire check your system and then generate a report at the command line by entering the following:

matthew@seymour~:$ sudo tripwire -m c

No output is shown here, but you would actually get a report after entering this command. The output could be redirected to a file, but a report is saved as /var/lib/tripwire/report/hostname-YYYYMMDD-HHMMSS.twr (in other words, using your host’s name, the year, the month, the day, the hour, the minute, and the seconds). This report can be read using the twprint utility, like this:

matthew@seymour~:$ sudo twprint --print-report -r 
/var/lib/tripwire/report/shuttle2-20020919-181049.twr | less

Other options, such as emailing the report, are supported by Tripwire, which should be run as a scheduled task by your system’s scheduling table, /etc/crontab, on off-hours. (It can be resource intensive on less powerful computers.) The Tripwire software package also includes a twadmin utility that you can use to fine-tune or change settings or policies or to perform other administrative duties.

Plan to spend some time reading documentation if you want to use Tripwire. It is powerful but not simple. We recommend starting with the man pages and www.tripwire.com.

Securing Devices

Do not ever advertise that you have set a NIC (network interface controller) to promiscuous mode. Promiscuous mode (which can be set on an interface by using ifconfig’s promisc option) is good for monitoring traffic across the network and can often enable you to monitor the actions of someone who might have broken into your network. The tcpdump command also sets a designated interface to promiscuous mode while the program runs; unfortunately, the ifconfig command does not report this fact while tcpdump is running!

Remember to use the right tool for the right job. Although you can use a network bridge to connect your network to the Internet, it would not be a good option. Bridges have almost become obsolete because they forward any packet that comes their way, which is not good when a bridge is connected to the Internet. A router enables you to filter which packets are relayed.

Viruses

In the right hands, Linux is every bit as vulnerable to viruses as Windows. This might come as a surprise to you, particularly if you made the switch to Linux on the basis of its security record. However, the difference between Windows and Linux is that Linux is much easier to secure against viruses. Indeed, as long as you are smart and diligent, you need never worry about them. Here is why:

Linux never puts the current directory in your executable path, so typing ls runs /bin/ls rather than any program named ls in the current directory.

A nonroot user can infect only the files that user has write access to, which is usually only the files in the user’s home directory. This is one of the most important reasons for never using sudo when you don’t need to.

Linux forces you to manually mark files as executable, so you can’t accidentally run a file called myfile.txt.exe thinking it is just a text file.

By having more than one common web browser and email client, Linux has strength through diversity: Virus writers cannot target one platform and hit 90 percent of the users.

Despite all these factors, Linux is susceptible to being a carrier for viruses. If you run a mail server, your Linux box can send virus-infected mails on to Windows boxes. The Linux-based server would be fine, but the Windows client would be taken down by the virus. To prevent such a situation, consider using a virus scanner for your machine. You have several to choose from, both free and commercial. The most popular free suite is ClamAV (www.clamav.net), but several others compete to provide commercial solutions. Look around for the best deal before you commit.

Configuring Your Firewall

Use a hardware-based or software-based firewall on each computer connected to the Internet. Ubuntu has a firewall application named Uncomplicated Firewall (UFW) that is installed by default. This tool enables you to implement selective or restrictive policies regarding access to your computer or LAN.

UFW is run from the terminal, and you must have administrative privileges to use it. Commands are given like this:

matthew@seymour~:$ sudo ufw status

The most useful commands UFW are listed in Table 20.1. For others, see the ufw man page. Many are described in greater detail after the table.

By default, the UFW or firewall is disabled. To enable the firewall, run the following command:

matthew@seymour~:$ sudo ufw enable

To disable UFW, replace enable with disable.

Table 20.1 Useful Commands for UFW

Command

Actions Performed

Usage: sudo ufw command

 

Enable

Enables the firewall

Disable

Disables the firewall

Reload

Reloads the firewall to ensure changes are applied

default allow|deny|reject

Sets default policy

logging on|off

Toggles logging (can also be used to set the level of logging; see the man page)

allow ARGS

Adds an allow rule

deny ARGS

Adds a deny rule

reject ARGS

Adds a reject rule

limit ARGS

Adds a limit rule

delete RULE

Deletes the rule

status shows

Shows the firewall status

status numbered

Shows the firewall status as a numbered list of rules

Usage: ufw command

 

status verbose

Shows verbose firewall status

show REPORT

Shows a firewall report

-version

Displays version information

Next, you want to enable firewall logging. Much as with the enable command, you run the following command:

matthew@seymour~:$ sudo ufw logging on

To enable specific ports on the firewall, you can run the ufw command along with the port number to open. For example, if you want to allow port 80 (HTTP) incoming connections to your Ubuntu server, enter the following:

matthew@seymour~:$ sudo ufw allow 80

To remove the firewall rule allowing port 80 connections, run the following command:

matthew@seymour~:$ sudo ufw delete allow 80

Many services are already defined in ufw. This means you don’t have to remember the standard ports those services use, and you can allow, deny, or delete by using the service name, like this:

matthew@seymour~:$ sudo ufw allow ssh

You can also allow incoming connections from particular IP addresses. For example, if you want to let 192.168.0.1 connect to your server, enter the following:

matthew@seymour~:$ sudo ufw allow from 192.168.0.1

To remove the firewall rule allowing the previous IP address to connect, run the following command:

matthew@seymour~:$ sudo ufw delete allow from 192.168.0.1

There is a graphical interface called GUFW that you can install from the Ubuntu repositories to manage UFW. The same details apply, but the interface is easier and does not require you to remember as much as with UFW.

UFW is based on iptables, which is used to configure the Linux kernel’s built-in firewall. UFW simplifies the user tasks and syntax but really just uses iptables. You probably won't need to know this on your Ubuntu machine, but for completeness and to help you in case you use a different Linux distribution in the future, Table 20.2 lists simple, basic commands as a brief introduction to iptables.

In the table, you see words in all-caps like ACCEPT and DROP, which are policies to be set for things called chains. Chains are descriptions of specific types of network access, such as INPUT, FORWARD, and OUTPUT in Table 20.2, as well as other interactions in a network. You can, for example, define the default policy as DROP, which means to reject, and then ALLOW specific types of traffic to go through the firewall. iptables is quite complex and incredibly powerful.

Table 20.2 Useful Commands for iptables

Command

Actions Performed

Usage: command

 

sudo iptables -L

Lists the currently set firewall rules

sudo iptables -L -vn

Lists the currently set firewall rules but with more detail

sudo iptables -F

Deletes all currently set firewall rules

sudo iptables -P INPUT DROP

Drops all incoming traffic

sudo iptables -P FORWARD ACCEPT

Accepts all forwarded traffic

sudo iptables -P OUTPUT DROP

Drops all outgoing traffic

sudo iptables -A INPUT -s 8.8.8.8 -j DROP

Drops all traffic from a specific IP address (the example here is a Google DNS server, and you probably don’t want to block that one…)

You can block or allow traffic based on IP address, NIC, port, network, and more. You can set iptables to log all actions or just specific actions. You can even use it to configure NAT routers. For more, see the man pages for iptables and its IPv6 cousin, ip6tables.

nftables is a new firewalling tool that is gradually replacing iptables. nftables is considered stable and suitable for production environments, but it is not yet the default. If you want to start reading and consider switching now instead of waiting for it to become the default, see the official documentation at https://wiki.nftables.org/wiki-nftables/index.php/Main_Page.

AppArmor

AppArmor is a mandatory access control (MAC) system. It is less complicated than the better-known SELinux (https://selinuxproject.org/), a MAC framework created by the U.S. National Security Agency (NSA). AppArmor is designed to limit what specific programs can do by restricting them to the use of predetermined resources—and only those resources. This is done via profiles, which are loaded into the kernel at boot. It can be run in complain mode, where information is logged about insecure practices but no action is taken, or in enforce mode, where policies and limits are active.

This section provides a brief introduction to AppArmor. For a fuller introduction, check the links listed in the “References” section at the end of this chapter.

By default, AppArmor does little. You can install some extra profiles from the Ubuntu repositories by installing the apparmor-profiles package. These run in complain mode and log issues in /var/log/syslog.

To unleash the power of AppArmor, you need to edit or create text files in /etc/apparmor.d. A profile is named for the application it restricts, including the full path to the application in the file system. For example, the file sbin.rsyslogd, shown here, restricts the system logging daemon:

# Last Modified: Sun Sep 25 08:58:35 2011
#include <tunables/global>
# Debugging the syslogger can be difficult if it can't write to the file# that the kern-
el is logging denials to. In these cases, you can do the# following:# watch -n 1 'dmesg
| tail -5'
/usr/sbin/rsyslogd {  #include <abstractions/base>  #include <abstractions/nameservice>
  capability sys_tty_config,  capability dac_override,  capability dac_read_search,
capability setuid,  capability setgid,  capability sys_nice,  capability syslog,
  # rsyslog configuration  /etc/rsyslog.conf r,  /etc/rsyslog.d/ r,  /etc/rsyslog.d/** r,
/{,var/}run/rsyslogd.pid rwk,  /var/spool/rsyslog/ r,  /var/spool/rsyslog/** rwk,
  /usr/lib{,32,64}/rsyslog/*.so mr,
  /dev/tty*                     rw,  /dev/xconsole                 rw,  @{PROC}/kmsg
r,
  /dev/log                      wl,  /var/lib/*/dev/log            wl,  /var/spool/post
fix/dev/log    wl,
  # 'r' is needed when using imfile  /var/log/**                   rw,
  # Add these for mysql support  #/etc/mysql/my.cnf r,  #/{,var/}run/mysqld/mysqld.sock rw,
  # Add these for postgresql support  ##include <abstractions/openssl>  ##include
<abstractions/ssl_certs>  #/{,var/}run/postgresql/.s.PGSQL.*[0-9] rw,
  # Site-specific additions and overrides. See local/README for details.  #include
<local/usr.sbin.rsyslogd>}

Even without knowing the syntax, you can see from this file that profiles are simple text files that support the use of comments, that absolute paths and globbing (pattern matching for filenames) are supported, that specific capabilities are allowed or disallowed, and what locations and programs in the file system may be accessed or used.

Each access rule specifies specific permissions from this list:

r    - read
w    - write
ux   - unconstrained execute
Ux   - unconstrained execute - scrub the environment
px   - discrete profile execute
Px   - discrete profile execute - scrub the environment
ix   - inherit execute
m    - allow PROT_EXEC with mmap(2) calls
l    - link

These permissions are listed at the ends of lines.

genprof is a program that helps you generate or update a profile. You supply the name of the executable (or the path, if it is not already in the path) and may optionally supply the path to the profiles, as well. The following is an example:

matthew@seymour~:$ sudo genprof google-chrome

You will be asked to start the program and use it for a bit. After it is complete, you are given an opportunity to choose whether access to each function should be allowed or denied. The program then writes a text file in /etc/apparmor.d, using the name of the program and its path (in this case, opt.google.chrome.google-chrome, which in this case was installed directly from Google (www.google.com/chrome?platform=linux) so no premade AppArmor profile exists on the system used in this example). You may then edit the text file as desired, which you must do if you want to change from complain mode to enforce mode.

When you have a set of profiles that cover what you need, these are the commands you will use most often:

start: Use the start command as follows:

matthew@seymour~:$ sudo service apparmor start

stop: Use the stop command as follows:

matthew@seymour~:$ sudo service apparmor stop

reload: Use the reload command as follows:

matthew@seymour~:$ sudo service apparmor reload (or restart)

show status: Use the show status command as follows:

matthew@seymour~:$ sudo service apparmor status

This section has just scratched the surface of AppArmor, but hopefully you have learned enough information that your appetite has been whetted, and you are ready to do some further reading.

Forming a Disaster Recovery Plan

No one likes planning for the worst, which probably explains why two-thirds of people do not have wills. Having your systems hacked is a scary thing: One or more criminals has broken through your carefully laid blocks and caused untold damage to the machine. Your boss, if you have one, wants a full report of what happened and why, and your users want their email when they sit down at their desks in the morning. What do you do?

If you ever do get hacked, nothing will take the stress away entirely. However, if you take the time to prepare a proper response in advance, you should at least avoid premature aging. Here are some suggestions to get you started:

Do not just pull out the network cable. Pulling the cable acts as an alert that the cracker has been detected, which rules out any opportunities for security experts to monitor for that cracker returning and actually catch him or her.

Inform only the people who need to know. Your boss and other IT people are at the top of the list; other employees are not. Keep in mind that it could be one of the employees behind the attack, and you don’t want to tip off the culprit.

If the machine is not required, and you do not want to trace the attack, you can safely remove it from the network. However, do not switch it off because some backdoors are enabled only when the system is rebooted.

Make a copy of all the log files on the system and store them somewhere else. These files might have been tampered with, but they might contain nuggets of information.

Check the /etc/passwd file and look for users you do not recognize. Change all the passwords on the system and remove bad users.

Check the output of ps aux to see if unusual programs are running. Also check to see whether any cron jobs are set to run.

Look in /var/www and see whether any web pages are there that should not be.

Check the contents of the .bash_history files in the /home directories of your users. Are there any recent commands for your primary user?

If you have worked with external security companies previously, call them in for a fresh audit. Hand over all the logs you have and explain the situation. They will be able to extract all the information from the logs that is possible to extract.

Start collating backup tapes from previous weeks and months. Your system might have been hacked long before you noticed, and you might need to roll back the system more than once to find out when the attack actually succeeded.

Download and install Rootkit Hunter from http://rkhunter.sourceforge.net/. This tool searches for and removes the types of files that bad guys leave behind for their return.

Finally, keep your disaster recovery plan somewhere safe; saving it as a file on the machine in question is a very bad move.

References

https://help.ubuntu.com/community/InstallingSecurityToolsUbuntu community documentation of and suggestions for various security tools

https://nmap.orgThe official site for Nmap

www.tripwire.orgInformation and download links for the open source version of Tripwire

www.ubuntu.com/usnThe official Ubuntu security notices list, which is well worth watching

https://help.ubuntu.com/community/UFWUbuntu community documentation for UFW

https://wiki.ubuntu.com/UncomplicatedFirewallUbuntu documentation for UFW

https://gitlab.com/apparmor/apparmor/wikis/home/The official documentation for AppArmor

https://help.ubuntu.com/community/AppArmorUbuntu community documentation for AppArmor

https://wiki.ubuntu.com/Security/FeaturesAn Ubuntu wiki page that outlines and describes security features, Ubuntu, and configuration

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

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