How to secure your Linux system
4th Jan 2011 | 09:00
Linux security tips and tricks and you need to know
Linux security basics
Are you running Linux just because you think it's safer than Windows? Think again. Sure, security is a built-in (and not a bolt-on) feature and extends right from the Linux kernel to the desktop, but it still leaves enough room to let someone muck about with your /home folder.
Linux might be impervious to viruses and worms written for Windows, but that's just a small subset of the larger issue. Attackers have various tricks up their sleeves to get to those precious bits and bytes that make up everything from your mugshot to your credit card details.
Computers that connect to the internet are the ones most exposed to attackers, although computers that never get to see online action are just as vulnerable. Think of that ageing laptop or that old hard disk you just chucked away without a second thought. Bad move.
With the kind of data recovery tools available today (many as a free download) it doesn't matter what OS was installed on the disk. If it holds data – corrupted or otherwise – it can be retrieved, bank accounts recreated, chat transcripts reconstructed, images restitched. But don't be scared. Don't stop using the computer.
While it's virtually impossible to make a machine connected to the internet impenetrable to attacks, you can make an attacker's task difficult and also ensure they have nothing to learn from a compromised system. Best of all, with Linux, and some pieces of open source software, it doesn't take much effort to secure your Linux installation.
There is no golden rule for security that applies in every single case, and even if there were it would have been cracked already. Security is something that needs to be worked upon, and personalised. Follow the tips and tools in this tutorial as we show you how to adapt them to your very own Linux installation.
Follow these six tips to get a safer computer the easy way
1. Keep up with security updates
All mainstream Linux desktop distros (such as Debian, Ubuntu, Fedora, etc) have security teams that work with the package teams to make sure you stay on top of any security vulnerabilities. Generally these teams work with each other to make sure that security patches are available as soon as a vulnerability is discovered.
Your distro will have a repository solely dedicated to security updates. All you have to do is make sure the security specific repository is enabled (chances are it will be, by default), and choose whether you'd like to install the updates automatically or manually at the press of a button.
For example, under Ubuntu, head over to System > Administration > Software Sources. Here, under the Updates tab, specify how frequently the distro should ping the security repository for updates, and whether you'd like to install them without confirmation, or just be notified about the updates.
The latter is a better option, because it lets you review the updates before installing them. But chances are they'll be fine, and you can save yourself some time by having your distro install them automatically.
In addition to the updates, distros also have a security mailing list to announce vulnerabilities, and also share packages to fix them. It's generally a good idea to keep an eye on the security list for your distro, and look out for any security updates to packages that are critical to you.
There's a small lag between the announcement and the package being pushed to the repository; the security mailing lists guide the impatient on how to grab and install the updates manually.
2. Disable unnecessary services
A Linux desktop distro starts a number of services to be of use to as many people as possible. But one really doesn't need all these services.
For example, do you really need Samba for sharing files over the network on your secure server, or the Bluetooth service to connect to Bluetooth devices on a computer that doesn't have a Bluetooth adapter?
All distros let you control the services that run on your Linux installation, and you should make full use of this customisation feature.
Under Ubuntu, head to System > Preferences > Startup Applications. Here you can remove check marks next to the services you wish to disable. But be careful when turning off services. Some applications might stop functioning because you decided to disable a service on which they rely.
For example, many server applications rely on databases, so before you turn off MySQL or PostgreSQL you should make sure you aren't running any applications that rely on them.
3. Restrict root access
Most distros these days don't allow you to login as root at boot time, which is good. When you have to execute a task that requires super user privileges you'll be prompted for a password. It might be a little irritating but it goes a long way to making sure that admin tasks are isolated from the user.
You can restrict access privileges for a user from under System > Administration > Users and Groups. Here you can broadly categorise a user as a desktop user or a system administrator or customise access privileges manually. By default, users are created as with 'Desktop user' permissions and can't install software or change settings that affect other users.
On the command line, the su command (on Fedora, and the like) lets normal users switch to the root account, while the sudo command (on Debian, Ubuntu, etc) grants more privileges to the user. The usage of these commands can be limited to a particular group, which prevents any user from administering the system. sudo is also the more secure of the two, and it keeps an access log under /var/log/auth.log.
Make a habit of regularly scanning the log for failed and successful sudo attempts.
4. Don't auto-mount devices
If you're really concerned about security, you need to lean on the customisation feature of the Users And Groups settings. One of the areas to look at is auto-mounting devices.
Most distros auto-mount USB drives and CDs as soon as they are inserted. It's convenient, but allows anybody to just walk up to your machine, plug in a USB disk and copy all your data. To avoid such a situation, go to to System > Administration > Users and Groups, select your user and head to the Advanced Settings > User Privileges tab.
Make sure you uncheck the boxes corresponding to the Access External Storage Devices Automatically option, the Mount Userspace Filesystems, and Use CD-ROM Drives option. When unchecked, these options will prompt the user for a password before giving them access to these devices.
You might also want to disable sharing files on the network, as well as require the user to enter a password before connecting to the Ethernet and wireless devices. By disabling access to configure printers you prevent important data from being printed.
5. Don't stay on the bleeding edge
Packages included in a desktop Linux distribution are updated regularly. Besides the official repositories, there are custom repositories for third-party software. While developers do take care to scan the packages for vulnerabilities before pushing them on to the repository, it's almost inevitable that some updates with defects do get through.
While it's good to keep the system updated, from a security point of view, not all updates are good for the system. Some updates conflict with existing installed package or may even pull in new dependencies that may make the system more prone to attack. All this is why you should only update packages if you have to.
Scan the updates and look for updates to packages that are critical to you. Most package managers also make it possible to check an update and display its changelog and a brief description of the changes. UI changes can safely be ignored or delayed until a package has been thoroughly tested. Instead, look out for and grab updates that offer a fix to existing issues with packages.
6. Don't upgrade every six months
Most major desktop Linux distributions make a new release every six months, but you don't have to install every last upgrade just because it's there. Debian, for example, offers three distributions to choose from based on the extent of the stability of the software available in it. After Debian 6.0, stable releases will be made every two years.
Other distros take a different approach to guarantee secure releases. Ubuntu marks certain releases as LTS (or Long Term Support). A desktop release of the LTS version is supported for three years, and a server release is supported for five years, which is a lot longer than the 18 months for a standard Ubuntu release.
Although not up to date, these releases are much more secure from a security point of view, with packages that are a lot more stable and more thoroughly tested than their latest versions. If running a secure system is your goal, you should think of sticking to one of these long-term stable releases and avoid the temptation to upgrade as soon as the latest version of your becomes available.
Software firewalls and encryption
Out of the box, a Linux installation is much more secure than other operating systems. That is, until you connect to the internet. Once online, a desktop Linux installation, in its bid to be of use to as many users as possible, leaves enough room to be exposed to attacks and intrusions. Don't sweat though. Help is only a terminal away.
All Linux distros ship with Iptables, which is a part of the kernel that enables sysadmins to filter network packets. Configuring it manually is impossible for all but the elite, but in the true spirit of open source the community offers a number of graphical front-ends that make setting up a firewall a walk in the park. One such graphical firewall is Firestarter.
We didn't start the fire
Firestarter simplifies the process of configuring the settings for a firewall. It can limit access on ports that are running services that might be prone to outside attacks, and you can also use it to glance at the network traffic passing across the machine you're running it on.
Most distros bundle Firestarter in their repos, so installing it shouldn't be a problem. When you start it for the first time, the firewall launches a simple configuration wizard that prompts you to select the network interface on which it will be active.
If you have multiple devices with one connecting to the internal network, Firestarter can act as gateway and share the internet connection with the rest of the network. By default, Firestarter only filters through connections that are in response to connection requests from the firewall host. The advantage of doing things this way is that it blocks access to services like Telnet, which can be exploited to gain access to your machine without your knowledge.
Tweaking the firewall doesn't take much effort either. If you have an app that requires access on certain ports, such as a Torrent client, you need to punch holes in your firewall to allow incoming connections. That's easily done from under the Policy tab.
Right-click inside the space under Allow Service and select Add Rule. From the pull-down menu, select the service you want to allow, say Samba, select the source IP (anyone opens the port to all) and you're done.
To restrict outgoing traffic, select Outbound Traffic Policy from the drop-down list. Now you can select either the Permissive or the Restrictive option. If you select the Permissive option, you'll have to add the hosts you want to block in a blacklist. Restrictive is the opposite, and only allows connections from the listed hosts, denying the rest.
When running in restrictive mode, Firestarter will log all connection refusals under the Events tab. As you spot a connection you want to allow for your users, right-click on the entry and select the option to either allow the connection for everyone or just when it originates from a particular source.
You can also monitor active connections to the firewall from Firestarter's main interface. It shows you the status of the service, gives you a summary of inbound and outbound connections, and the amount of data that has passed through an interface. In addition to listing the source and destination of the traffic, it'll also tell you the port the data is travelling through, the service running on that port and the program that's calling the shots.
Encrypt your filesystem
If you really want to keep others from reading your files, user passwords won't cut it. For instance, there's very little to stop a user with higher access permissions, like the root user, from gawking at stuff under your home directory. What you need is to encrypt your data so that it's unintelligible to people without the means to decrypt it.
The smart way to do this is to encrypt the whole filesystem, which would automatically encrypt any data kept on it. This is where TrueCrypt shines.
It lets you carve a virtual slice out of your Linux partition that will act as a standalone encrypted filesystem. You then mount it, use it to store and read files as you would from a normal partition, then unmount it, and Bob's your uncle. When it isn't mounted, the encrypted filesystem appears to be a random jumble of bits.
TrueCrypt isn't available in any distribution's repository due to licensing issues, but installing it is a trivial affair. Grab it from its website, extract the Tar archive, and install it via the graphical setup. Just make sure your distro has the Fuse library, and the device mapper tools.
Create an encrypted volume
Before you can use TrueCrypt you'll have to create an encrypted volume to store files on, so launch the app and click on the Create Volume button. This will launch the Volume Creation Wizard, which lets you either create a virtual encrypted disk within a file or an encrypted volume within an entire partition, or even a disk such as a removable USB drive.
If you select the first option to create a virtual disk, TrueCrypt will ask you to point it to a file on the disk that'll be the encrypted volume. If the file exists, TrueCrypt will recreate it, using one of the eight encryption algorithms.
Next, specify the size of the encrypted volume and format it as an FAT filesystem, which makes it accessible from other operating systems as well as Linux. Finally, choose a password to mount the encrypted volume.
To store files on the volume you'll have to mount it. Select the file that's your encrypted volume from the TrueCrypt main interface, and press the Mount button. The app will prompt for the password of the volume before it can be mounted. You also get the option to mount the volume as read-only, if all you have to do is read files from it.
By default, TrueCrypt chooses not to remember the name of the file that's your encrypted volume. This is a security feature, and adds another roadblock in the path of an intruder. If you ask the app to remember the name of the file, anyone with physical access to the computer can select the file from a pull-down menu and mount the encrypted volume. They'll still have to get past your password though.
Once the encrypted volume is mounted you can save files to it just like you do with a normal volume. TrueCrypt uses your modern hardware at its disposal to encrypt and decrypt files on the fly; which is to say it minimises the lag due to the overhead of converting unreadable bitstream into meaningful data that can be read by your text editor or played by your media player.
When you're through, unmount the volume with the Dismount button within the program.
Securely delete files and browse anonymously
Think formatting a disk is enough? Think again
Removing a file from the disk seems like a simple operation: just right-click on the file and send it to the trash. Command line users may use the rm command do do the same thing.
Unfortunately, none of these methods actually deletes a file or a folder. They just hypnotise the filesystem to forget where a file is located in the disk. These newly liberated disk locations are then added to the filesystem's pool of free address, and can point to new files.
That works in theory, but in practice the humongous size of partitions means that the disk locations that hold the deleted file may actually harbour them long enough for recovery tools to reconstruct them.
That's where shred comes in. Shred overwrites a file's space on the disk to make sure the space contains only garbage. You might also want to use the --remove option to make sure it deletes the original file as well.
Shredding a file can be a lengthy affair, as it overwrites the location 25 times. You can manipulate the number of rewrites with the -n switch, like this:
$ shred --remove -n 5 -v top-secret.txt
shred: top-secret.txt: pass 1/5 (random)...
shred: top-secret.txt: pass 2/5 (ffffff)...
shred: top-secret.txt: pass 3/5 (random)...
shred: top-secret.txt: pass 4/5 (000000)...
shred: top-secret.txt: pass 5/5 (random)...
shred: top-secret.txt: removing
shred: top-secret.txt: renamed to 0000
shred: 0000: renamed to 000
shred: 000: renamed to 00
shred: 00: renamed to 0
shred: top-secret.txt: removed
Shred works well on devices like /dev/sdb, which negates the use of the --remove switch, because you wouldn't want to remove the device. There's a caveat here. Shred assumes the filesystem rewrites the file in place. This would render it useless on modern journalled filesystems such as ext3.
Shred also fails to wipe traces of the data being deleted in several places, such as the swap, RAM, and the filesystem journal. An effective and secure deletion strategy requires the secure delete tools.
The secure-delete tools include srm to securely remove the files, smem and sswap to wipe traces of data from the physical and SWAP memory, and sfill to ensure the free space on the disk doesn't point to old deleted files. The tools make use of cryptographic algorithms especially designed to make sure deleted files are unrecoverable.
Once it's installed, make sure you remove the file or a directory with:
$ srm -v ../the-hole/eicar.com.txt
Using /dev/urandom for random input.
Wipe mode is secure (38 special passes)
Wiping ../the-hole/eicar.com.txt *********************************** *** Removed file ../the-hole/eicar.com.txt ... Done
Add the -r switch to recursively delete a directory. When you're done, make sure you wipe off residual traces from your RAM with smem, which may take a considerable amount of time depending on the size of the physical memory it has to wipe. You can speed up the process with the -l switch, which reduces the number of rewrite passes (this is less secure).
Top off the process by disabling swap with swapoff <swap-partition>, wiping it clean with sswap <swappartition>, and then re-enabling it with swapon <swappartition>. The sfill command comes in handy when you are discarding a disk. Use it from a live CD on an unmounted partition to wipe the free space.
They might not be as bad as the other operating system, but all Linux distros tend to accumulate a lot of crud over a period of time. But why blame Linux?
The junk files are the legacy of the plethora of apps you have running on top of your kernel. You can pin their habit of collecting fluff to of the way the applications are configured to give you a better user experience. And not only do all those log files, the temporary internet files and the various app caches accumulate to take up a considerable amount of disk space, they pose a great threat to your privacy.
Instead of trolling through the filesystem and emptying the various tmp/ directories, use BleachBit. It's a one-stop shop for removing all the crud that the apps have preserved.
BleachBit has a set of about 70 pre-defined cleaners, each of which works on a particular app such as Firefox, Google Chrome, Adobe Reader, OpenOffice.org and more. The cleaners are tuned to wipe the dead weight off the applications and give them a performance boost.
The lightweight BleachBit is available in the repositories of all major distributions, though you might want to grab the latest build from its website. The project also releases bonus cleaner packs for older versions.
The BleachBit GUI is divided into two frames. On the left-hand side you select the apps that you wish to clean; this expands to give you more options specific to that app. In the right-hand frame, you get a brief explanation of each of these checkable options.
To clean an area, such as Firefox's cache, simply click on the checkbox next to it. Some cleanup operations require you to trawl through a large location and involve more than a simple delete operation. BleachBit will warn you when selecting such a task that might take up a considerable amount of time, for example, wiping the swap memory.
Before you ask BleachBit to zap the useless files in the apps you've selected, use the Preview button to review the list of files it'll delete. If you encounter a file that you don't want to delete, such as the cache of a particular Firefox user, you can add it to a whitelist.
This is a list of files that BleachBit will not touch, even if the broader cleaner that they come under has marked them for removal. You can specify any files or folders to bypass under the Whitelist tab under Edit > Preferences.
BleachBit also has a command line interface. For example, the following command cleans cookies under Firefox and Google Chrome:
$ bleachbit --delete firefox.cookies google_chrome.cookies
Use the --preview switch to get a list of files before removal. The CLI makes BleachBit scriptable for automated daily runs.
To add a cron job to nuke regularly created files, such as rotated logs and cookies daily at 2.00 am, edit the crontab with crontab -e and add the following line:
0 2 * * * bleachbit --delete firefox.cookies google_chrome. cookies system.rotated_logs
If daily sounds too frequent, you should at least run the app before creating backups. You can also use BleachBit to speed up certain apps, house clean the distro by fixing broken shortcuts, delete language packs and empty physical RAM and swap memory.
Pull a Keyser Soze on the internet – make it think you don't exist…
On the internet, sometimes the best form of privacy is being anonymous. It's difficult for an attacker to get to you if they can't pinpoint you on the network. And no one covers your tracks better than the combination of Privoxy and Tor.
Tor protects privacy via a distributed network of relays run by volunteers spread across the world. This helps prevent anybody monitoring your internet connections from learning what sites you visit.
Tor works with web browsers, instant messaging programs and many other TCP-based apps. But the various app protocols and associated programs can be coaxed into revealing information about the user, which is where Privoxy comes into the picture. Tor depends on Privoxy and its filtering capabilities to enhance privacy.
Begin by pulling Privoxy from your distro repositories, then head into your browser's advanced settings where you can change its proxy settings. Here just fill in 127.0.0.1 for the HTTP proxy, and specify 8118 as the port. That's all there's to it.
When you're done, start the Privoxy daemon with /etc/ init.d/privoxy start. You can now access Privoxy's interface from http://config.privoxy.org or http://p.p.
To hook up Privoxy with Tor, you first need to set up Tor's package repository. This is easily done by adding the following line to your Ubuntu or Debian installation:
deb http://deb.torproject.org/torproject.org <DISTRIBUTION> main
Replace <DISTRIBUTION> with the name for your distro, like karmic, or sid. Then add the GPG key used to sign the packages by running the following:
gpg --keyserver keys.gnupg.net --recv 886DDD89 gpg --export A3C4F0F979CAA22CDBA8 F512EE8CBC9E886DDD89 | sudo apt-key add -
If you use Yum, create a torproject.repo under /etc/ yum/repos.d with the following content:
name=Tor and Vidalia
Again replace DISTRIBUTION with the name of your Fedora or CentOS release, such as centos5 or fc13. Now fetch Tor via the package manager, which will also pull in additional packages like the Vidalia Tor GUI controller.
Make sure you don't install the Polipo web proxy app, since we are using Privoxy and the two might conflict because they operate on the same port.
The last step is to get Privoxy and Tor to talk to each other. For this just edit the Privoxy config file under /etc/privoxy and uncomment the following line:
# forward-socks4a / 127.0.0.1:9050
Also uncomment the following lines to make sure the local network is still reachable:
# forward 192.168.*.*/ .
# forward 10.*.*.*/ .
# forward 127.*.*.*/
Presto! Now all our internet traffic that passes through the Tor and Privoxy proxies is masked.
First published in Linux Format Issue 139
Liked this? Then check out 7 of the best Linux firewalls
Sign up for TechRadar's free Weird Week in Tech newsletter
Get the oddest tech stories of the week, plus the most popular news and reviews delivered straight to your inbox. Sign up at http://www.techradar.com/register