Difference between revisions of "Linux security"

From Gender and Tech Resources

m (Traffic monitoring)
m (Traffic monitoring)
Line 527: Line 527:
  
 
  $ sudo adduser user wireshark
 
  $ sudo adduser user wireshark
 +
 +
==== Capturing packets ====
 +
 +
You can launch it and click the name of an interface under ''Interface List'' to start capturing packets on that interface. For example, if you want to capture traffic on the wireless network, click your wireless interface. You can configure advanced features by clicking ''Capture Options'':
  
 
== Configure sysctl (*) ==
 
== Configure sysctl (*) ==

Revision as of 20:54, 8 August 2015

This page contains some basic security measures specifically for people getting started with linux. Knowing your way around a bit on the kinky linux command-line helps. If you run into trouble, find us on IRC.

Internet Security is based on a slew of old myths, which reach their most ‘refined’ form in RandomSource, which in turn of course derived from the original Rule of Least Power episode "Planet of Wobbly Rocks where the Security Guard Got Shot".

Setting up root mail

Debian with MATE comes with the exim mailserver installed. If you don't like exim, install postfix (if you install the one, the other is uninstalled).

  • Exim uses the Sendmail design model where a single binary controls all the facilities of the MTA. This monolithic design is inherently less secure due to the lack of binary separation between the individual components of the system. Exim separates processes and has well-defined stages where it gains or loses privileges.
  • Postfix has a modular design to improve security over Qmail. A master daemon (a background process) launches other smaller processes with limited privileges that do specific tasks related to the various stages of mail delivery. The modular approach limits the effects of attacks.
  • Sendmail is the default MTA shipped with many Linux distribution sets and is the most well-known. It is easy to configure but had the most security loopholes, partly because it was designed long before hackers started attacking email systems. Developers fix most security issues quickly, but because it has the most number of users, it is still the biggest target for hackers.

Postfix

Installing

To install postfix:

$ sudo apt-get install postfix

Setting up local email account

Next is setting up an account in a mail client.

icedove

The wizard of icedove (thunderbird) does not allow directly for setting up local mail adresses. Choose "I think I'll configure my account later.":

Localmail1.png

Make the menu appear, and choose the big Movemail link (all the way to the right of the blue email):

Localmail2.png

Fill in "Identity" data like so:

Localmail3.png

Outgoing Server Information like so (will be revisited):

Localmail4.png

Your "Account Name":

Localmail5.png

If all went well the account has appeared. Revisit SMTP settings: Edit > Account Settings -> Outgoing Server (SMTP) -> Edit

Localmail7.png

Set Port 25:

Localmail6.png

You may already have messages for user. Maybe not for root yet.

Open /etc/aliases with your favourite editor (vi, vim, nano, geany):

$ sudo geany /etc/aliases

And make sure there is a root: username, username being *your* username of course, and a postmaster: root line in the file.

Localmail8.png

Installing intrusion detection

You can use a firewall, keep your system softwares up to date, stop all unrequired services, use long and difficult passwords and password managers, and more (see below), there is still a chance that some intruder might get into your system.

When intruders penetrate your system there is a great chance that they will want to make their presence as quiet as possible. To do so, they are most likely to replace some common binaries such as ls, netstat or ps with versions that will not make their presence visible. For example, ls can be replaced with an ls version that won't show the files they created, netstat will not show connections that are used by the intruder, and ps will hide processes the intruder runs. To detect changes like that in your system, you can set up intrusion detection with for example aide or tripwire.

Aide and tripwire are both File Integrity Agents (FIAs). A FIA monitors the integrity and state of the files and objects on your machine. If it detects changes to those files, then it alerts the administrator that an unauthorised access or change has taken place. FIAs usually take a hash of all files to be monitored using an algorithm like MD5. The snapshot is periodically checked against the current hash of the file and any variations alerted on.

For some "aide vs tripwire" notes, see Linux applications: Intrusion detection, and for an example install of tripwire on a server, see Linux server security: Installing intrusion detection. On a home system, aide.

aide

Installing

To install aide on a debian based system:

$ sudo apt-get install aide

Open up /etc/default/aide with your favourite editor to change who to send its reports to:

$ sudo geany /etc/default/aide
Aide1.png

Initialising

Initialise (this can take some time):

$ sudo aideinit

Configuring

Most of aide configuration can be found in /etc/aide/aide.conf. This file is pretty well documented and default rules are quite decent. Aide aims at reporting files that changed since the last snapshot (stored in /var/lib/aide/aide.db). In hostile environments, a good security measure is to keep the database file on a floppy disk, cdrom or external disk. If you have such a device, you can copy the current snapshot to it and use the snapshot from that device during later runs of aide.

Before making modifications to the configuration file, make a backup first:

$ sudo cp /etc/aide/aide.conf /etc/aide/aide.conf.old 

So let say that you have a copy of aide.db on an external disk. To use that snapshot, you can change database=file:/var/lib/aide/aide.db to database=file:/media/user/drive/aide/aide.db:

Aide2.png

Read through the file to acquaint yourself with aide. By default, changes in Binaries and Libraries directories are checked. Those are matched to the BinLib rule, which basically checks for any changes in permissions, ownership, modification, access and creation date, size change, md5 and sha1 signature, inode, number of links and block count. Then, it also checks for modifications in the log files against the rule Logs. Because log files tend to grow, you cannot use a signature there and you also have to ask aide not to check for size modification (S).

Usage

On debian alikes, aide is run on a daily basis through the script /etc/cron.daily/aide. Default settings in /etc/default/aide tells aide to update it's database. Using database_out value in /etc/aide/aide.conf, aide is going to output a new database any time it runs in /var/lib/aide/aide.db.new if you kept the default settings.

Any time you install new packages or change some configuration settings, run:

$ sudo /etc/cron.daily/aide

And check in the report that any modifications were only done to files you intended to modify and that added files are only coming from packages you have just installed and copy the new database to whatever place your database points to. Great way to learn about linux and non-intended changes too.

Installing rootkit scanners

A rootkit is a collection of tools a hacker installs on a victim's computer after gaining initial access. It generally consists of network sniffers, log-cleaning scripts, and trojaned replacements of core system utilities such as ps, netstat, ifconfig, and killall. Most times they are self-hiding toolkits to avoid the eye of the sysadmin. Applications that are used to detect rootkits are known as rootkit scanners. There are two rootkit scanners that are important to have on your linux box: rkhunter and chkrootkit. Both.

rkhunter

Rootkit Hunter (rkhunter) is a shell script to detect known rootkits or malware. It also performs checks to see if commands have been modified, and various checks on the network interfaces, including checks for listening applications.

Installing

You can install it from the Software Center or synaptic, or from the commandline:

$ sudo apt-get install rkhunter

Or you can get get it from http://sourceforge.net/projects/rkhunter/ or check current version number and use wget:

$ wget http://downloads.sourceforge.net/project/rkhunter/rkhunter/1.4.2/rkhunter-1.4.2.tar.gz

After download, extract the files and enter the resulting directory:

$ tar xzvf rkhunter*
$ cd rkhunter*

Run the install script:

$ sudo ./installer.sh --layout /usr --install
Rkhunter-running-install-script.png

Updating database

Update the rkhunter database:

$ sudo rkhunter --update

This command has to be run on a regular basis to keep the database of known rootkits current. You can use cron to schedule running of this command at regular intervals. See Running jobs, jobs, jobs! for more on running commands or scripts at a given date and time.

Update-rkhunter-db-and-baseline.png

Baselining

Set baseline file properties by checking the current values and storing them as known-good values:

$ sudo rkhunter --propupd

rkhunter is configured to be generic and each distro can (and most do) diverge from expected defaults. These appear during an initial run as false positives:

$ sudo rkhunter -c --enable all --disable none

You'll get groups of results, warnings, and at the end a summary of the results.

Rkhunter-first-run.png

You can have a look at more details of the warnings in /var/log/rkhunter.log.

$ sudo geany /var/log/rkhunter.log

I immediately encounter these noticeable two:

No-mail-on-warning.png
Package-manager.png

Sometimes if you change something, more warnings vanish or appear, so I always work on a few unrelated ones, then run --propupd and rkhunter -c again as shown above, until I no longer have warnings. Open up rkhunter's configuration file:

$ sudo geany /etc/rkhunter.conf

Remove the # in front of MAIL-ON-WARNING and replace the fake email adresses with your local mail account (see above):

Mail-on-warning.png

Likewise set the package manager:

Package-manager-set.png

I am also getting warnings from the deleted_files test:

Deleted-files.png

No problem. Mate and iceweasel need to be able to use tmp files. You can make the strings to allow processes using deleted files for in /etc/rkhunter.conf (on debian-based):

$ sudo awk '/Process: / {print "ALLOWPROCDELFILE="$3}' /var/log/rkhunter.log | sort -u
[sudo] password for user:
ALLOWPROCDELFILE=/usr/bin/mate-terminal
ALLOWPROCDELFILE=/usr/lib/iceweasel/iceweasel

Select and copy/paste the strings to the /etc/rkhunter.conf file (right-click mouse will give you the option to copy from command-line):

Allowprocdelfile.png

And a warning from the packet_cap_apps test:

Dhcpclient.png

Get the strings for allowing (current) packet capturing applications:

$ sudo awk -F"'" '/is listening on the network/ {print "ALLOWPROCLISTEN="$2}' /var/log/rkhunter.log
[sudo] password for user: 
ALLOWPROCLISTEN=/sbin/dhclient

and I only needed to comment it out:

Allowproclisten.png

A few suspicious files and a hidden dir from the filesystem test:

Suspicious-files-hidden-dirs.png

/dev/shm is an implementation of traditional shared memory concept for passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. Like a tmp file. A performance choice. /dev/shm/pulse-shm-0123456789 or whatever number seems not dangerous for the system. It's a clean install, and I'll whitelist it.

If I were to just add a line ALLOWDEVFILE=/dev/shm/pulse-shm-0123456789 to the rkhunter configuration file, this will stop the warning. Until I reboot. The numbers in the end of pulse-shm files change on every start and is unpredictable. This is where regular expressions and wildcards come in handy. As it is, it only needs commenting out:

Pulse-shm.png

The presence of the hidden /etc/.java directory also gives me a warning. So often do /dev/.udev, /dev/.static and /dev/.initramfs. These are known hidden (sofar) non-malignent hidden directories and can simply be whitelisted (only needs commenting out):

Java-hidden-dir.png

ALL GREEN. Purrrrfect baseline. For now. :) In the near future more applications may try to use deleted files, and after installation of applications more warnings may appear that I'll have to deal with to keep it green!

unhide

ACTUALLY, nearly all green and two purple:

Hidden-processes-skipped.png
Hidden-ports-skipped.png
  • unhide (ps) is for detecting hidden processes and implements six techniques:
    • Compare /proc vs /bin/ps output
    • Compare info gathered from /bin/ps with info gathered by walking through the procfs.
    • Compare info gathered from /bin/ps with info gathered from syscalls (syscall scanning).
    • Full PIDs space occupation (PIDs bruteforcing)
    • Reverse search, verify that all thread seen by ps are also seen by the kernel (/bin/ps output vs /proc, procfs walking and syscall)
    • Quick compare /proc, procfs walking and syscall vs /bin/ps output.
  • unhide-tcp is a forensic tool that identifies TCP/UDP ports that are listening but are not listed in /bin/netstat through brute forcing of all TCP/UDP ports available. It comes with unhide.
$ sudo apt-get install unhide
$ sudo rkhunter --propupd
$ sudo rkhunter -c --enable all --disable none

Now it's all green. :)

chkrootkit

chkrootkit is a shell script that checks system binaries for rootkit modification.

Installing

To install chkrootkit:

$ sudo apt-get install chkrootkit

Configuring

If you want an automatic daily run of chkrootkit, open /etc/chkrootkit.conf and replace RUN_DAILY="false" with RUN_DAILY="true"

$ sudo geany /etc/chkrootkit.conf
Chkrootkit-config.png

Usage

Using chkrootkit (perform all tests):

$ sudo chkrootkit

Managing passwords

Using a password manager allows you to load passwords in your clipboard, making it hard to catch it with a keylogger (just in case). And all good password managers allow you to generate passwords, making the passwords independent from your personal preferences and harder to crack. One of the easiest password managers is a GUI tool called keepassx:

$ sudo apt-get install keepassx

It will appear in your menu. A "first steps" tutorial can be found here http://keepass.info/help/base/firststeps.html

Recommendations:

  • Keep the database on a removable medium like an encrypted USB stick.
  • Use a second encrypted stick to keep a backup of that database on.
  • For added security, set up the database to use a password as well as a keyfile.
  • Try to always close off the application. It uses a lockfile to prevent access by other processes. Quitting the application removes it. If not, and whenever you get a message that you cannot open your database, check on the USB in the directory where the database resides that there isn't a lockfile blocking access. If there is a lockfile while the database is not open for you, just delete the lockfile.
  • On rare occasions a database is truly corrupted. That backup on that other stick, phew. :D

If you want to try your hand at cracking your own (current and new) passwords, try one of these http://sectools.org/tag/pass-audit/

Turning camera off

Yao-ming-meme-turning-on-the-webcam.jpg

Intruders can gain access to their victims’ computers with remote-access Trojans (RATs) – malware that gives an intruder administrative control over its targeted computers, including, in this case, the ability to remotely control webcams. It’s an invisibly-installed malware program spread via email attachment or by tricking victims into visiting a booby-trapped site.

Tape the camera. It may even be possible to turn it off in BIOS (depending on your version).

Better yet, if you know what driver module is controlling the webcam, you can disable the driver with modprobe -r.

Check with:

$ lsmod | grep "uvc"

If stuff like this appears, your webcam device uses an uvc driver http://www.ideasonboard.org/uvc/:

uvcvideo               79005  0 
videobuf2_vmalloc      12816  1 uvcvideo
videobuf2_core         47787  1 uvcvideo
videodev              126451  3 uvcvideo,v4l2_common,videobuf2_core
media                  18305  2 uvcvideo,videodev
usbcore               195340  7 uvcvideo,ums_realtek,usb_storage,ehci_hcd,ehci_pci,usbhid,xhci_hcd

To disable the cam:

$ sudo modprobe -r uvcvideo

To enable the cam:

$ sudo modprobe uvcvideo

If not an uvcvideo driver, try $ sudo lsmod | grep "media" and use the modinfo command to find out more about the modules listed behind it to locate your webcam driver module:

$ sudo modinfo [modulename]

Then replace the "uvcvideo" in the above modprobe command with the name of your driver module.

To disable the webcam at boot (if file not exists, create it):

$ sudo geany /etc/modprobe.d/blacklist.conf

At bottom of the file add this line: blacklist uvcvideo (or the name of your driver instead of "uvcvideo").

Save the file and reboot. Your webcam is no longer functioning.

Turning microphone off

Open the alsa control panel for muting the microphone:

$ sudo alsamixer

You can also use the same modprobe enabling/disabling method as used above for webcam. This page may be helpful for finding your driver module: http://alsa.opensrc.org/ALSA_modules.

Using a firewall

Gufw-mint.png

With a firewall, you can:

  • Log hosts scanning services that aren't running
  • Limit the services that programs can connect to
  • Segregate the local network into trust segments (LAN, DMZ, and Internet)
  • Redirect ports to the hosts providing the service (NAT).

If you have a single machine at home, only the first two are of interest. These are also the two that are most likely to cause issues for a beginning user.

ufw and gufw

Enabling

Mint and ubuntu come with a firewall installed, but it is disabled. Usually it's better to turn it on. Especially on mobile devices like laptops, which sometimes connect to other networks than your own.

The firewall is called ufw (uncomplicated firewall), and can be operated from the terminal (Menu > Accessories > Terminal):

$ sudo ufw enable

Type your password when prompted for it; this will remain entirely invisible, not even asterisks will show, which is normal.

Ufw has a sensible set of default settings (profile), which are fine for the vast majority of home users. So unless you have special wishes: you're done!

Checking status

You can check the status of the firewall with this command:

$ sudo ufw status verbose

If you wish, you can install a GUI frontend to ufw, called gufw:

$ sudo apt-get install gufw

And it'll be in your menu items (the icon in mint is a brick wall).

Safer browsing

It is clear that browsing has the most low cost attack vectors for data theft by hackers, tracking by corporations and for governmental spying. Safer browsing is a good investment all around.

Always use a GNU free software browser. This ensures it can be freely audited. Doesn’t mean it is audited or reviewed. Check for that.

Settings

For disabling flash:

  • Firefox: Add-ons > Plugins > Flash > Never Activate.
  • Chromium: Settings > Show advanced settings… > Content settings > Do not run plugins by default.

For disabling java:

  • Firefox: Add-ons > Plugins > Java > Never Activate.
  • Chromium: Settings > Show advanced settings… > Content settings > Do not run plugins by default.

Extensions

The NoScript Firefox extension provides extra protection for Firefox, Seamonkey and other mozilla-based browsers: this add-on allows JavaScript, Java, Flash and other plugins to be executed only by trusted web sites of your choice (e.g. your online bank) http://noscript.net/. There is mozilla talk of “adding NoScript functionality into the core browser”.

The closest Extension to NoScript that I have found for Chromium is ScriptSafe, which has certain operational differences: Apparently ScriptSafe acts more stringently concerning components of Web pages compared to NoScript.

HTTP Switchboard is a scriptblocker AND an adblocker. It is no longer developed. The project has split into two distinct, more advanced extensions: uBlock Origin and uMatrix.

Using removable storage media

A simple but straightforward security method is to keep all sensitive information on removable storage media like portable flash memory drives or external hard drives that you only mount the device when you need access to it.

You can turn old harddrives into external harddrives by taking them out of an old PC and putting them in a portable HDD USB storage kit (alias harddrive enclosure). These "DIY" kits are available for 2.5 inch and 3.5 inch HDD using either IDE or SATA connections and cost way less than a manufactured USB HDD.

You can check state, and turn write protect of a drive (or USB stick) on and off (during initialization and updates) with hdparm http://linux.die.net/man/8/hdparm

You may have a permission problem accessing it. If so, change the group of /media/[externaldisk] to storage, change permissions to 775 and add users that need to be able to write to disk to the storage group (re-login required before changes are visible).

As root (or use sudo) do:

# chgrp storage /media/[externaldisk]
# chmod 775 /media/[externaldisk]
# gpasswd -a [user] storage

This way everyone will be able to read the disk, but only root and users in storage group will be able to write to it. If you want everyone to be able to read/write, use chmod 777. If the operation isn't permitted while running it as root you probably need to add support for the NTFS file system first:

# apt-get update
# apt-get install ntfs-3g

But the most popular forms of security all rely on encryption, the process of encoding information in such a way that only the person (or computer) with the key can decode it. Or maybe others can for some forms of encryption. Or can soon?

Encryption

For an overview of encryption concepts see encrypting everything and for application of concepts in useful tools, see object encryption on linux and anonymising your traffic with linux.

Making backups

Data backups were traditionally done by commands to archive and compress files to backup, then writing that backup archive to tape. Tape archiving has been replaced by backing up data over the network, to other hard disks, CD's, DVD's and other low-cost removable media.

Archiving and compressing

Linux offers separate tools for gathering groups of files into a single archive and compressing that archive for efficient storage. Oh yuk, "efficient", oh well. It's about using less disk space and reducing transfer times over networks. And comes at a price. It can increase your CPU usage.

tar

You can combine archiving and compressing together by using additional options to the tar (tape archiver) command. Tar can behave differently on different distros. The manual page contains descriptions of the myriad of features that come with tar. The basic operations of tar:

  • Create a backup archive: c
  • Extract files from an archive: x
  • Compare differences between archives: d
  • Update files in an archive: u
  • Append files: r or A
  • Delete files from an existing archive: d
  • List contents of an archive: t

When creating a tar archive, you can add options that compress the resulting archive. With j the archive will be compressed in bzip2 format, and with z in gzip format. For example, tar with bzip2 compression:

$ tar xjvf funnybusiness.tar.bz2 *.txt

You can also use other compression mechanisms like lzop with tar. It is faster, but the compression is less than with bzip2 which is around 10 times slower while only giving twice the amount of compression. You can also set the compression level in the compression commands themselves.

gzip

Gzip compress the size of the given files using Lempel-Ziv coding (LZ77). Whenever possible, each file is replaced by one with the extension .gz. For more on how it works, see https://en.wikipedia.org/wiki/DEFLATE

Compress a file:

$ gzip funnybusiness.txt

Compress all images with a .jpg extension in a directory:

$ gzip *.jpg

Compress all files in a directory:

$ gzip -rv [directory]

Test integrity of a gzip compressed file:

$ gzip -tv funnybusiness.gz

To uncompress a compressed file:

$ gunzip -v funnybusiness.gz

Fastest compression time, least compression:

$ gzip -1 funnybusiness.gz

Slowest compression time, most compression:

$ gzip -9 funnybusiness.gz

bzip2

bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm and Huffman coding. Compression is generally considerably better than that achieved by bzip command (LZ77/LZ78-based compressors). Whenever possible, each file is replaced by one with the extension .bz2.

$ bzip2 [filename]

Uncompress:

$ bunzip [filename].bz2

lzop

lzop uses the LZO data compression library for compression services, and its main advantages over gzip are much higher compression and decompression speed (at the cost of some compression ratio). lzop is copyrighted under the terms of the GNU General Public License (GPL). More on http://www.lzop.org/

You will probably have to install it first:

$ sudo apt-get install lzop

Compress:

$ lzop [filename]

Unlike gzip and bzip2, lzop has no separate command for unlzopping. NO UNLZOPPING! Use the d option:

$ lzop -dv [filename].lzo

Backing up files

Data backup is something that everybody should do, but unfortunately, few people do it on a regular basis. You can make a backup of your entire system with rsync or with unison.

rsync

rsync (remote sync), is a remote and local file synchronisation tool. It uses an algorithm that minimises the amount of data copied by only moving the portions of files that have changed. It operates in a way similar to ssh, scp, and cp, for example:

$ rsync -a [directoryname]/ /media/[pathtoexternaldisk]/[directoryname]

The a option is a combination flag. It stands for "archive" and syncs recursively and preserves symbolic links, special and device files, modification times, group, owner, and permissions. Rsync can be used for a lot more in many different ways http://www.thegeekstuff.com/2010/09/rsync-command-examples/.

unison

unison allows for accessing the same set of files from any computer (running Mac OS X, M$ Windows XP, or UNIX/Linux) and keeps these files up-to-date by always maintaining the most recently-modified version of each file during synchronization. The great benefit of using unison to replicate files across different computers (servers) is that your backups are alive http://www.cis.upenn.edu/~bcpierce/unison/.

Traffic monitoring

wireshark

Wireshark lets you capture and interactively browse the traffic running on a computer network.

Installing

$ sudo apt-get install wireshark

Choose YES if you want to capture packets as user:

Configuring-wireshark-common.png

You will also need to allow non-root users to capture packets. For that, follow the procedure described in /usr/share/doc/wireshark-common/README.Debian:

$ sudo adduser user wireshark

Capturing packets

You can launch it and click the name of an interface under Interface List to start capturing packets on that interface. For example, if you want to capture traffic on the wireless network, click your wireless interface. You can configure advanced features by clicking Capture Options:

Configure sysctl (*)

Audit your setup

Resources

General

Debian

Ubuntu

Mint

Related