Difference between revisions of "Linux security"

From Gender and Tech Resources

m (Usage)
m (Capturing packets)
Line 552: Line 552:
 
[[File:Stop-capture.png|840px|thumb|center]]
 
[[File:Stop-capture.png|840px|thumb|center]]
  
For examples of its use, see [[Anonymising your traffic with linux]]. If there’s nothing interesting on your own network to inspect, Wireshark’s wiki has you covered. The wiki contains a page of sample capture files that you can load and inspect https://wiki.wireshark.org/SampleCaptures. To open a capture file, click ''Open'' on the main screen and browse for a file. You can also save your own captures saved and open them later.
+
For examples of its use, see [[Anonymising your traffic with linux]]. If there’s nothing interesting on your own network to inspect, Wireshark’s wiki has you covered. The wiki contains a page of sample capture files that you can load and inspect https://wiki.wireshark.org/SampleCaptures. To open a capture file, click ''Open'' on the main screen and browse for a file. You can also save your own captures and open them later.
  
 
==== Filtering packets ====
 
==== Filtering packets ====

Revision as of 18:46, 13 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.

tripwire

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).

Rules

Found a pretty good no-nonsense tutorial here https://help.ubuntu.com/community/UFW

iptables and netfilter

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 and can be used to debug network protocol implementations, examine security problems and inspect network protocol internals. See networking concepts.

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:

Interface-list.png

You can configure advanced features by clicking Capture Options:

Capture-options.png

As soon as you click Start, you’ll see the packets start to appear in real time. Wireshark captures each packet sent to or from your system. If you’re capturing on a wireless interface and have promiscuous mode enabled in your capture options, you’ll also see other the other packets on the network.

Click the stop capture button near the top left corner of the window when you want to stop capturing traffic.

Stop-capture.png

For examples of its use, see Anonymising your traffic with linux. If there’s nothing interesting on your own network to inspect, Wireshark’s wiki has you covered. The wiki contains a page of sample capture files that you can load and inspect https://wiki.wireshark.org/SampleCaptures. To open a capture file, click Open on the main screen and browse for a file. You can also save your own captures and open them later.

Filtering packets

If you’re trying to inspect something specific, such as the traffic a program sends, it helps to close down all other applications using the network so you can narrow down the traffic. Still, you’ll likely have a large amount of packets to sift through. That’s where filtering come in.

The most basic way to apply a filter is by typing it into the filter box at the top of the window and clicking Apply. For example, type dns and you’ll see only DNS packets.

Filtering.png

Another interesting thing you can do is right-click a packet and select Follow TCP, UDP or SSL Stream.

Inspecting packets

Click a packet to select it and you can dig down to view its details. You can also create filters by using the Apply as Filter submenu to create a filter based on it (those ands and ors are boolean algebra):

Set-filter-based-on-packet.png

Configuring sysctl (*)

sysctl is a tool for examining and changing kernel parameters at runtime, a near-necessary tool in the defense from malware.

$ sudo geany /etc/sysctl.conf

For now it is naught more than removing a few comment-out chars and adding a few lines:

#
# /etc/sysctl.conf - Configuration file for setting system variables
# See /etc/sysctl.d/ for additonal system variables
# See sysctl.conf (5) for information.
#

#kernel.domainname = example.com

# Uncomment the following to stop low-level messages on console
#kernel.printk = 3 4 1 3

##############################################################3
# Functions previously found in netbase
#

# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
net.ipv4.conf.default.rp_filter=1
net.ipv4.conf.all.rp_filter=1

# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
net.ipv4.tcp_syncookies=1

# Uncomment the next line to enable packet forwarding for IPv4
#net.ipv4.ip_forward=1

# Uncomment the next line to enable packet forwarding for IPv6
#  Enabling this option disables Stateless Address Autoconfiguration
#  based on Router Advertisements for this host
#net.ipv6.conf.all.forwarding=1

###################################################################
# Additional settings - these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
#
# Log Martian Packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

See resources below.

Auditing your setup

Look-at-all-the-fucks-i-give.jpg

Tiger

Tiger supports multiple UNIX platforms it is free and provided under a GPL license. Tiger is used as a security audit and is useful both for system analysis (security auditing) and for real-time, host-based intrusion detection. More on its history and resurrection here http://digital-era.net/setting-up-and-using-tiger-for-security-audit-and-intrusion-detection/.

It consists of Bourne Shell scripts, C code and data files used for checking for security problems on a UNIX system. It scans system configuration files, file systems, and user configuration files for possible security problems and creates a report on issues found.

Installing

$ sudo apt-get install tiger

Configuring

  • You can mess with the tiger variables in the /etc/tiger/tigerrc configuration file. For each available module there is a corresponding variable in the file that determines whether the module is run. A variable can be set equal to Y to run, or N to skip. Other configuration variables will modify the behaviour of some modules, and can be adjusted based on the operating system.
  • The /etc/tiger/tiger.ignore configuration file defines the set of messages that will not be presented in the report even if any of the modules generate them. All entries (per line) are used as extended regular expressions that are compared against each message (mind the overhead which grows with the size of the file).

Usage

The command tig‐exp(8) can be used to obtain explanations of the problems reported by tiger. Doing a first run can be shocking (not boring). For all listed fixes below the explanations are included.

Checking passwd files:

--WARN-- [pass014w] Login (name) is disabled, but has a valid shell.

The listed login ID is disabled in some manner (‘*’ in passwd field, etc), but the login shell for the login ID is a valid shell (from /etc/shells or the system equivalent). A valid shell can potentially enable the login ID to continue to be used. An attacker can hide programs within these shells by simply ‘su’ing into these accounts.

Debian comes with some predefined users (https://www.debian.org/doc/manuals/securing-debian-howto/ch12.en.html#s-faq-os-users) listed in /etc/passwd:

  • The default behavior is that UID’s from 0 to 99 are reserved in Debian (https://www.debian.org/doc/debian-policy/) to ease the installation of some services that require that they run under an appropriate user/UID. If you do not intend to install these services, you can safely remove those users who do not own any files in your system and do not run any services.
  • UID’s from 100 to 999 are created by packages on install (and deleted when the package is purged). Some of the accounts in this range are users linked to programs you’re running. In general, it is better to prune your system via the associated packages than try to manage them manually.
  • Manually created users end up with a UID just above 1000 (unless you manually specified the uid).

For example www-data in most cases, does not need a shell, but some cgi could need it. Historically all users under UID 99 had a /bin/sh as login shell, and the ones found and listed here by tiger are historic or legacy users, for all “modern” linux services already come preconfigured to /bin/false. For those not preconfigured, you can dig into your system to know what each user does there:

  • Do a top or a ps -aux and check the users; if there’s a process started by “nobody” user you can’t delete it.
  • Also check crontab and cron.d; if you delete a user required for starting a cron job, that job will never work again.
  • Another useful check is to check the /etc/shadow file and see which second fields are X (crossed out) for which accounts.

If you conclude a process shouldn’t be there, then stop the daemons, uninstall its packages, and then delete the users. If you are unsure about deleting a user used as administrative user you can set its shell to /bin/false or /sbin/nologin (or something else that doesn’t exist). The user will remain there but nobody will get a shell from it.

Always leave the shell for your user and root user. Whatever you do, do NOT remove or change the shell for root.

--WARN--­­ [pass015w] Login ID sync does not have a valid shell (/bin/sync)

The listed login ID does not have a valid login program or shell. Usually these Shells are defined in /etc/shells.

This is a special case in which there is not a valid shell for sync. /bin/sync is a valid file with a valid purpose. You can ignore.

--WARN­­-- [pass006w] Integrity of password files questionable (/usr/sbin/pwck ­r).

The password files have integrity issues as found by pwck -r http://www.sanfoundry.com/pwck-command-usage/. This can lead to looping of password manipulation programs and to authentication or login issues if not corrected. Install the relevant packages or create the directory and set permissions for only limited access.

$ sudo /usr/sbin/pwck -r

Checking user accounts:

--WARN­­-- [acc022w] Login ID nobody home directory (/nonexistent) is not accessible.

But without a valid home directory, the user could end up with / as the home directory. You can disable his shell in /etc/passwd by setting it to /bin/false or /sbin/nologin and ignore the resulting error, or you can create the directory, change its ownership and persmissions.

$ sudo mkdir /nonexistent
$ chown nobody:nobody /nonexistent
$ chmod 400 /nonexistent

Checking cron entries:

Cron allows users to submit jobs for the system to do at a particular, possibly recurring time. It can be very useful, but also has a very real potential for abuse by either users or system crackers. Users can be restricted to use cron by creating a /etc/cron.allow (holding only system administrators) or a /etc/cron.deny file (listing which users are not allowed access).

--WARN-- [cron004w] Root crontab does not exist

Not a problem. Ignore.

--WARN-- [cron005w] Use of cron is not restricted

For standard Debian systems, all users may use this command. Use the fix on Linux/UNIX Restricting at/cron Usage To Authorized Users here http://www.cyberciti.biz/faq/howto-restrict-at-cron-command-to-authorized-users/ or ignore.

Checking services:

--WARN--­­ [inet003w] The port for service (x) is also assigned to service (y)

A program with a port assigned to TCP and a second entry for the same port with UDP. These service ports are defined in /etc/services and double entries is quite normal (it is about synonyms). You can just ignore or review these and make sure they are all synonyms and you don’t have two very different programs accessing the same port. Check the /etc/services file against the file the official assigning authority provides. Review open ports and if any, either uninstall or disable services you don’t use or want. Be careful.

Checking system file permissions:

--ALERT-- [perm023a] /bin/su is setuid to `root'

The explanation of tiger reads: The indicated file has the setuid bit set, but it should not have it. This should be changed by using chmod u-s file where ‘file’ is the indicated file. The system should be checked for signs of intrusion.

Restricting the su command to superuser only in Linux (http://www.debianadmin.com/howto-restrict-su-command-to-superuser-only-in-linux.html) can affect some apps and packages that link to suid rooted su binary. For example, on debian it leads to an authentication failure when ‘su’ing in console or terminal of a user. My recommendation is to ignore this and those like it. You also don’t, for example, want to remove the suid bit from /usr/bin/passwd, for if you do no user will be able to change password.

Everything from /bin/, /sbin/, /usr/bin and /usr/sbin should be safe, they are part of the base OS. The most common reason for any program to be setuid is to enable it to act as root (setuid root) for access to hardware, secure storage, devices …

AND any vulnerability in a program that is set up as setuid root can get an attacker root-level access to your box, by running the command as a regular user (privilege escalation). If you can avoid it (or doing so is inconvenient or opens up other holes or cans of worms and authentication failures), you don’t want things to run setuid root.

If you are mounting shares that have setuid root files on them that were created by a user on another box, they can be used to own your box. There are options to mount such shares no-setuid – so the setuid bit on files will be ignored on that filesystem.

In particular, you don’t want files that are setuid to be writable by non-root users, otherwise someone could replace them with malicious code that will then be executed as root.

If you find setuid binaries in non-binary filesystem locations (especially in for example /tmp or anywhere under /var) whose origins are unknown you may have been hacked. A setuid enabled binary for root under /home/username/crack smells definitely fishy.

You can find all files (in /usr/local/bin) with S_ISUID bit set with:

$ sudo find /usr/local/bin -perm +4000

And all files with S_ISUID and that are writable by owner with:

$ sudo find /usr/local/bin -perm -4200

Checking network configuration:

--WARN-- [lin017w] The system is not configured to log suspicious (martian) packets

Fix with:

$ sudo sysctl ­w net.ipv4.conf.all.log_martians=1
$ sudo sysctl ­w net.ipv4.conf.default.log_martians=1

Yes, yes, I had forgotten those default versions. Also corrected above.

Resources

General

Debian

Ubuntu

Mint

Sysctl

Related