Powered by Blogger.

Featured 1

Curabitur et lectus vitae purus tincidunt laoreet sit amet ac ipsum. Proin tincidunt mattis nisi a scelerisque. Aliquam placerat dapibus eros non ullamcorper. Integer interdum ullamcorper venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Featured 2

Curabitur et lectus vitae purus tincidunt laoreet sit amet ac ipsum. Proin tincidunt mattis nisi a scelerisque. Aliquam placerat dapibus eros non ullamcorper. Integer interdum ullamcorper venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Featured 3

Curabitur et lectus vitae purus tincidunt laoreet sit amet ac ipsum. Proin tincidunt mattis nisi a scelerisque. Aliquam placerat dapibus eros non ullamcorper. Integer interdum ullamcorper venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Featured 4

Curabitur et lectus vitae purus tincidunt laoreet sit amet ac ipsum. Proin tincidunt mattis nisi a scelerisque. Aliquam placerat dapibus eros non ullamcorper. Integer interdum ullamcorper venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Featured 5

Curabitur et lectus vitae purus tincidunt laoreet sit amet ac ipsum. Proin tincidunt mattis nisi a scelerisque. Aliquam placerat dapibus eros non ullamcorper. Integer interdum ullamcorper venenatis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Saturday, April 12, 2014

Installing Nagios on RedHat based system

Nagios is an awesome Open Source monitoring tool, its provides you more comprehensive monitoring environment to always keep an eye on your all machines / networks whether you are in a your data center or just your small labs.
With Nagios, you can monitor your remote hosts and their services remotely on a single window. It shows warnings and indicates if something goes wrong in your servers which eventually helps us to detect some problems before they occur. It helps us to reducedowntime and business losses.
Recently, Nagios released its latest versions Nagios 4.0.1 on 15th October 2013, and its latest stable release of Nagios plugins 1.5.
This article is intended to guide you with easy instructions on how to install latest Nagios 4.0.1 from source (tarball) on RHEL 6.4/6.3/6.2/6.1/6/5.8CentOS 6.4/6.3/6.2/6.1/6/5.8 and Fedora 19,18,17,16,15,14,13,12 distributions. Within 30 minutes you will be monitoring your local machine, no any advanced installation procedure only basic installation that will work 100%on most of the today’s Linux servers.
Follow the steps below :
 1. Install the following pre-requisites
[root@foo1 ~]# yum install -y wget httpd php gcc glibc glibc-common gd gd-devel make net-snmp
2. Download the Nagios packages
[root@foo1 ~]# wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-4.0.0.tar.gz

3. Untar the tar ball

[root@foo1 ~]# tar -xvzf nagios-4.0.0.tar.gz

4. Create nagios system user

[root@foo1 ~]# useradd nagios

5. Run configure

[root@foo1 ~]# cd nagios
[root@foo1 nagios]# ./configure
...
...
*** Configuration summary for nagios 4.0.0 09-20-2013 ***:

 General Options:
 -------------------------
        Nagios executable:  nagios
        Nagios user/group:  nagios,nagios
       Command user/group:  nagios,nagios
             Event Broker:  yes
        Install ${prefix}:  /usr/local/nagios
    Install ${includedir}:  /usr/local/nagios/include/nagios
                Lock file:  ${prefix}/var/nagios.lock
   Check result directory:  ${prefix}/var/spool/checkresults
           Init directory:  /etc/rc.d/init.d
  Apache conf.d directory:  /etc/httpd/conf.d
             Mail program:  /bin/mail
                  Host OS:  linux-gnu

 Web Interface Options:
 ------------------------
                 HTML URL:  http://localhost/nagios/
                  CGI URL:  http://localhost/nagios/cgi-bin/
 Traceroute (used by WAP):  

Review the options above for accuracy.  If they look okay,
type 'make all' to compile the main program and CGIs.

6. Run make

[root@foo1 nagios]# make all
[root@foo1 nagios]# make install
[root@foo1 nagios]# make install-init
[root@foo1 nagios]# make install-config
[root@foo1 nagios]# make install-commandmode
[root@foo1 nagios]# make install-webconf

7. Check Nagios Core 4.0.0 configuration for errors

[root@foo1 nagios]# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
...
...
Total Warnings: 0
Total Errors:   0

Things look okay - No serious problems were detected during the pre-flight check

8. Create Nagios Core 4.0.0 Apache user

[root@foo1 nagios]# htpasswd -s -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

9. Install EPEL Repository

[root@foo1 nagios]# rpm -ivh http://ftp-stud.hs-esslingen.de/pub/epel/6/i386/epel-release-6-8.noarch.rpm

10. Install Nagios plugins

[root@foo1 nagios]# yum install nagios-plugins-all -y

11. Create a link to Nagios plugins directory

[root@foo1 nagios]# rm -rf /usr/local/nagios/libexec
[root@foo1 nagios]# ln -s /usr/lib/nagios/plugins/ /usr/local/nagios/libexec
[root@foo1 nagios]# chown -R nagios:nagios /usr/local/nagios/libexec

12. UPDATE: Add apache user to nagios group in /etc/group file

nagios:x:500:apache

13. Start Apache server

[root@foo1 nagios]# /etc/init.d/httpd start

14. Start Nagios Core 4.0.0 service

[root@foo1 nagios]# /etc/init.d/nagios start

15. Visit Nagios URL in your browser

Open http://IPADDRESS/nagios or http://FQDN/nagios in your browser and enter username and password created in step 8!


Friday, April 11, 2014

Wake of the Heartbleed Bug


Finding a faulty car part used in nearly every make and model, but you can't recall the Internet and all the data you put out on is more simple version of the HeartBleed Bug. More improved version or more details version, a flaw in the OpenSSL open source encryption toolkit that potentially allows for the unrestricted access to server memory, is an incredibly big deal. For the past two years, much of our private online data -- including passwords, credit card information, billing addresses and user names -- stored on some of the biggest Web sites out there could have been accessed by strangers with a little Web know-how.
The problem is that we don't know if the bad guys have found the faults first (the safe money is on "yes"). Due to the nature of the vulnerability, an attacker could have constantly leveraged the vulnerability millions of times over in the last two years on a single server, and we would have no clue. As is standard with any information breach, monitoring your online accounts, including financial statements, for any suspicious activity is the only way to be sure whether or not you're an online victim. 

How Industry reacted :

While it's easy to advise users to keep an eye out on their online accounts and data, the Heartbleed bug is present in millions of major Web sites and Web services due OpenSSL being the default secure-socket layer/Transport Layer Security (SSL/TLS) for the Apache and NGINX Web servers. Those affected include the heavy hitters like Google, Yahoo, Netflix, Facebook, Instagram, Twitter and PayPal. The security industry was quick to react and shortly after Monday night's disclosure of the bug, patches for the vulnerable versions of OpenSSL started to roll out. While this doesn't reverse the two years of potential access to our online data and the information that might have been swiped, it does stop the bleeding. It's now up to online Web sites and service providers to patch their Web servers.
As expected, many of the big names were quick to get their systems patched and get the word out that it's safe to use their services. As of midday on Wednesday, Google announced that it had updated many of its services. "We've assessed this vulnerability and applied patches to key Google services such as Search, Gmail, YouTube, Wallet, Play, Apps, and App Engine," said Matthew O'Connor, Google product manager.  "Google Chrome and Chrome OS are not affected. We are still working to patch some other Google services."

Many others have already followed suit, including Instagram, Facebook and Yahoo. Online users can also check to see if sites are safe before visiting through this online Heartbleed test site.

End User Actions :

"This is probably the worst bug discovered this year. We believed in the security of SSL/TLS, and now discover that it comes with a hole that allows anyone to read our personal information such as passwords, cookies or even server's private keys," said Jiri Sejtko, Director of the AVAST Virus Lab
. "We, as end users, simply can't do anything, but make sure we are as secure as possible."
And that means it's time to change all your online passwords. Many sites have already take Symantec's last bit of advice and have instigated password resets for their sites and services. For those that haven't, you may be inclined to go ahead and reset your password on your own. Don't.
The issue is that there still are many who are running the unpatched OpenSSL encryption tool. Changing your password or information on them will change nothing, as your newly changed info is still vulnerable. Security experts recommend completely avoiding sites using the unpatched OpenSSL until the patch has been applied and, once patched, then go ahead and change your password.

For those who may still potentially be running vulnerable versions of the encryption tool, Symantec's Dick O'Brien recommends businesses follow these steps:
  • Remember that the flaw lies in the OpenSSL library "and not a flaw with SSL/TLS nor certificates issued by Symantec [or other security firms]."
  • Those running OpenSSL 1.0.1 through 1.0 will need to update to version 1.0.1g of the software or recompile OpenSSL without the heartbleed extension.
  • If there's concern that Web server certificates have been compromised, contact the firm that issued the certificates for replacements.
  • "Finally, and as a best practice, businesses should also consider resetting end-user passwords that may have been visible in a compromised server memory."

Wednesday, March 19, 2014

Free and open-source software OS

When it comes to securing network infrastructure, the trend is to invest in commercial-grade appliances. Sadly, security designers tend to ignore the built-in security features available in FOSS distros. This article explains a few such features, and will help readers decide when and how to use them in a given network scenario.
Before we talk about the various features built into FOSS systems, we need to understand some terminology as well as the various attack methods. A network is typically divided into LAN and WAN, wherein the LAN can have network switches to further sub-divide it into manageable small networks. LAN and WAN are separated by a router. A firewall is deployed within the network to keep a watch on network packets from the security standpoint. This division of the internal and external network is called a perimeter, and as mentioned earlier, the firewall is an important component of the perimeter. Viewing firewall operations at a high level, the policies of what should be allowed to get into the network from the outside world, and what on the Internet should be accessible from the internal network decide the perimeter defence. In a complex network scenario, perimeter defence can also incorporate intrusion detection systems, UTM (Unified Threat Management) devices, etc, to make it more robust.
In the cyber security world, most attacks happen from within the network perhaps due to a root-kit, spy-ware, or a virus making its way to desktops or servers; or by a disgruntled employee who knows enough about the internal network to plant an attack. How an attack takes place is also important to understand. Please refer to the table below, which classifies various security attacks into two categories: network and Web.
Network attacks    Web attacks
Denial of Service    Denial of Service
Network sniffing    Cross-site scripting
Packet crafting    Man in the middle
Packet spoofing    Cryptographic attacks
Device invasion    Database hacking
DNS attacks    Cookie injection
Wireless attacks    Code exploitation
As you can see, this is an elaborate list of attacks, and no single device can stop them all and protect the network. For example, since a firewall sits on the perimeter, it hardly helps to prevent internal attacks, prompting a need to have an application-level firewall. Similarly, an anti-virus running on servers may not be capable of performing packet-level security analysis, which is crucial for a mission-critical database server. Cyber security is never 100 per cent fool-proof; hence, security designers need to explore all possible options prior to putting appropriate controls in place, leading to a robust design. This is where understanding and using the in-built security features of FOSS distros becomes important to introduce robustness.
FOSS security features
While there are so many distros available with various built-in features, I will concentrate on those features that are found in almost all versions. Some of the features mentioned below are actually open source projects that became integral parts of distros, over time.
Iptables: All Linux distros support iptables, which is essentially a truth-table sort of database containing information that lets the net-filter algorithm decide on how to treat a packet. It is a kernel module, requiring elevated privileges to configure. The working operation of iptables is very simple. Each packet is stripped into various fields, and the rules from the table are applied to make a decision in terms of letting it go ahead, blocking it, or dropping it. For a given server role, iptables can be written only once, by taking into account all the packet acceptance and rejection scenarios, and would rarely be needed to change. While many production farms use iptables to introduce an additional layer of security, it is important to note that it puts an additional burden on the server’s resources. Since every packet is stored temporarily and checked against a set of rules, it needs a considerable amount of computational power. Hence, iptables rules should not be very elaborate, but just adequate for the given network or application scenario. You can learn how to set up iptables on Ubuntu Linux, at https://help.ubuntu.com/community/IptablesHowTo
ConnTrack: This is another kernel-based module that falls under the net-filter framework. As an extension to iptables, ConnTrack essentially tracks the connection for all network sessions. It further tries to relate packets that formed a sensible and successful connection. ConnTrack operates at Layers 3 and 4, and creates useful information about each packet by reading its various fields. This can optionally be used further by iptables, to improve its effectiveness. For example, if the high-level protocol is HTTP, the packets are found to contain HTTP headers, as well as the session-based source and destination IP address, and service port information. If this data is made available by ConnTrack, it becomes easy for iptables to allow those packets without delving deep into them, thus saving precious (server) computational resources. The right approach is to have iptables and ConnTrack together.
Source address verification: One of the serious security attacks is packet spoofing, whereby attackers modify the source IP address to fool the destination host. As a result, it is rather difficult to detect and stop the spoofing attack. Most Linux systems come with a built-in, but usually less known, feature called source address verification. It is a kernel feature that, when turned on, starts dropping packets that appear to be arriving from the internal network but in reality are not. Most of the latest kernels on distros such as Ubuntu and CentOS do support it; if your Linux distro does not, it is time to upgrade or migrate to a new distro. Modifying the hosts.conf file to add nospoof on is another level of defence to try. For smaller Linux networks, a nice utility called arpwatch is very useful for detection. Arpwatch keeps track of MAC and IP addresses, and records all changes—and can be scripted to alert administrators upon a possible attack. Scripting can also be done to go through network interface logs and look for anomalies with respect to source address forging.
Anti-sniff: Another serious type of attack is packet sniffing, wherein the network cards are put into promiscuous mode and packets are dumped for analysis to create an attack vector. All famous distros such as Ubuntu and CentOS do support anti-sniffing utilities, which monitor the network interface settings and ensure that promiscuous mode is not enabled. This effectively stops sniffers from working, thwarting further security attacks.
SniffIt: While the anti-sniffer is deployed in a FOSS network, it is important to see if it is functioning properly. For that, you need to simulate sniffing, and the SniffIT or DSniff utilities do that. Wireshark is another good example. The idea behind a sniffer is also to capture packet patterns that can eventually be fed into an intrusion detection system. Snort is a famous FOSS IDS system. DSniff is very effective in capturing SSL traffic.
Beyond FOSS built-in security
As explained earlier, no single device or method can help you achieve 100 per cent security. Also, it is important to note that for some attacks such as packet sniffing, packet crafting, etc, there are no built-in security features available in an open source distro. All the methods explained here surely strengthen security, but they must be complemented with commercial-grade appliances and devices, to design a robust perimeter defence system.

Monday, March 17, 2014

SElinux security contexts

This article discusses security contexts for subjects (typically, processes) and how they are assigned. To view the list of processes on your system, along with their hierarchy, use the pstree command:
[root@vbg-work ~]# pstree

init-+-NetworkManager-+-dhclient
     |                `-{NetworkManager}
     |-abrtd
     |-acpid
     |-atd
     |-auditd-+-audispd-+-sedispatch
     |        |         `-{audispd}
     |        `-{auditd}
     |-avahi-daemon---avahi-daemon
     |-bonobo-activati---{bonobo-activat}
     |-cimserver---3*[{cimserver}]
     |-clock-applet
     |-console-kit-dae---63*[{console-kit-da}]
     |-crond
     |-cupsd
     |-2*[dbus-daemon---{dbus-daemon}]
     |-2*[dbus-launch]
     |-devkit-disks-da---devkit-disks-da
     |-devkit-power-da
     |-evolution---7*[{evolution}]
     |-evolution-alarm---{evolution-alar}
     |-evolution-data----2*[{evolution-data}]
     |-gconf-im-settin
     |-gconfd-2
     |-gdm-binary---gdm-simple-slav-+-Xorg
     |                              `-gdm-session-wor---gnome-session-+-abrt-applet
     |                                                                |-bluetooth-apple
     |                                                                |-gdu-notificatio
     |                                                                |-gnome-panel---{gnome-panel}
     |                                                                |-gnome-power-man
     |                                                                |-gnome-volume-co
     |                                                                |-gpk-update-icon---{gpk-update-ico}
     |                                                                |-metacity---{metacity}
     |                                                                |-nautilus---{nautilus}
     |                                                                |-nm-applet
     |                                                                |-polkit-gnome-au
The above output shows the process tree on my system (starting with the init process). init is the first one to be executed by the kernel after the basic system has been set up. All processes are children ofinit. When the system is shut down, init is the last process to terminate before the kernel executes its own shutdown.
To view the security contexts allotted to all system processes, execute the pstree command with the -Zoption:
[root@vbg-work ~]# pstree -Z
init(`system_u:system_r:init_t:s0')
 |-NetworkManager(`system_u:system_r:NetworkManager_t:s0')
 |  |-dhclient(`system_u:system_r:dhcpc_t:s0')
 |  `-{NetworkManager}(`system_u:system_r:NetworkManager_t:s0')
 |-abrtd(`system_u:system_r:abrt_t:s0-s0:c0.c1023')
 |-acpid(`system_u:system_r:apmd_t:s0')
 |-atd(`system_u:system_r:crond_t:s0-s0:c0.c1023')
 |-auditd(`system_u:system_r:auditd_t:s0')
 |  |-audispd(`system_u:system_r:audisp_t:s0')
 |  |  |-sedispatch(`system_u:system_r:audisp_t:s0')
 |  |  `-{audispd}(`system_u:system_r:audisp_t:s0')
 |  `-{auditd}(`system_u:system_r:auditd_t:s0')
 |-avahi-daemon(`system_u:system_r:avahi_t:s0')
 |  `-avahi-daemon(`system_u:system_r:avahi_t:s0')
 |-bonobo-activati(`unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023')
 |  `-{bonobo-activat}(`unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023')
 |-cimserver(`system_u:system_r:initrc_t:s0')
 |  |-{cimserver}(`system_u:system_r:initrc_t:s0')
 |  |-{cimserver}(`system_u:system_r:initrc_t:s0')
 |  `-{cimserver}(`system_u:system_r:initrc_t:s0')
 |-clock-applet(`unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023')
 |-console-kit-dae(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
 |  |-{console-kit-da}(`system_u:system_r:consolekit_t:s0-s0:c0.c1023')
Now, we can see the security contexts associated with all the processes. How did init get a type ofinit_t? Why are the security contexts of some child processes different from those of the parent (else all processes in the system should have had the type init_t)? How are these different security types assigned?
Consider another scenario: The httpd process on a Fedora/RHEL server is started with the commandservice httpd start or /etc/init.d/httpd start. Start the Web server process, if it’s not already running, with the following command:
[root@vbg-work ~]# /etc/init.d/httpd start
Check the security context associated with the httpd process:
[root@vbg-work ~]# ps axZ | grep httpd
unconfined_u:system_r:httpd_t:s0 3099 ?        Ss     0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3102 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3103 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3104 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3105 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3106 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3107 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3108 ?        S      0:00 /usr/sbin/httpd
unconfined_u:system_r:httpd_t:s0 3109 ?        S      0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3113 pts/0 S+   0:00 grep httpd
As you can see, the httpd process gets a security context type of httpd_t.
Stop the Web server with the following command:
[root@vbg-work ~]# service httpd stop
Stopping httpd:                                   [ OK ]
Restart the Web server. But this time, not from the service start-up script, but by executing the binary command, which is as follows:
[root@vbg-work ~]# /usr/sbin/httpd
…and now, check the SELinux security context for the Web server process:
[root@vbg-work ~]# ps axZ | grep httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3207 ? Ss   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3209 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3210 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3211 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3212 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3213 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3214 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3215 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3216 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 3218 pts/0 S+   0:00 grep httpd
[root@vbg-work ~]#
This time, the type of the Web server process is unconfined_t. Why is it so?
If we use the service command, the same Web server process gets a security context type of httpd_t, but executing the Web server directly gives the Web server process a security context type ofunconfined_t.
As you would have probably guessed by now, this is due to Type Transitioning. Like objects (files), Type Transitioning is also applied to subjects (processes).
The basic rules to set the security context of services are the same as those for files: Whenever a new service (process) is created in the memory, Type Transition rules in the policy are checked. If a Type Transition rule exists and matches the conditions, the resulting process is given the new security context. When there are no such rules, the new process inherits the security context of its parents.
To check all Type Transitions rules that apply to processes (classes of type process), issue the following commands:
[root@vbg-work ~]# sesearch -T -c process
 type_transition user_wine_t fusermount_exec_t : process mount_t;
   type_transition staff_execmem_t nsplugin_config_exec_t : process nsplugin_config_t;
   type_transition insmod_t fusermount_exec_t : process mount_t;
   type_transition xend_t fusermount_exec_t : process mount_t;
   type_transition sysadm_java_t fusermount_exec_t : process mount_t;
   type_transition ricci_modservice_t fail2ban_initrc_exec_t : process initrc_t;
   type_transition init_t afs_bosserver_exec_t : process afs_bosserver_t;
   type_transition hotplug_t dictd_initrc_exec_t : process initrc_t;
   type_transition ricci_modservice_t sssd_initrc_exec_t : process initrc_t;
   type_transition init_t apmd_exec_t : process apmd_t;
   type_transition qmail_local_t qmail_queue_exec_t : process qmail_queue_t;
   type_transition staff_execmem_t gpg_agent_exec_t : process gpg_agent_t;
...
Based on the above rules, the syntax of Type Transition rules that apply to processes can be understood as:
type_transtion [Parent Process Type] [Type of File being executed to create a process] : process [Type of The New Process created]
To check the above rules, let us look at the example of the Web server process discussed earlier. When executing the executable /usr/sbin/httpd directly to create the httpd process:
  1. The parent process is the shell (because we are executing the command /usr/sbin/httpd under the Bash shell).
  2. The type of the parent process is unconfined_t. (Execute the following command to check.)
    [root@vbg-work ~]# ps axZ | grep bash
    unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 2460 pts/0 Ss   0:00 bash
  3. The type of the file being executed is httpd_exec_t. (Execute the following command to check.)
    [root@vbg-work ~]# ls -lZ /usr/sbin/httpd
    -rwxr-xr-x. root root system_u:object_r:httpd_exec_t:s0 /usr/sbin/httpd
Let us check in our policy if such a rule exists:
[root@vbg-work ~]# sesearch -T -c process | grep httpd_exec_t | grep unconfined_t
[root@vbg-work ~]#
This shows that we do not have a Type Transition rule to set the security context of new processes created by executing files of type httpd_exec_t under a parent process of type unconfined_t. In such a scenario, i.e., in the absence of any Type Transition rule, the new process takes the type of the parent; therefore, the httpd process inherits its security context from Bash (which is unconfined_t).
Let us now analyse the other case. When starting the httpd service through initialisation scripts:
  1. The parent process is the shell (because we are executing the script /etc/init.d/httpd under Bash).
  2. The type of the parent process is unconfined_t. (Execute the following command to check.)
    [root@vbg-work ~]# ps axZ | grep bash
    unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 2460 pts/0 Ss 0:00 bash
  3. The type of the file being executed is httpd_initrc_exec_t. (Execute the following command to check.)
    [root@vbg-work ~]# ls -lZ /etc/init.d/httpd
    -rwxr-xr-x. root root system_u:object_r:httpd_initrc_exec_t:s0 /etc/init.d/httpd
Let us check in our policy if such a rule exists:
[root@vbg-work ~]# sesearch -T -c process | grep httpd_initrc_exec_t | grep unconfined_t
type_transition unconfined_t httpd_initrc_exec_t : process initrc_t;
[root@vbg-work ~]#
Finally, we have found a match. This rule states that if a file of type httpd_initrc_exec_t is executed under a parent process of type unconfined_t, the resulting process should get a type of initrc_t.
This is good, but we had observed that the Web server process had a type of httpd_t and this rule states that the type of the resulting process is initrc_t. Is there an error? Is there something missing?
There is, indeed, something missing. It is important to note that the Web server process is created on executing the binary file (/use/bin/httpd). Therefore, the init script actually executes this file.
But what happens is that the shell script process created by executing the initialisation script (/etc/init.d/httpd) is now running with a process security context bearing the type initrc_t (as per the rule above). When this process further executes the Web server binary (/usr/sbin/httpd), a new context is created. Therefore, there is another scenario that comes into play here, which is:
  1. The parent process is the shell script process created by executing the script /etc/init.d/httpd.
  2. The type of the parent process is initrc_t (because this is the type of process created by executing the init script from under Bash, as per the Type Transition rule above).
  3. The type of the file being executed is httpd_exec_t (as the shell script further executes the binary/usr/sbin/httpd). Execute the following command to check:
    [root@vbg-work ~]# ls -lZ /usr/sbin/httpd
    -rwxr-xr-x. root root system_u:object_r:httpd_exec_t:s0 /usr/sbin/httpd
Let us see if we have a Type Transition rule in the policy for the above:
[root@vbg-work ~]# sesearch -T -c process | grep httpd_exec_t | grep initrc_t
type_transition initrc_t httpd_exec_t : process httpd_t;
[root@vbg-work ~]#
Voila! There it is, stating that if a file of type httpd_exec_t is executed under a parent process of typeinitrc_t, the resulting process created will have a security context type of httpd_t.
As an exercise, let us ensure that the httpd process, if executed directly under the shell, should also be created with a security context type of httpd. To do this, we will need to create a new module and insert it into our policy. We will need to create a new type enforcement file as discussed in earlier articles. An example of the file is given below:
vbg@vbg-work test-selinux]$ cat http.te
policy_module(http-lfy,1.1.0)

########################################
#
# Declarations
#

require {
 type httpd_t;
 type unconfined_t;
 type httpd_exec_t;
 role unconfined_r;
 class process transition;
}

########################################
#
# http local policy
#
type_transition unconfined_t httpd_exec_t : process httpd_t;

role unconfined_r types httpd_t;

allow unconfined_t httpd_t:process transition;
[vbg@vbg-work test-selinux]$
Compile and load this module:
[vbg@vbg-work test-selinux]$ make http.pp
[vbg@vbg-work test-selinux]$ su -
[root@vbg-work ~]# semodule -i /home/vbg/test-selinux/http.pp
Now execute the command /usr/sbin/httpd and note the security context type of the httpd process:
root@vbg-work ~]# /usr/sbin/httpd
[root@vbg-work ~]#
[root@vbg-work ~]# ps axZ | grep http
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4343 ? Ss   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4345 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4346 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4347 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4348 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4349 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4350 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4351 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:httpd_t:s0-s0:c0.c1023 4352 ? S   0:00 /usr/sbin/httpd
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 4354 pts/0 S+   0:00 grep http
[root@vbg-work ~]#
But how is the type of the first process (init) set? Does it inherit its type from the kernel? What exactly happens?
The following lines are taken verbatim from Dan Walsh’s blog: “When the SELinux kernel boots up, it is hard coded to run as kernel_t. Since at this point there is no policy running, this is the only context. So since this is the only context, all applications that are run will stay in kernel_t. When the kernel executes/sbin/init it originally is running as kernel_t, then it reads in the policy file and loads it into the kernel. At this point init re-execs itself. When /sbin/init was installed it is labelled init_exec_t and now there is a rule in the kernel that says when kernel_t execs an application labelled init_exec_t, it should transition to init_t. So now the init process is running as init_t.”
Let us check if such a rule really exists in the policy, which applies when init re-executes itself:
  1. The parent process is the kernel.
  2. The parent process type is kernel_t.
  3. The file being executed is /sbin/init.
  4. The security context type of the file being executed is init_exec_t:
    [root@vbg-work ~]# ls -lZ /sbin/init
    -rwxr-xr-x. root root system_u:object_r:init_exec_t:s0 /sbin/init
Search the SELinux policy for a Type Transition rule:
root@vbg-work ~]# sesearch -T -c process | grep init_exec_t | grep kernel_t
type_transition kernel_t init_exec_t : process init_t;
There we are! When /sbin/init is executed under kernel_t, the init process being created has a type of init_t. This can be checked by the following command:
[root@vbg-work ~]# pstree -pZ | head -n 1
init(1,`system_u:system_r:init_t:s0’)
[root@vbg-work ~]#
Now we can understand how subjects or processes created in memory get their security contexts. Applying SELinux policy rules under type enforcement is simply allowing access only to desired objects by the designated subjects, and once we know how to set the security context types of objects and subjects, and how to create allow rules, we can easily achieve the best out of SELinux.
In the next article in this series, we will explore macros and dive deep into them.

The Art of Guard - Part VII

To test the effects of the new module, let us create a sample index.html file in the DocumentRoot folder of Apache:
[root@vbg ~]# echo "The Art of Guard - Part VII " > /var/www/html/index.html
[root@vbg ~]# service httpd start
To check if all is fine, let us view the Web page using elinks:
[root@vbg ~]# elinks --dump http://localhost
   The Art of Guard - Part VII
This shows that all is indeed fine and Apache can serve our document on the website. Let us now change the type of index.html to lfy_t and see what happens:
[root@vbg ~]# chcon -t lfy_t /var/www/html/index.html
chcon: failed to change context of `/var/www/html/index.html' to `system_u:object_r:lfy_t:s0': Permission denied
We have received an error message! The SELinux policy on my system does not allow us to change the type of the file /var/www/html/index.html to lfy_t.
But what is the current type of /var/www/html/index.html? To check the security context ofindex.html, use the following command:
[root@vbg ~]# ls -lZ /var/www/html/index.html
-rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html
We can see that the default type allotted to this file (SELinux object) is httpd_sys_content_t. Why is it so? We did not specify the file type when creating it. Why did it take this particular type and not tmp_t or some other type?
By default, newly created objects and subjects take the type of their parent object and subject, respectively. Since the folder /var/www/html/ is of the type httpd_sys_content_t, any new files created under it will also get the same type, unless you want it otherwise. The same applies to processes (or ‘subject’ in SELinux terminology).
Since SELinux is not allowing us to change the security context of our file to lfy_t, we will need to write a few allow rules and include them in our policy. As discussed in the earlier article, the best way is to add these allow rules to our Policy Module.
But first we need to understand why exactly this action is being disallowed. Let us turn to the log files for help:
[root@vbg ~]# tailf /var/log/audit/audit.log

type=AVC msg=audit(1261193853.109:39): avc:  denied  { relabelto } for  pid=2293 comm="chcon" name="index.html" dev=sda2 ino=104970 scontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 tcontext=system_u:object_r:lfy_t:s0 tclass=file
type=SYSCALL msg=audit(1261193853.109:39): arch=c000003e syscall=188 success=no exit=-13 a0=1a660e0 a1=3dece15649 a2=1a67660 a3=1b items=0 ppid=1960 pid=2293 auid=500 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=1 comm="chcon" exe="/usr/bin/chcon" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null)
type=USER_AUTH msg=audit(1261194789.950:40): user pid=2313 uid=500 auid=500 ses=1 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:unix_chkpwd acct="vbg" exe="/sbin/unix_chkpwd" hostname=? addr=? terminal=? res=success'
Now we can see from the AVC Denial message in the Audit Log that relabelto permission is denied to the source context unconfined_t (bash process—my shell) for the target context lfy_t. Going by our earlier discussion (in Part 5), we could create an allow rule for the above in our test.te file:
allow unconfined_t lfy_t : file { relabelto }
But will this solve the above-mentioned issue? Will not other SELinux denials crop up?
The important thing to remember is that SELinux permissive mode has been given for exactly this reason—troubleshooting. So let us take the system into permissive mode and see if any more errors occur:
[root@vbg ~]# getenforce
Enforcing
[root@vbg ~]# setenforce 0
[root@vbg ~]# getenforce
Permissive
Let us also clear the log file so that it contains only the latest errors. But we cannot afford to lose important logs. So we need to first make a copy of the current log file:
[root@vbg ~]# cat /var/log/audit/audit.log > /var/log/audit/my-audit-log-19Dec09
Now, let us empty the log file:
[root@vbg ~]# >/var/log/audit/audit.log
…and repeat the chcon command:
[root@vbg ~]# chcon -t lfy_t /var/www/html/index.html
Let us have a look at AVC denial messages in the new log file:
[root@vbg ~]# cat /var/log/audit/audit.log | grep -i deni
type=AVC msg=audit(1261195413.081:42): avc:  denied  { relabelto } for  pid=2328 comm="chcon" name="index.html" dev=sda2 ino=104970 scontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 tcontext=system_u:object_r:lfy_t:s0 tclass=file
type=AVC msg=audit(1261195413.081:42): avc:  denied  { associate } for  pid=2328 comm="chcon" name="index.html" dev=sda2 ino=104970 scontext=system_u:object_r:lfy_t:s0 tcontext=system_u:object_r:fs_t:s0 tclass=filesystem
We can see that two actions are disallowed. Let us write the allow rules for them:
allow unconfined_t lfy_t : file { relabelto }
allow lfy_t fs_t : filesystem { associate }
Let us update our module policy file, test.te:
[vbg@vbg test-selinux]$ vim test.te
policy_module(test, 1.1)

type lfy_t;

allow unconfined_t lfy_t : file { relabelto };
allow lfy_t fs_t : filesystem { associate };
Save and close. (Do note that we have now increased the version number to 1.1.)
Compile the test.te source file by running the make command:
[vbg@vbg test-selinux]$ make test.pp
Compiling targeted test module
/usr/bin/checkmodule:  loading policy configuration from tmp/test.tmp
test.te":5:ERROR 'unknown type unconfined_t' at token ';' on line 3199:

allow unconfined_t lfy_t : file { relabelto };
/usr/bin/checkmodule:  error(s) encountered while parsing configuration
make: *** [tmp/test.mod] Error 1
Oops! We have received an error while compiling our module!
This is because we have not defined the types and classes used elsewhere in our source file (test.te). But are these types not already defined in the policy? Doesn’t unconfined_t exist already?
It does, but we need to explicitly define which types and classes are required for our module. To solve this error, let us define the types in the required section of our source file. We explicitly add the following lines to our source:
require {
        type unconfined_t;
        type fs_t;
}
So that the new test.te is:
[vbg@vbg test-selinux]$ cat test.te
policy_module(test, 1.1)

require {
 type unconfined_t;
 type fs_t;
}

type lfy_t;

allow unconfined_t lfy_t : file { relabelto };
allow lfy_t fs_t : filesystem { associate };
Let us now compile this again:
[vbg@vbg test-selinux]$ make test.pp
Compiling targeted test module
/usr/bin/checkmodule:  loading policy configuration from tmp/test.tmp
/usr/bin/checkmodule:  policy configuration loaded
/usr/bin/checkmodule:  writing binary representation (version 10) to tmp/test.mod
Creating targeted test.pp policy package
rm tmp/test.mod.fc tmp/test.mod
This has successfully created our upgraded policy package. Thus the important points to remember while creating the code for a policy module are:
  1. Specify all existing types of the policy in a required section in the source file.
  2. Specify all new types to be created outside the required section.
Let us now upgrade the version in the policy and check:
[root@vbg test-selinux]# semodule -u test.pp
[root@vbg test-selinux]# semodule -u test.pp
[root@vbg test-selinux]# semodule -l | grep test
test 1.1
That shows that our latest version is now loaded.
Let us now try to re-label /var/www/html/index.html from httpd_sys_content_t to lfy_t:
[root@vbg test-selinux]# setenforce 1
[root@vbg test-selinux]# chcon -t lfy_t /var/www/html/index.html
chcon: cannot access `/var/www/html/index.html': Permission denied
Again, there are some more errors! Is it that SELinux is too cumbersome to troubleshoot? Till when do we need to keep on looking at these errors and generate rules? This would be a very demotivating and time-consuming task. Fortunately, a splendid tool called audit2allow comes to our rescue.
audit2allow generates SELinux policy allow rules from the logs of denied operations. It parses the log file and creates corresponding allow rules.
Let us repeat the above steps to generate AVC Denial logs in the audit log file.
[root@vbg test-selinux]# setenforce 0
[root@vbg test-selinux]# > /var/log/audit/audit.log
[root@vbg test-selinux]# cat /var/log/audit/audit.log | audit2allow

#============= unconfined_t ==============
allow unconfined_t lfy_t:file getattr;
audit2allow has many helpful options. Do ensure that you go through the man page in detail. To generate the “required” section for already existing system types and classes, use the option -r withaudit2allow:
[root@vbg test-selinux]# cat /var/log/audit/audit.log | audit2allow -r

require {
 type unconfined_t;
 type lfy_t;
 class file getattr;
}

#============= unconfined_t ==============
allow unconfined_t lfy_t:file getattr;
We can redirect these required statements to our policy module source file:
[root@vbg test-selinux]# cat /var/log/audit/audit.log | audit2allow -r >> /home/vbg/test-selinux/test.te
All we need to do now is edit the resulting test.te file, remove the declaration of type lfy_t from the required section and keep a single required section. Finally, our test.te should look like the one below:
[vbg@vbg test-selinux]$ cat test.te
policy_module(test, 1.1.1)

require {
 type unconfined_t;
 type fs_t;
 class file getattr;
}

type lfy_t;

allow unconfined_t lfy_t : file { relabelto };
allow lfy_t fs_t : filesystem { associate };
allow unconfined_t lfy_t:file getattr;
All we need to do is to compile and load this policy module:
[vbg@vbg test-selinux]$ make test.pp
Compiling targeted test module
/usr/bin/checkmodule:  loading policy configuration from tmp/test.tmp
/usr/bin/checkmodule:  policy configuration loaded
/usr/bin/checkmodule:  writing binary representation (version 10) to tmp/test.mod
Creating targeted test.pp policy package
rm tmp/test.mod.fc tmp/test.mod

[root@vbg test-selinux]# semodule -u test.pp
[root@vbg test-selinux]# semodule -l | grep test
test 1.1.1

[root@vbg test-selinux]# setenforce 1
[root@vbg test-selinux]# chcon -t lfy_t /var/www/html/index.html
[root@vbg test-selinux]# ls -lZ /var/www/html/index.html
-rw-r--r--. root root system_u:object_r:lfy_t:s0       /var/www/html/index.html
Finally, with the help of the wonderful audit2allow tool, we have been able to re-label the/var/www/html/index.html file to the type lfy_t. Can we now view the output of this file?
[root@vbg ~]# elinks --dump http://localhost
                                   Forbidden

   You don't have permission to access / on this server.

   --------------------------------------------------------------------------

    Apache/2.2.13 (Fedora) Server at localhost Port 80
Changing the Security Context type from httpd_sys_content_t to lfy_t has caused this SELinux denial. The setroubleshoot daemon popped up and recommended running restorecon on/var/www/html/index.html to restore its context to the original one.
As a simple exercise, it is left to you to modify the policy module to permit the httpd service read access to the files of type lfy_t. Please remember the rules covered above and also use the audit2allowcommand to generate the desired source.
In the next article of this series, we will look at how to set default security contexts for files using policy modules. We will also use policy modules to set rules that will automatically assign the type lfy_t to all files created in the Apache DocumentRoot folder.