Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Wednesday, May 22, 2013

How to Block DOS or limit traffic on DNS and Log the activity



Step1:
Add the below entry in syslog to log the iptables activity in to seperate file.

kern.*                                                 /var/log/firewall.log

Restart the syslog service.

Step2:
Limit the traffic in single second.

# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --set --name DNSQF --rsource

"If a new traffic from a source hits at destination port #53 This rule will log the source IP to the list called DNSQF"  Increase the hitcounter value in kernel
 chmod 600 /sys/module/xt_recent/parameters/ip_pkt_list_tot
 echo 200 > /sys/module/xt_recent/parameters/ip_pkt_list_tot
 chmod 400  /sys/module/xt_recent/parameters/ip_pkt_list_tot


Below rule logs and blocks the traffic hitting the threshold
# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --update --seconds 1 --hitcount "30" --name DNSQF --rsource -j LOG
# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --update --seconds 1 --hitcount "30" --name DNSQF --rsource -j DROP


" If a new traffic from a source hitting port 53 exceeds the number "30" in one second, it will be Logged and then Dropped."  
Step3:
 Limit the traffic in 5 Sec (Backup rule)

# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --set --name DNSHF --rsource

Hit counter is already set in above step so below command should work without any error


# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --update --seconds 5 --hitcount "150" --name DNSHF --rsource -j LOG
# iptables -A INPUT -p tcp --dport 53 -m state --state NEW -m recent --update --seconds 5 --hitcount "150" --name DNSHF --rsource -j DROP

Any traffic hitting the rule will be logged to the file /var/log/firewall.log  or can use below command
#iptables -L -n -v

Thursday, November 10, 2011

Password policy rules in Linux


Setting up stronger password policy rules in Linux

Increased password security is no longer an optional item in setting up a secure system.  Many external organizations (such as PCI) are now mandating security policies that can have a direct effect on your systems.  By default, the account and password restrictions enabled on a Linux box are minimal at best.  To better secure your hosts and meet those requirements from external vendors and organizations, here’s a small how-to on setting up stronger password and account policies in Linux.  This is targeted at RHEL so other distributions may or may not be 100% compatible.

As an example, let us assume that our security department has created an account security policy document.  This document identifies both account and password restrictions that are now going to be required for all accounts both existing and new.
The document states that passwords must:
  • Be at least 8 characters long.
  • Use of at least one upper case character.
  • Use of at least one lower case character.
  • Use of at least one special character (!,@#$%, etc)
  • Warn 7 days prior to expiration.
  • Expire after 90 days 
  • Lock after 97 days.
The good news is that Linux has all of these features and can be setup to meet the requirements given to us.  Unfortunately though, Linux doesn’t have all this information located in one central place. If you’re not using the RedHat supplied redhat-config-users GUI, you’re going to have to make the changes manually.  Since our server systems don’t run X, we will be making the changes directly to the system without the help of the GUI.
In RHEL, changes are made in multiple locations.  They are:
  • /etc/pam.d/system-auth
  • /etc/login.defs
  • /etc/default/useradd
In Linux, password changes are passed through PAM. To satisfy the first three requirements we must modify the PAM entry that corresponds with passwords. /etc/pam.d/system-auth is the PAM file responsible for authentication and where we will make our first modifications. Inside /etc/pam.d/system-auth there are entries based on a “type” that the rules apply to. As we are only discussing password rules, you will see a password type.

password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3
The password type is “required for updating the authentication token associated with the user.” Simply put, we need a password type to update the password. Looking at the example, we can see that pam_cracklib is the default module that is responsible for this operation. To configure pam_cracklib to meet our specifications we need to modify the line accordingly:
  • Minimum of 8 characters: minlen=8
  • At least one upper case character: ucredit=-1
  • At least one lower case character: lcredit=-1
  • At least one special character: ocredit=-1
Our /etc/pam.d/system-auth will now look like this:

#password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3
password    requisite     /lib/security/$ISA/pam_cracklib.so retry=3 minlen=8 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
If you are curious as to how pam_cracklib defines and uses credits, check the link above to the pam_cracklib module page. Next, to meet the requirement to have passwords expire after 90 days, we need to modify the /etc/login.defs file.
# Password aging controls:
# # PASS_MAX_DAYS Maximum number of days a password may be used. # PASS_MIN_DAYS Minimum number of days allowed between password changes. # PASS_MIN_LEN Minimum acceptable password length. # PASS_WARN_AGE Number of days warning given before a password expires. # PASS_MAX_DAYS 90 PASS_MIN_DAYS 0 PASS_MIN_LEN 8 PASS_WARN_AGE 7
Notice how the PASS_MIN_LEN is also set here as well. Since we have been given some latitude on when to warn users we have chosen to warn users seven days prior to expiration. But our last item is curiously missing. Where do we set up the accounts so that after 97 days the account is locked out and requires a system administrator to unlock?
Believe it or not useradd controls the initial locking of an account. Issuing a useradd -D will show you the current default paramters that are used when useradd is invoked.

[root@host ~]# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
The INACTIVE=-1 entry defines when an account will be deactivated. Inactive is defined as the, “number of days after a password has expired before the account will be disabled.” Our requirements state that the account should be disabled seven days after account expiration. To set this we can either:

  • Invoke useradd -D -f 7
  • Modify /etc/default/useradd and change the INACTIVE entry.
Just remember that an inactive or disabled account is a locked account whereas an expired account is not locked. With this last change, all of the requirements that have been given to us have been met. We modified the password rules for all new passwords, and setup the system to activate password aging as well as configure the system to disable an account if necessary. But one issue remains — if this is not a new system what happens to all existing account? The answer is nothing.
In the next installment I’ll show you how to make our modifications effective on existing user accounts…

Monday, October 24, 2011

How To Disable SSH Host Key Checking


Remote login using the SSH protocol is a frequent activity in today's internet world. With the SSH protocol, the onus is on the SSH client to verify the identity of the host to which it is connecting. The host identify is established by its SSH host key. Typically, the host key is auto-created during initial SSH installation setup.

By default, the SSH client verifies the host key against a local file containing known, rustworthy machines. This provides protection against possible Man-In-The-Middle attacks. However, there are situations in which you want to bypass this verification step. This article explains how to disable host key checking using OpenSSH, a popular Free and Open-Source implementation of SSH.

When you login to a remote host for the first time, the remote host's host key is most likely unknown to the SSH client. The default behavior is to ask the user to confirm the fingerprint of the host key.
$ ssh peter@192.168.0.100
The authenticity of host '192.168.0.100 (192.168.0.100)' can't be established.
RSA key fingerprint is 3f:1b:f4:bd:c5:aa:c1:1f:bf:4e:2e:cf:53:fa:d8:59.
Are you sure you want to continue connecting (yes/no)? 

If your answer is yes, the SSH client continues login, and stores the host key locally in the file ~/.ssh/known_hosts. You only need to validate the host key the first time around: in subsequent logins, you will not be prompted to confirm it again.

Yet, from time to time, when you try to remote login to the same host from the same origin, you may be refused with the following warning message:
$ ssh peter@192.168.0.100
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
3f:1b:f4:bd:c5:aa:c1:1f:bf:4e:2e:cf:53:fa:d8:59.
Please contact your system administrator.
Add correct host key in /home/peter/.ssh/known_hosts to get rid of this message.
Offending key in /home/peter/.ssh/known_hosts:3
RSA host key for 192.168.0.100 has changed and you have requested strict checking.
Host key verification failed.$

There are multiple possible reasons why the remote host key changed. A Man-in-the-Middle attack is only one possible reason. Other possible reasons include:
  • OpenSSH was re-installed on the remote host but, for whatever reason, the original host key was not restored.
  • The remote host was replaced legitimately by another machine.

If you are sure that this is harmless, you can use either 1 of 2 methods below to trick openSSH to let you login. But be warned that you have become vulnerable to man-in-the-middle attacks.

The first method is to remove the remote host from the~/.ssh/known_hosts file. Note that the warning message already tells you the line number in the known_hosts file that corresponds to the target remote host. The offending line in the above example is line 3("Offending key in /home/peter/.ssh/known_hosts:3")

You can use the following one liner to remove that one line (line 3) from the file.
$ sed -i 3d ~/.ssh/known_hosts

Note that with the above method, you will be prompted to confirm the host key fingerprint when you run ssh to login.

The second method uses two openSSH parameters:
  • StrictHostKeyCheckin, and
  • UserKnownHostsFile.

This method tricks SSH by configuring it to use an emptyknown_hosts file, and NOT to ask you to confirm the remote host identity key.
$ ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no peter@192.168.0.100
Warning: Permanently added '192.168.0.100' (RSA) to the list of known hosts.
peter@192.168.0.100's password:

The UserKnownHostsFile parameter specifies the database file to use for storing the user host keys (default is ~/.ssh/known_hosts).

The /dev/null file is a special system device file that discards anything and everything written to it, and when used as the input file, returns End Of File immediately.

By configuring the null device file as the host key database, SSH is fooled into thinking that the SSH client has never connected to any SSH server before, and so will never run into a mismatched host key.

The parameter StrictHostKeyChecking specifies if SSH will automatically add new host keys to the host key database file. By setting it to no, the host key is automatically added, without user confirmation, for all first-time connection. Because of the null key database file, all connection is viewed as the first-time for any SSH server host. Therefore, the host key is automatically added to the host key database with no user confirmation. Writing the key to the/dev/null file discards the key and reports success.

Please refer to this excellent article about host keys and key checking.

By specifying the above 2 SSH options on the command line, you can bypass host key checking for that particular SSH login. If you want to bypass host key checking on a permanent basis, you need to specify those same options in the SSH configuration file.

You can edit the global SSH configuration file (/etc/ssh/ssh_config) if you want to make the changes permanent for all users.

If you want to target a particular user, modify the user-specific SSH configuration file (~/.ssh/config). The instructions below apply to both files.

Suppose you want to bypass key checking for a particular subnet (192.168.0.0/24).

Add the following lines to the beginning of the SSH configuration file.
Host 192.168.0.*
   StrictHostKeyChecking no
   UserKnownHostsFile=/dev/null

Note that the configuration file should have a line like Host * followed by one or more parameter-value pairs. Host *means that it will match any host. Essentially, the parameters following Host * are the general defaults. Because the first matched value for each SSH parameter is used, you want to add the host-specific or subnet-specific parameters to the beginning of the file.

As a final word of caution, unless you know what you are doing, it is probably best to bypass key checking on a case by case basis, rather than making blanket permanent changes to the SSH configuration files.


Refer & Thanks to: http://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html

Wednesday, October 5, 2011

Hints on how to check your machine for intrusion



The compromise of kernel.org and related machines has made it clear that
some developers, at least, have had their systems penetrated.  As we
seek to secure our infrastructure, it is imperative that nobody falls
victim to the belief that it cannot happen to them.  We all need to
check our systems for intrusions.  Here are some helpful hints as
proposed by a number of developers on how to check to see if your Linux
machine might be infected with something:


0. One way to be sure that your system is not compromised is to simply
   do a clean install; we can all benefit from a new start sometimes.
   Before reinstalling any systems, though, consider following the steps
   below to learn if your system has been hit or not.

1. Install the chkrootkit package from your distro repository and see if it
   reports anything.  If your distro doesn't have the chkroot package,
   download it from:
 http://www.chkrootkit.org/

   Another tool is the ossec-rootcheck tool which can be found at:
 http://www.ossec.net/main/rootcheck

   And another one is the rkhunter program:
    http://www.rootkit.nl/projects/rootkit_hunter.html
   [Note, this tool has the tendancy to give false-positives on some
   Debian boxes, please read /usr/share/doc/rkhunter/README.Debian.gz if
   you run this on a Debian machine]

2. Verify that your package signatures match what your package manager thinks
   they are.

   To do this on a rpm-based system, run the following command:
    rpm --verify --all
   Please read the rpm man page for information on how to interpret the
   output of this command.

   To do this on a Debian based system, run the following bash snippet:
 dpkg -l \*|while read s n rest; do if [ "$s" == "ii" ]; then echo $n;
 fi; done > ~/tmp.txt
 for f in `cat ~/tmp.txt`; do debsums -s -a $f; done
   If you have a source-based system (Gentoo, LFS, etc.) you presumably
   know what you are doing already.

3. Verify that your packages are really signed with the distro's keys.

   Here's a bash snippet that can do this on a rpm based system to
   verify that the packages are signed with any key, not necessarily
   your distro's key.  That exercise is left for the reader:

 for package in `rpm -qa`; do
  sig=`rpm -q --qf '%{SIGPGP:pgpsig}\n' $package`
  if [ -z "$sig" ] ; then
   # check if there is a GPG key, not a PGP one
   sig=`rpm -q --qf '%{SIGGPG:pgpsig}\n' $package`
   if [ -z "$sig" ] ; then
    echo "$package does not have a signature!!!"
   fi
  fi
 done
   Unfortunately there is no known way of verifying this on Debian-based
   systems.

4. To replace a package that you find suspect, uninstall it and install
   it anew from your distro.  For example, if you want to reinstall the
   ssh daemon, you would do:
 $ /etc/init.d/sshd stop
 rpm -e openssh
 zypper install openssh # for openSUSE based systems
 yum install openssh # for Fedora based systems

   Ideally do this from a live cdrom boot, using the 'rpm --root' option
   to point rpm at the correct location.


5. From a liveCD environment, look for traces such as:
   a. Rogue startup scripts in /etc/rc*.d and equivalent directories.
   b. Strange directories in /usr/share that do not belong to a package.
      This can be checked on an rpm system with the following bash snippet:
 for file in `find /usr/share/`; do
  package=`rpm -qf -- ${file} | grep "is not owned"`
  if [ -n "$package" ] ; then
   echo "weird file ${file}, please check this out"
  fi
 done
6. Look for mysterious log messages, such as:
   a. Unexpected logins in wtmp and /var/log/secure*, quite possibly
      from legitimate users from unexpected hosts.
   b. Any program trying to touch /dev/mem.
   c. References to strange (non-text) ssh version strings in
      /var/log/secure*.  These do not necessarily indicate *successful*
      breakins, but they indicate *attempted* breakins which means your
      system or IP address has been targeted.

7. If any of the above steps show possible signs of compromise, you
   should investigate further and identify the actual cause.  If it
   becomes clear that the system has indeed been compromised, you should
   certainly reinstall the system from the beginning, and change your
   credentials on all machines that this machine would have had access
   to, or which you connected to through this machine.  You will need
   to check your other systems carefully, and you should almost
   certainly notify the administrators of other systems to which you
   have access.

Finally, please note that these hints are not guaranteed to turn up
signs of a compromised systems.  There are a lot of attackers out there;
some of them are rather more sophisticated than others.  You should
always be on the alert for any sort of unexpected behavior from the
systems you work with.
 
----------------------------------------------------------------------------
----------------------------------------------------------------------------
I would like to add here a few controls I ran on firewall and system logs,
that are easy to perform and which report few false positives :

  - check that communications between your local machines are expected ;
    for instance if you have an SSH bouncing machine, it probably receives
    tens of thousands of SSH connection attempts from outside every day,
    but it should never ever attempt to connect to another machine unless
    it's you who are doing it. So checking the firewall logs for SSH
    connections on port 22 from local machines should only report your
    activity (and nothing should happen when you sleep).

  - no SSH log should report failed connection attempts between your
    local machines (you do have your keys and remember your password).
    And if it happens from time to time (eg: user mismatch between
    machines), it should look normal to you. You should never observe
    a connection attempt for a user you're not familiar with (eg: admin).

     $ grep sshd /var/log/messages
     $ grep sshd /var/log/messages | grep 'Invalid user'
  - outgoing connections from your laptop, desktop or anything should
    never happen when you're not there, unless there is a well known
    reason (package updates, browser left open and refreshing ads). All
    unexpected activity should be analysed (eg: connections to port 80
    not coming from a browser should only match one distro mirror).
    This is particularly true for cheap appliances which become more
    and more common and are rarely secured. A NAS or media server, a
    switch, a WiFi router, etc... has no reason to ever connect anywhere
    without you being aware of it (eg: download a firmware update).

  - check for suspicious DNS requests from machines that are normally
    not accessed. A number of services perform DNS requests when
    connected to, in order to log a resolved address. If the machine
    was penetrated and the logs wiped, the DNS requests will probably
    still lie in the firewall logs. While there's nothing suspect from
    a machine that does tens of thousands DNS requests a day, one that
    does 10 might be suspect.

  - check for outgoing SMTP connections. Most machines probably never
    send any mail outside or route them through a specific relay. If
    one machine suddenly tries to send mails directly to the outside,
    it might be someone trying to steal some data (eg: mail ssh keys).

  - check for long holes in logs various service logs. The idea is that
    if a system was penetrated and the guy notices he left a number of
    traces, he will probably have wiped some logs. A simple way to check
    for this is to count the number of events per hour and observe huge
    variations. Eg:

       $ cut -c1-9 < /var/log/syslog |uniq -c
       8490 Oct  1 00
       7712 Oct  1 01
       8316 Oct  1 02
       6743 Oct  1 03
       7428 Oct  1 04
       7041 Oct  1 05
       7762 Oct  1 06
       6562 Oct  1 07
       7137 Oct  1 08
        160 Oct  1 09
    Activity looks normal here. Something like this however would be
    extremely suspect :

       8490 Oct  1 00
        712 Oct  1 01
       6743 Oct  1 03

  - check that you never observe in logs a local address that you
    don't know. For instance, if your reverse proxy is on a DMZ which
    is provided by the same physical switch as your LAN and your switch
    becomes ill and loses all its VLAN configuration, it them becomes
    easy to add an alias to the reverse-proxy to connect directly to
    LAN machines and bypass a firewall (and its logs).

  - it's always a good exercise to check for setuids on all your machines.
    You'll generally discover a number of things you did not even suspect
    existed and will likely want to remove them. For instance, my file
    server had dbus-daemon-launch-helper setuid root. I removed this crap
    as dbus has nothing to do on such a machine. Similarly I don't need
    fdmount to mount floppies. I might not use floppies often, and if I do,
    I know how to use sudo.

       $ find / -user root -perm -4000 -ls

  - last considerations to keep in mind is that machines which receive
    incoming connections from outside should never be able to go out, and
    should be isolated in their own LAN. It's not hard to do at all, and
    it massively limits the ability to bounce between systems and to steal
    information. It also makes firewall logs much more meaningful, provided
    they are stored on a support with limited access, of course :-)
 
 
 
Also refer: 
http://www.ossec.net/main/rootcheck
http://www.rootkit.nl/projects/rootkit_hunter.html
http://www.chkrootkit.org/ 

Sunday, December 26, 2010

Installing and configuring mod_security-Ubuntu 9.04


This how-to is reported to work in Ubuntu 8.04-10.10 as well.

What is mod_security you ask ?


Mod Security can significantly increase the security of your Apache installation.
 
What Is ModSecurity?

ModSecurity is a web application firewall that can work either embedded or as a reverse proxy. It provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis.

It is also an open source project that aims to make the web application firewall technology available to everyone.

Do not think you need this ? Follow along with the examples and decide for yourself (This tutorial assumes you already have Apache and php5 installed).
First, let us look at the default Apache behavior. I will use “ubuntuVPS” as the server of interest.

“Insecure” Example 1 – curl

Use curl to obtain information on the server (bodhi@home is a remote machine connecting to “ubutnuVPS”. You can test all this with any browser if you wish, simply use your server’s home page).
bodhi@home# curl -i ubuntuVPS
HTTP/1.1 200 OK
Date: Tue, 28 Apr 2009 22:06:21 GMT
Server: Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch
Last-Modified: Tue, 28 Apr 2009 21:39:54 GMT
ETag: "50d4a-2d-468a44dadbe80"
Accept-Ranges: bytes
Content-Length: 45
Vary: Accept-Encoding
Content-Type: text/html
< html>< body>< h1>It works!< /h1>< /body>< /html>

Looks like this in your browser (the famous It works! page)

See how with a single command we already know the server is Ubuntu running Apache 2.2.11 and PHP 5.2.6 ?

“Insecure” Example 2 – bad .php

For this I will ask you to create a file “/var/www/insecure.php”
Put the following code in the file :
# vim /var/www/insecure.php
< ? $secret_file = $_GET['secret_file'];
include ( $secret_file); ? >;

Note: I had to put a space at the front of the php tag “<; ?”, remove it.

Now what ? Open a browser and enter http://ubuntuVPS/insecure.php?secret_file=/etc/passwd

I shall use curl in this example:
bodhi@home# curl -i "http://ubuntuVPS/insecure.php?secret_file=/etc/passwd"
HTTP/1.1 200 OK
Date: Tue, 28 Apr 2009 22:24:11 GMT
Server: Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.1 with Suhosin-Patch
X-Powered-By: PHP/5.2.6-3ubuntu4.1
Vary: Accept-Encoding
Content-Length: 860
Content-Type: text/html
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
sshd:x:101:65534::/var/run/sshd:/usr/sbin/nologin
postfix:x:104:107::/var/spool/postfix:/bin/false

YIKES !!!

Install and configure mod_secure

There was a time when installing mod_security was a bit difficult, now it is as easy as :
sudo apt-get -y install libapache-mod-security
The “hard part” is that we need to configure mod_security and obtain a few rules.

Configure mod_security

Using any editor, make a file “/etc/apache2/conf.d/modsecurity2.conf” and put the following contents in the file.
#vim /etc/apache2/conf.d/modsecurity2.conf
< ifmodule mod_security2.c>
Include conf.d/modsecurity/*.conf
< /ifmodule>

Note: I had to add a space at the front of the tag “< ifmodule mod_security2.c>” and “< /ifmodule>”, remove them.

By default, mod_security logs to /etc/apache2/logs, the following commands will put the log in /var/log/apache2/mod_security and create a symbolic link back to /etc/apache2/logs

sudo mkdir /var/log/apache2/mod_security
sudo ln -s /var/log/apache2/mod_security/ /etc/apache2/logs
Download and install rules
Download rules from here

As of this writing, the rule set was “modsecurity-core-rules_2.5-1.6.1.tar.gz”, you may need to adjust accordingly as new rules are released.
sudo mkdir /etc/apache2/conf.d/modsecurity
cd /etc/apache2/conf.d/modsecurity
sudo wget http://www.modsecurity.org/download/modsecurity-core-rules_2.5-1.6.1.tar.gz
sudo tar xzvf modsecurity-core-rules_2.5-1.6.1.tar.gz
sudo rm CHANGELOG LICENSE README modsecurity-core-rules_2.5-1.6.1.tar.gz


Enable mod_security:

sudo a2enmod mod-security
Now restart Apache
That’s it :)

Testing mod_security

“Secure” Example 1 – curl
bodhi@home# curl -i http://ubuntuVPS
HTTP/1.1 200 OK
Date: Tue, 28 Apr 2009 22:44:42 GMT
Server: Apache/2.2.0 (Fedora)
Last-Modified: Tue, 28 Apr 2009 21:39:54 GMT
ETag: "50d4a-2d-468a44dadbe80"
Accept-Ranges: bytes
Content-Length: 45
Vary: Accept-Encoding
Content-Type: text/html
< html>< body>< h1>It works!< /h1>< /body>< /html>

Look no more server or php information (Fedora apache 2.2.0 , LOL !!! )

“Secure” Example 2 – bad .php
bodhi@home# curl -i "http://ubuntuVPS/insecure.php?secret_file=/etc/passwd"
HTTP/1.1 501 Method Not Implemented
Date: Tue, 28 Apr 2009 22:47:38 GMT
Server: Apache/2.2.0 (Fedora)
Allow: TRACE
Vary: Accept-Encoding
Content-Length: 291
Connection: close
Content-Type: text/html; charset=iso-8859-1
< !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
< html>< head>
< title>501 Method Not Implemented< /title>
< /head>< body>
< h1>Method Not Implemented< /h1>
< p>GET to /insecure.php not supported.< br />
< /p>
< hr>
< address>Apache/2.2.0 (Fedora) Server at ubuntuvps Port 80< /address>
< /body>< /html>

Looks like this in your browser:
"501 Method Not Implemented
Method Not Implemented"
GET to /insecure.php not supported.Apache/2.2.0 (Fedora) Server at ubuntuvps Port 80
Ah 501 Error looks much better then the contents of /etc/passwd :)
Where to go from here ?

1. Monitor your logs :
tail /var/log/apache2/mod_security/modsec_audit.log
 
2. Learn / edit your mod_security rules : ModSecurity Reference Manual

3. Delete bad.php, LOL
sudo rm -rf /var/www/insecure.php

I hope you enjoyed and learned from this tutorial :)

Reference:
"This is just a copy cat of the post from http://blog.bodhizazen.net/linux/how-to-mod_security-ubuntu-904/
All credit should go to the respective author. I tried the method in Ubuntu 10.10 and it works fine."

Note:-
Some of the rules may deny the access to you applications (eg: phpmyadmin/drupal etc). Test the rules well before you implement.

Friday, February 12, 2010

11. SELinux Tools


Utility "star"
Archiving SELinux Labeled files (Backup of SELinux labeled files using "star")
    Currently "tar" is not supporting the SELinux context information backup while archiving. This tool is not installed by default. This tool is a replacement to tar in a SELinux system. "star" preserves the security context information
Usage of "star"
Will show with the following example
# mkdir /root/test
# seq 1000000 > /root/test/test_file.txt
# ls -alZ /root/test/
    Make note of the SELinux label.
# star -xattr -H=exustar -c -f teststar.star /root/test
    This will create a file called teststar.star.
Now test the above statement by extracting the file using "STAR"
# cp teststar.star /tmp && cd /tmp
# star -xattr -x -f teststar.star
# ls -alZ /test
    Now we can see the directory which had archived before and still have the preserved security Tuple. While using "TAR" this result will vary (while extracting the newly created file will gain the Tuple of parent directory)
Note:-
    The archive created by star can also be extracted by tar, but tar wont be able to read the extended attributes from the file resulting creation of extracted file without the preserved context information. Optionaly we can backup with out SELinux context information and can relay upon reinstate the SELinux context for all files using "fixfiles" or by " #touch /.autorelabel && reboot". This method is used for all the tools that are not SELinux compliant.

SELinux LOG files
What to look for in LOG files are related to denies/permission problems:
    /var/log/messages is the default AUDIT log file (This may vary according to the "kern*" parameter in syslogd.conf file), and this file stores the messages related to "avc".
# grep avc /var/log/messeges | less
    This shows the logs of SELinux activity in the system. This file logs the following events
1. usage of resources
2. relabeling file contexts
3. changing the modes (enforcing=0 & enforcing=1).
4. booleans change information
5. file system relabeled after a reboot by setting up /.autorelabel

Structure of logs while an action of denial by SELinux
avc: denied {getattr read link}(attempted operation by subject on object) for pid (the process ID) 4223 exec=/usr/sbin/httpd (executed daemon) path=/home/user/public_html(path to the object accessed by subject) scontext=user_u:system_r:httpd_t(source context information) tcontext=system_u:object:ruser_home_t(targeted context information) tclass=dir (This is the class of the object, directory or file)
    This logs are used to troubleshoot the issues with the SELinux. The problem may be initially due to the DAC or MAC both yields the logs here. So make sure the DAC permissions prior to checking MAC.

Enabling Auditing:
    This makes the SELinux more verbose in logging the information to log file. This makes easy for debugging SELinux related issues.
To enable the auditing
Modify /etc/grub.conf by appending "audit=1" to kernel boot line
# vim /etc/grub.conf
audit=1
# reboot
    Reboot the system, This makes completion of enabling the auditing.
Confirming whether auditing is enabled
# cat /proc/cmdline
ro root=LABEL=/ rhgb quiet audit=1
    This file contains the switches used to start the currently running kernel. Verify the option "audit=1".
# grep audit /var/log/messages
(This may vary according to your kernel logging location)
    Monitor the above log file. this shows audit related messages.Or information about enabling the audit

Now we will create a condition to test/witness auditing. we will use here apache for it

# /usr/sbin/run_init /etc/init.d/httpd start
# ps -ef |grep httpd
    This starts the httpd with support to SELinux.
# cd /home/user/
# chcon -R -t user_home_t public_html
    Now we have changed the type of the public_html to user_home_t, which is an incorrect label and apache cannot be accessed this file. Thus we can generate the auditing information
Verify the mode  that SELinux is running
# cat /selinux/enforce
0
    This means the SElinux is running in permissive mode, which will generate the audit information.
Note: Permissive mode will not deny subjects from accessing the objects, but generated logs.

Open the browser and access the file
http://localhost/~user/
    This will load the file.(Because we are in permissive mode)
Now switch to enforcing mode and try accessing the same url http://localhost/~user/
# echo 1 > /selinux/enforce
    This will deny the file access.
Check the log file, According to syslog.conf file It logs to /var/log/firewall.log. This can be changed
http://localhost/~user/
# grep kern* /etc/syslog.conf
# less /var/log/firewall.log
Note:-
   This default /var/log/messege file only contains the information about switching the SELinux mode, this means the auditing has been logged to some where else. The /var/log/firewall.log shows the detailed information about the SELinux activity. This makes very useful to trace out the exact problem with SELinux enabled system. We can analyze to get the information about which objects have been denied from accessing by objects. By default the auditing is disabled. It is necessery for debugging the SELinux related issues. The Log file keeps on increasing rapidly, so the log file analysis should be taken care in daily basis.

Installing SELinux Management Tools
    This tool helps in Auditing and inspecting SELinux environment. Both GUI and CLI tools are available.

Shell Based Tools
Install the package using the rpm setools-xx.rpm.
1. seinfo
    which provides useful input based on source or binary policy.
# /usr/bin/seinfo    /etc/selinux/targeted/policy/policy.18
    This will return the information about the policy. Without the path of the policy the tool fails to run.
This shows the policy that cached by "avc" and running in the system.

2. avcstat (Advanced Vector Cache Stat)
    This tool shows the status of avc which houses the current policy, includes the information about the hits,misses, lookups etc. So we can get the sence of SELinux usage whether increased of decreased.
Installed in the location /usr/sbin/avcstat
# /usr/sbin/avcstat
lookups             hits        misses      allocs      reclaims    frees
2033982       2010020    12772        13983        140        12005
    This will return the number of lookups to avc cache, number of hits to cache. These are metrics that we have to monitor whether the system is under performing. If the number of lookups are double that the number of hits then the system will be under performing.
# /usr/sbin/avcstat 5
    This will refresh every 5 sec and shows the output.
3. sesearch
    This has the ability to search based on source type, destination type or class and search all the policy to get a match and get the conclusion that which subject related to object as per the rules.
#/usr/bin/sesearch -a -t httpd_sys_content_t /etc/selinux/targeted/polcy/policy.18
    This shows the all the rules (-a) that matches the type (-t) httpd_sys_content_t in the given policy "policy.18". This tool dumps the permissions according to the type of content we have given. So it is very useful to troubleshoot as well can be used to mimic the rules while creating the rules for new domain
#/usr/bin/sesearch -a -s httpd_t /etc/selinux/targeted/polcy/policy.18
    This shows all the rules based on the subject httpd

GUI Based Tools
1. seaudit
    This provides a way to interact with the entries that logged by SELinux into the default location /var/log/messages If the kernel logs are not logging into /var/log/messeges we have to configure the tool with the approproate file location.
Installing the tool:
#rpm -ivh setools-gui-xx.rpm
    This will install both seaudit as well apol
# seaudit -l /var/log/firewall.log -p /etc/selinux/targeted/policy/policy.18
    seaudit has to be shown the location of the log file (-l) and the location of the policy (-p) -p /etc/selinux/targeted/policy/policy.18

2. apol
      apol is a graphical tool that allows the user to inspect aspects of a SELinux security policy. The tool lets the user browse policy components (types, classes, roles, users, etc.), rules (TE, RBAC, MLS), and file system contexts. Among other capabilities, the tool provides in depth analysis of domain transitions, information flows, and relabeling permissions.

Thursday, February 11, 2010

10. SELinux - Source Targeted Policy


The file_context file with respect to Source Targeted Policy:
    The binary installation of the Targeted Policy created the file "file_contexts" inside /etc/selinux/targeted/contexts/files, it involves many individual files for creation of the file_contexts file.
After installation of the source policy we will get a folder called /etc/selinux/targeted/src. Beneath "src" a folder called "policy" contains many files and folders including version information, role based access control information and other related files. Two important files in this folder are "attrib.te" used for the Type Enforcement for attributes and another file called "assert.te".The "file_contexts" sub directory inside the policy folder of "src" has additional file called "types.fc", which is almost similar as the binary installation "file_contexts". "distro.fc" file is having information about the linux distros to make conditional matches for m4 usage while building the policy(i.e, it guides to the exact file location according to the distro variable.)
Note:-
(filename.fc = file context
 filename.te = type enforcement)
In "program" directory of the "file_contexts" have many *.fc files which defines the file context information about the various system utilities and daemons.
Eg:-
# cat ping.fc
# ping

/bin/ping.*        --    system_u:object_r:ping_exex_t
/usr/sbin/hping2    --    system_u:object_r:ping_exex_t
    This file defines the file context information for the binary ping. i.e, if there were policy applied in the system then the security label will be as above. But if we look at the binary /bin/ping, it will show something that not matches the above statement.
The context information of the current binary is
# ls -alz /bin/ping
-rwx-rx-rx    root root system_u:object_r:bin_t
    This is because each file context defined inside the folder "/etc/selinux/targeted/src/policy/file_contexts/program" should have a corresponding type enforcement defined. Here the type "bin_t" is applied/inherited from the context of parent ( /bin) directory. The corresponding ".te" files should be located in /etc/selinux/targeted/src/policy/domains/program. This folder houses all the TE files that corresponds to .fc files. eg:- apache.te, dhcpd.te, ntpd.te etc. So the listed daemons (which corresponds to the programs) will be protected.
Check whether the protection for apache has been enforced
# cat /etc/selinux/targeted/src/policy/file_contexts/program/apache.fc | grep /var/www
/var/www(/.*)?    system_u:object:httpd_sys_content_t
(And the corresponding TE file has been created inside "/etc/selinux/targeted/src/policy/domains/program" )
# ls -al /etc/selinux/targeted/src/policy/domains/program |grep apache
-rwx------    root root Jan 8 2010    apache.te
Now check the file_context of folder /var/www
# ls -ldZ /var/www
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t
    The folder is correctly labeled because of .fc has corressponding .te file defined. i.e, the Type has been enforced because it has a corressponding TE file for FC file.

Focus on TE files which relate to FC files.
    TE files resides inside /etc/selinux/targeted/src/policy/domains/program.
Function of TE :
1. TE Files enforce Type
    a. TE Files describes what are each domains able to do, this includes the types that domains that able to access as well as the system related calls (link, unlink, read, tcp_open, udp_open etc).
2. Now the action that are to be enabled in the object are defined in the TE file."TE" file enables actions on objects.
3. THIS FILE PERMITS BASICALLY SUBJECT TO OBJECT ACCESS.

   " We will explain this process with apache service."

        The SELinux admin should have low level of understanding about the operating system in order to understand the calls that made by a program.
The general system calls that apache makes are described below.
    a. read files (config files, content files and log files)
    b. bind to network ports (TCP: 80, TCP :443)
    c. write to file (log files)
    d. execute scripts (cgi, php etc)

Now take a look at apache file:
# vim /etc/selinux/targeted/src/policy/domains/program/apache.te
    Initially it defines about the booleans that can be over written by the configurations in "/etc/selinux/targeted/booleans" file. Under the "Apache Types" we defines the types that supported by apache. This is where actually the labels that defined for the domains which usually corresponds the types that applied to the filenames.
For Eg:-
#ls -alZ /var/www/
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_script_exec_t cgi-bin
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t error
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t html
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t icons
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t manual
-rwxr-x--x    root root Jan 8 2010 system_u:object:httpd_sys_content_t usage
    Notice that the context entries in this folder are defined in the "apache.te" file. Beneath "Apache Types" we can see the type for allowing access for apache defined
Eg:-
# cat /etc/selinux/targeted/src/policy/domains/program/apache.te
    "This file governs what the apache and its related programs are allowed to do on your system."
# Syntax: The syntax is as follows
allow|neverallow|audit|dontaudit     subject|domains     object     object_class     {premissions that to be appiled}
allow httpd_t httpd_log_t:link_file read
    allows httpd_t domain to Object httpd_log_t with object class as link_file with permission read
allow httpd_suexec_t self:capability {setuid setgid };
    # allows the subject httpd_suexec_t domain to object self capability with permissions setuid & setgid
dontaudit httpd_suexec_t var_run_t:dir search;
    This will stop auditing the given process
allow httpd_suexec_t home_root_t:dir search;
    This grands apache the permission to search the object having label home_root_t in which the object class is a directory) This means the apache can search any directory having the label "home_root_t", which is a directory (object class :dir)
The permission should be in "{}" curly brackets while defining two or more at a time.

Monday, February 8, 2010

9. SELinux Targeted Policy (RedHat) - IV


Now we will discuss about Preparing system with the source policies that are associated with the policy number 18 (by default comes with RHEL 4)
Inside the "/etc/selinux" folder have "targeted" folder which contains the source & Binary policies. If we intend to make any changes to the Policy we have to install the targeted source policy. The default installation will be the Binary policy which is unchangeable. So for changing the policy we have to install the targeted source policy. Again "the default installation of RHEL 4 installs the binary packages."

Need of source Policy installation
  1. In order to customize the policy or changing the policy
  2. In order to Learn more about the targeted Policy that how it is written.
  3. May need to define a policy in case of installation of a new program (which moves the newly installed program to the confined domains in SELinux).
    SELinux which operates in the kernel, processes existing policy, based on binary format in memory, so the source file are not used by the SELinux portion of the kernel.
The "/etc/selinux" folder contains
  • targeted/
  • config,v
  • config
The "Targeted" folder Contains
  • booleans  (This file contains the variables for enabling and disabling features on the fly such as cgi enabled apache http_enable_homedirs (refer previous topic) etc)
  • policy/ (This Folder contains the actual binary file of the policy called policy.xx(Eg:- "policy.18" RHEL 4)
  • contexts/ (This Folder consists of information about the contexts. All the contexts (Tuples) are defined inside this folder. The "file_contexts" file inside the folder "contexts/files" is the key file that actually maintains the relation ship between directories of the files system and how those directories and files should be labeled. Also the file contains the context entries of all sorts of mount points (i.e, how should the the files created in the file system labeled by default).
Installing source policy for Targeted Policy:
# rpm -qa |grep -i selinux
    This will show the selinux-policy-targeted package. This is responsible for the binary policy installation.
For installation of the selinux source policy download the source package of the policy named selinux-policy-targeted-sources.version.rpm .The installation creates the folder called /etc/selinux/targeted/src.
Install the package
# rpm -ivh selinux-policy-targeted.version.rpm
# cd /etc/selinux/targeted/src
 Beneath the /etc/selinux/targeted/src have a directory called "policy" which contains all of the files and directories that pertained to targeted policy.

The "file_contexts" file:
    This file contains the labeling information of all objects and subjects. It uses regular expressions for labeling
the files. check the "/home" definitions in the file to get more idea about the regular expressions used in the file_contexts..
The format used in the file is
" regexp -type context|none "
(types

-d = directory
  -- = file)
Eg:-
/home     -d     system_u:object_r:home_root_t
    The knowledge in this file is useful while creating the new policies.
Another eg:-
/media/[^/]*/.*    none
    This will make no labeling for the mounted object beneath the folder /media (eg:- cdrom mounted inside the /media). In short this file describes how the files in the system should be labeled to take effect of the targeted policy. So if we run the "fixfiles" (Refer previous posts) utility it refers this file for labeling.

RUN_INIT (Process at system boots with respect to SELinux)
    While system boots INIT determines the SELinux support and if found, it creates the process or allocates the space inside the memory with the help of utility called "run_init". "run_init" sets up the programs that are protected by SELinux in to distinct spaces that cannot be overlaped by each other or interacted by other daemons. So this way it increases the system security.

Key Start-up Utility For SELinux-Protected Daemons:
    If we need to restart a daemon, run_init will help that programs to run with in their protected spaces i.e, "run_init" ensures protected daemon isolation. "run_init" has been installed by package named "policycoreutils".

How to Check the process whether its out of context or running correctly with policy defined context:

We will use the apache to check whether the daemon is having the correct context
# ps -axZ |grep httpd
root:system_r:httpd_t    3111    ?    S    0:00    /usr/sbin/httpd
    Here we can see the Tuple/Context as "root:system_r:httpd_t". Here apache is running with the wrong user_id root:.

To change it First kill the process
# kill 3111

Now run the process/httpd daemon using run_init
# /usr/sbin/run_init /etc/init.d/httpd start
    ( This Will promt you for authentication for root user)
        This will start the httpd daemon in the domain that specified in the policy. i.e, the policy enforces the type or honors the type.
Now we check the httpd process again
# ps -axZ |grep httpd
user_u:system_r:httpd_t    5114    ?    S    0:00    /usr/sbin/httpd
    We can see that the apache is up and running with the proper context.

Thursday, February 4, 2010

8. SELinux Targeted Policy (RedHat) - III

SELinux Context Definition:
    Here we will discuss about the basics behind roles, types and domains in SELinux. Its important that we have a clear understanding of the three key pieces of information used in the security context Tuple.

Security Context or Tuple:
    A security context or Tuple consist of 2 or more related fields in given row.
eg:- user_u:system_r:unconfined_t
explained in simple word is  "id:first_name:last_name"

Field/Degree 1: USER LABEL
eg:- user_u, root_u etc
In general the first value will be the user value. Usually the non-privilege user will be described as "user_u". However the root user is treated as "root_u". The targeted policy in RHEL is not much more concentrated in the first and second fields

Field/Degree 2: (Role based Access control[RBAC])
    SELinux supports users being the members of Role (same like a typical DAC system where the user belongs to a group). i.e, in this example of Tuple user_u:system_r:unconfined_t & root_u:system_r:unconfined_t  the non privilege & privilege user is having a common role "system_r"

Field/Degree 3: Type/Domain
    It makes a difference whether we apply this to a subject or object. i.e, Type is applied to objects such as files and Domains are applied to Subjects (Programs or users).
Eg:-
Privilege as well as non privilege users are grouped in to unconfined "Type" by default .
For process such as httpd, each process has a domain named after the process with a suffix of "_t" eg:- httpd_t, dhcpd_t

7. SELinux Targeted Policy (RedHat) - II


Confined and Unconfined states
1. How to Disable Protection of currently protected targeted Daemon (httpd) while SELinux runns at enforcing mode ?
Or
How to Disable a particular domain from SELinux protection while it runs in enforcing mode?
Or
Transition from confined state to unconfined state of a daemon

We will explain this with apache daemon. Lets start configuring apache from confined state to unconfined state.
Steps:
# ps -axZ |grep httpd
    This will show the apache sandbox (Tuple) details or SELinux labeling httpd process .
# cd /selinux
    Inside this directory is a file called httpd_disable_trans, which controlls the httpd upon invication makes the transition from the default unconfined_t (unconfined) to httpd_t (confined)

Step: 1
# echo "1 1" > /selinux/booleans/httpd_disable_trans
    The file is overwritten by two values "1 1". The first value "1" is related to the currently running status of the daemon with respect to SELinux i.e, the service is currently being protected and the other value "1" is the pending value.
Step: 2
# echo "1" > /selinux/commit_pending_bools
    This makes the changes to booleans immediately, reloads  SELinux policy (None of the other domains are effected)
Step: 3
# service httpd restart
    This cause the httpd service reload finishes the transition from confined (httpd_t) sandbox to unconfined (unconfined_t) sandbox, "which is not protected by the Targeted Policy ". This means the httpd service will be behaving like a typical Linux service.
# ps -axZ |grep httpd
    Now we can notice that the httpd has been moved from confined to unconfiend.

2. Changing back httpd from unconfined  to confined context.

# echo "0 0" > /selinux/booleans/httpd_disable_trans
# echo "1" > /selinux/commit_pending_bools
# service httpd restart
# ps -axZ
    Now we can see that the httpd is running in confined.

Wednesday, February 3, 2010

6. SELinux Targeted Policy (RedHat) - I

Introduction:
    Here we will discuss about the daemons that supported with Targeted Policy. The Targeted policy in SELinux is specifically designed for RHEL and not applied to other Linux Distros. The idea of Targeted policy in SELinux is to protect vulnerability/highly utilized daemons/services of RHEL Servers. Each daemon is essentially sandboxed in targeted policy.i.e, daemons are restricted to some area and unable to interact to
other area/domains.
List of daemons protected by Targeted Policy by default.
Confined:
  1. dhcpd
  2. httpd
  3. mysql
  4. named
  5. nscd - name service caching daemon
  6. ntpd
  7. portmap
  8. postgresql
  9. snmpd
  10. squid
  11. syslogd
  12. winbindd
Unconfined:
  13. All other process
    The first 12 process mentioned above are the daemons which is protected as confined domains in Tuple (httpd_t, squid_t,snmp_t etc) and all other programs/subject/process are included in the unconfined (unconfined_t) domains in Targeted Policy. The Targeted policy restricts from communicating one domain with the other, i.e, dhcpd_t from httpd_t, which can be called as sandboxed.

Monday, January 25, 2010

5. SELinux With Baisc Linux Commands


    The following commands with "-Z" reveals along with the context information specifically for each commands.
  • ps -Z
  • ls -Z
  • cp -Z
  • id -Z
  • mv -Z
# id
uid=500(user1) gid=500(user1) groups=500(user1) context=user_u:system_r:unconfined_t
or
# id -Z
user_u:system_r:unconfined_t
This shows the information about the user ID and the context information of the user(SELinux label of user). i.e,  id -Z reveals current security context of users
# ps -Z
Shows the ps run by the user and the labeling information of each process. i.e, ps -Z reveals various domains in Tupals[SUBJECTS].
# ls -Z
Reveals the security context of files/directories[OBJECTS]
# cp
Copying a file will result in inheriting the targeted folder type context. Make sure that the context is verified once the file has been copied.
# mv
Moving a file will preserve the security context.

Saturday, January 23, 2010

4. SELinux TYPE Context : chcon & restorecon


Changing and restoring the Types:(chcon with Apache public directory)
We will explain the usage of chcon and restorecon with the following example.
Eg:-
Correctly label files under ~/public_html which is served by Apache using the UserDir derivative on a server which runs SELinux in Enforcing mode.

Step 1
Make sure that the apache serves the file under public_html directory of all users.
# vim /etc/httpd/httpd.conf
#(comment the following derivative)
 # UserDir disable
UserDir public_html
# service httpd restart
This will make apache to serve the pages in the directory public_home of all users home directory.

Keep in mind that the SElinux is enabled and running in Permissive mode. Now create directory inside any users home directory
# cd /home/user
# mkdir public_html && cd public_html && echo "testing the Type Enforcement(TE)" > index.html
Now check the label of the newly created directory
# ls -ltdZ public_html
drwxrwxr-x user user user_u:object_r:user_home_t public_html
The labeling is done automatically while creation of the folder with the specific type "user_home_t". But the Apache will not be able to server from this folder because of this type Tuple .

Step 2
First make sure that the DAC level permission is done for apache user to enter the users home directory to get the files inside the public_html folder. Because "SELinux honors the DAC prior to MAC"
# chmod a+x /home/user
# chmod a+x /home/user/public_html
Try accessing the file using the web browser http://localhost/~user.
This will serve the page from the users home directory. If we recall the SELinux has been set as Permissive mode so the page has been served. Refer Logs to find more details about the SElinux policy violations. The Logs will be generated since the SELinux is running at Permissive mode

Step:- 3
Now change the SELInux mode to Enforced
# echo 1 > /selinux/enforce
or
# setenforce 1
# sestatus
Make sure SELinux is running in the Enforced mode. Try accessing the file using the web browser http://localhost/~user.
This time we will get the 403 "Forbidden" error msg.

Step:- 4
Manipulate the Type Enforcement(TE), this means we have to make sure that the type or the value of the Tuple is changed on the files to be accessed by Apache.
# chcon -R -t httpd_user_content_t public_html/
Recursively change the type (TE) to "httpd_user_content_t". This will make apache to serve the page from the directory public_html. "httpd_user_content_t" is defined in the policy binary and source file.
# ls -ltrZ public_html/
Confirm the change.

Now Try accessing the file using the web browser http://localhost/~user.
This will serve the content.

To change the mode from enforcing to permissive mode
# echo 0 > /selinux/enforce
or
# setenforce 0

Note:
DAC-checks occurs first and if denied obviates need for MAC-checks


Restorecon - allows to restore the context information or the Tuple.
     This will allow to correctly restore the policy-based (/etc/selinux/targeted/policy/policy.xx) security-label context. The type contexts are inherited from the parent folder while running restorecon.
# restorecon -nv public_html
This will show the change that will be applied in the context from the policy to the current context. Usage of "-n" makes "no changes" to the files.
# restorecon -Rv public_html
This will restore the type context recursively under the folder public_html. The SElinux is need not to be enabled to run this utility because, this tool is based on the /etc/selinux/targeted/policy/policy.xx and applies accordingly.

verify the context with the following command.
# ls -ltrZ public_html

Note:-
"Copying a file will result in inheriting the type context of the targeted folder".
"Moving a file will preserve the SElinux security Tuple/context/label"

Thursday, January 21, 2010

3. SELinux Labeling


   As we discussed earlier SELinux works based on MAC systems, so that the system admin can separate the subjects from objects and this separation is based on the proper labeling of files in the filesystem. So this labeling becomes the heart of the SELinux functionality. SELinux enforces "types based" on the labels stored with in the files.

Labeling of Objects to support Type Enforcement(TE):

Labeling Features:
  1. To ensure that SELinux functions properly all Objects must be properly labeled to facilitate the Type Enforcement.
  2. File that are improperly labeled will not be protected.
Eg:-
# cd /root
# ls -lZ 

-rw-r--r--    root    root    user_u:object_r:file_t    install.log
    This will show the context information of the SELinux(labeling of each file), stored in the extended attributes of the file which supported by the ext2, ext3 reizerfs file systems inside the root folder. Files will be only properly labeled if we enable SELinux while creation of the files, that means while installation if we enable the SELinux all the files will be properly labeled and will be protected by SELinux and the file that created while SELinux was disabled will not be labeled and we have to do it manually.

       3.  Tuples/labels are the Security context. it is defined in user:role:type
                user example:- system_u, root etc
                role example:-  object_r
                type example:-  user_home_t, file_t etc
       4. Type applied to subject (httpd) is called = DOMAIN
       5. Type applied to Object (install.log) is called = TYPE

Re-Labeling the files to support SELinux
    Two ways to relabel the filesystem
1. Suggested way
    a. # touch /.autorelabel && reboot
        This will properly relabels all the files in the system. This will make the init to initiate the SELinux labeling This will happens before the programs start running.

2. Using the command "fixfiles"
    /sbin/fixfiles which belongs to "policycoreutils" rpm will change the context information will be done with out the system reboot.
To work with the fixfiles, the SELinux must be disabled before creation of the files and then use fixfiles to relabel the file
# fixfiles relabel
    This will relabels entire filesystem
# fixfiles -l fixedfile_log relabel
    This will relabels entire filesystem and logs output to the file fixedfile_log.
# fixfiles -R package name
    This will restore the labeling information of all the files installed by the particular package

Friday, January 15, 2010

2. SELinux Basics


Mandatory Access Control (MAC) SELinux
   
Benefits using the MAC model
  • MAC requires more system administration/experties
  • Some level of object oriented knowledge is required to configure. The objects in the system is divided in to 2
  1. Subjects - users & process
  2. Objects  - Files on the system (test/binary/sockets/named_pipes etc)
  • Offers more granular/fine control of security. This means the ability to restrict at very lower level of  access to the objects.(eg:- read/write/entering to a directory,lock a file, access a different contex area with in  the memmory etc)
  • SELInux is compiled in to the kernel and supported via LSM (Loadable security module) 

Determine the kernel supports SELinux
Step 1
# cd /boot/
# grep -i selinux config-`uname -ar`

    This will list the configuration of the selinux in the currently loaded kernel
Step 2
# sestatus -v
    This will tell the current status of the SELinux. "Policycoreutils" is the package which installs the
sestatus binary. This RPM also installs most used selinux binaries.
  • SELinux (MAC-based system) requires labeling for objects and subjects In-order to determine the access using SElinux the subjects and objects should be labelled. Here we have to set the given role and permissions to the subject and it should get matched with the object roles and permissions. /usr/sbin/setfiles is the binary to set the labelling for subjects and objects.
  • MAC based systems are Ideal for internet facing system running httpd,named,mysqld etc. The targeted  policy in SELinux ships with policies that supports these daemons.
  • The MAC checks perform by SELinux occurs after the DAC based checks
  • SELinux denies interaction between Subjects and Objects by default.
  • SELinux supports Type Enforcement (TE) TE is the way for us to label and group various subjects and  objects.i.e, it ties the process(subjects) to files(Objects).
  • TE also allows the creation of domains. Domains means assaigning various subjects into groups. i.e,  grouping httpd,htpasswd,htdigest into a group called httpd_r which equals a domain. And we can set permissions to this domain for accessing various objects.
    
SELinux MODES:
    SELinux functions in 3 Modes
1. Enforcing
    In this mode SELinux applies policies defined. In RedHat Linux the default policy is called "Targeted". This policy will be applied in the enforcing mode. Any violation to this policy will be results in deniel of access to object and  also creates a alarm.

2. Permissive
    The policy (Targeted) is applied, but instead of deniel it simply logs. it permites the subject for accessing  the objects . So this mode can be used to log the violation to test whether the application is compactable with the targeted policy.

3. Disabled
    The policy (Targeted) and SELinux is disabled.

Switching the SELinux Mode:

To enable the SELinux in permissive change the configuration at follwing file. This method requires the system
reboot

# cd /etc/selinux
# vim config
SELINUX=Permissive
#SELINUX=Enforcing
SELINUXTYPE=targeted

Another method of enabling SELinux, needs system reboot to enable SELinux
# system-config-securitylevel
    check the enabled mode only, this will makes the SELinux enabled in Permissive mode. and if need to
run in Enforcing mode have to select the Enforcing option.

3rd method of enabling SELinux
# vim /etc/grub.conf
#add the following to kernel line
selinux=1
#selinux=0 will run SELinux in Premissive mode

    This applies to all kernels that supports the SELinux (2.4 or 2.6)

Note:
Once the system is rebooted and running in Permissive mode we can use the following command to run the SELinux in to Enforcing mode without the system reboot
# echo 1 > /selinux/enforce
    The /selinux directory is same like /proc, a pseudo directory and all the files are saved in memory. all the SELinux labels will be presented at this directory.

SELinux Permissive mode:
    After enabling and rebooting the machine use the following to check the selinux status.
# sestatus
    This shows the status, SELinux mount point, mode (permissive or enforcing),policy version etc
  • Permissive mode allows to run the applications and all the Violations to the security policy will  logged in   /var/log/messages.
  • Policy version that ships with RHEL 4 is version 18. The policy is written in the source format based on  M4 macro language and compiled in to binary format.
  • /etc/selinux/targeted houses the source and binary files of the policy targated. The source policy may not be installed but the binaries policy must be installed to operate SELinux
  • /etc/selinux/targeted/policy contains the policy binary. selinux-policy-targated is the package installs the policy binary.
  • /etc/selinux/targeted/booleans file defines the daemons that the targated policy covers.

Booting Process of SELinux (How INIT handles the SELinux startup):
    After the BIOS starts hands of control to GRUB.GRUB initializes the Kernel. Kernel then initializes all the hardwares and hands over to INIT, the very first process in the Linux machine. In a SELinux enviornment init has to take certain decision whether the SELinux can be supported or not.
  1. /proc/filesystem contains the details about the filesystems that supported by the kernel INIT will search  for the "selinuxfs" in the /proc/filesystem. If this is not present the SELinux support will not be enabled.
  2. If enforcing=1 or enforcing=0 is passed in to the kernel commandline at boot time in GRUB the INITwill attempt to start in Enforcing(enforcing=1) or Permissive(enforcing=0) mode respectively
  3.  If there is no keyword defined to start through GRUB command line then the INIT will checks the/etc/selinux/config & starts the SELinux according to the config file. The GRUB command line overrides allthe configurations in the config file
  4. Loads the SELinux enviornment which includes the mounting of /selinux
  5. INIT reloads itself into the 'unconfined_t' domain. All process that are not targated will assossiated with the 'unconfined_t' domain.

Thursday, January 14, 2010

1. SELINUX - Introduction

SELINUX

Introduction:
Security-Enhanced Linux (SELinux) is a security architecture integrated into the 2.6.x kernel using the Linux Security Modules (LSM). It is a project of the United States National Security Agency (NSA) and the  SELinux community. SELinux integration into Red Hat Enterprise Linux was a joint effort between the NSA and Red Hat.It provides essentially the kernel firewall. Typically all OS runs with a discretionary access control mechanism(DAC). This means the process will be running with the respective user privilages. Also means a user on the system has all discretion for providing access to resources owned by the perticular user. However in Mandatary Access Controll system (MAC) the security admin is responsible for defining the policies access/restrictions the subject to object access. It involves the labeling subjects and objects.

     SELinux provides a flexible Mandatory Access Control (MAC) system built into the Linux kernel. Under standard Linux Discretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user's permissions to objects such as files, sockets, and other processes. Running a MAC kernel protects the system from malicious or flawed applications that can damage or destroy the system.SELinux defines the access and transition rights of every user, application, process, and file on the system.  SELinux then governs the interactions of these entities using a security policy that specifies how strict or lenient a given Red Hat Enterprise Linux installation should be. On a day-to-day basis, system users will be largely unaware of SELinux. Only system administrators need to consider how strict a policy to implement for their server environment. The policy can be as strict or as lenient as needed, and is very finely detailed. This detail gives the SELinux kernel complete,granular control over the entire system.

The SELinux Decision Making Process:
When a subject, (for example, an application), attempts to access an object (for example, a file), the policy enforcement server in the kernel checks an access vector cache (AVC), where subject and object  permissions are cached. If a decision cannot be made based on data in the AVC, the request continues to the security server, which looks up the security context of the application and the file in a matrix. Permission is then granted or denied, with an avc: denied message detailed in /var/log/messages if permission is denied. The security context of subjects and objects is applied from the installed policy, which also provides the  information to populate the security server's matrix.

SELINUX DAC / MAC CONCEPTS
 
3 common access control models:

    1. Discretionary Access Control (DAC)
                    This is the default model. Users has the rights to grand or deny access the objects.
 Major Problems with the DAC based system:
  • These are prone to malware and malicious softwares.
  • Setuid or setgid files are vulnuerable when a daemon compramises and gains the access.
  •  Access to all objects in the system is based on the identity of the user
  •  Default policy is liberal to access the objects
    2. Mandatory Access Control (MAC)-SELINUX
                     This is implemented by Selinux.
Benefits using the MAC model
  •  MAC requires more system administration/experties
  •  Some level of object oriented knowledge is required to configure. The objects in the system is divided in to 2
  1. Subjects - users & process
  2. Objects  - Files on the system (test/binary/sockets/named_pipes etc)
  • Offers more granular/fine control of security. This means the ability to restrict at very lower level of  access to the objects.(eg:- read/write/entering to a directory,lock a file, access a different contex area with in the memmory etc)
    3. Non-Discretionary Access Control (nDAC)
                       It is almost like a hybrid between DAC & MAC.
  • Administrator defines the DAC control for entire system