Archives

Iptables

IPTABLES RHEL 6
Netfilter and IPTables
The Linux kernel features a powerful networking subsystem called Netfilter. The Netfilter subsystem provides stateful or stateless packet filtering as well as NAT and IP masquerading services. Netfilter also has the ability to mangle IP header information for advanced routing and connection state management. Netfilter is controlled using the iptables tool.
The IPTables similar to IPChains.
Note:
The IPTables cannot be used if IPChains is already running. If IPChains is present at boot time, the kernel issues an error and fails to start IPTables.
Firewall Configuration Tool
The Firewall Configuration Tool only configures a basic firewall. If the system needs more complex rules, refer to “IPTables” for details on configuring specific iptables rules.
SystemAdministrationFirewall
system-config-firewall
IPTables Required Package
[root@server1 Desktop]# rpm -qa iptables
iptables-1.4.7-4.el6.x86_64
IPTables Service start | stop etc..,
/etc/rc.d/init.d/iptables {start|stop|restart|condrestart|status|panic|save}
service iptables {start|stop|restart|condrestart|status|panic|save}
chkconfig iptables on | off | –list
IPTables Configuration File
[root@server1 Desktop]# rpm -qlc iptables
/etc/sysconfig/iptables-config
[root@server1 Desktop]# grep -v ‘#’ /etc/sysconfig/iptables-config
IPTABLES_MODULES=”nf_conntrack_ftp”
IPTABLES_MODULES_UNLOAD=”yes”
IPTABLES_SAVE_ON_STOP=”no”
IPTABLES_SAVE_ON_RESTART=”no”
IPTABLES_SAVE_COUNTER=”no”
IPTABLES_STATUS_NUMERIC=”yes”
IPTABLES_STATUS_VERBOSE=”no”
IPTABLES_STATUS_LINENUMBERS=”yes”
Backup and Restore IPTables
By default, firewall rules are saved in the /etc/sysconfig/iptables or /etc/sysconfig/ip6tables files.
[root@server1 ~]# ll /etc/sysconfig/iptables*
-rw——-. 1 root root  272 Sep 17 19:41 /etc/sysconfig/iptables
-rw——-. 1 root root 1756 Jul 19 21:58 /etc/sysconfig/iptables-config
-rw——-. 1 root root 1740 Jan  7  2011 /etc/sysconfig/iptables-config.old
-rw——-. 1 root root  476 Jul 20 03:03 /etc/sysconfig/iptables.old
-rw——-. 1 root root  184 Sep 17 19:41 /etc/sysconfig/iptables.save
[root@server1 ~]#cp -rf /etc/sysconfig/iptables /etc/sysconfig/iptables.backup
[root@server1 ~]# iptables-restore -c /etc/sysconfig/iptables.backup
Understanding IPTables
The IPTables three built-in rules
Filter – The default table for handling network packets.
Nat – Used to alter packets that create a new connection and used for Network Address Translation
Mangle – Used for specific types of packet alteration.
Each table has a group of built-in chains, which corresponding to the actions performed on the packet by netfilter. There are five predefine chains INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING
Filter built-in chains
INPUT — Applies to network packets that are targeted for the host.
OUTPUT— Applies to locally-generated network packets.
FORWARD — Applies to network packets routed through the host.
Nat built-in chains
      
PREROUTING — Alters network packets when they arrive.
OUTPUT — Alters locally-generated network packets before they are sent out.
POSTROUTING — Alters network packets before they are sent out.
Mangle built-in chains
INPUT — Alters network packets targeted for the host.
OUTPUT — Alters locally-generated network packets before they are sent out.
FORWARD— Alters network packets routed through the host.
PREROUTING — Alters incoming network packets before they are routed.
POSTROUTING — Alters network packets before they are sent out.
Every chain has a default policy to ACCEPT, DROP, REJECT or QUEUE
IPTables rules processing flow
1.      Rules are processed from upper to lower.
2.      Once rules matched criteria no further processing would be done and it goes to the rules specified in the target (or) executes the special values mentioned in the target.
3.      If the criteria are not matched, it moves on the next rule.
4.      At the end of list default value is ACCEPT so if a packet do not meet any criteria it would pass the packet.
Table
Table Function
Chain
Chain Function
Filter
Packet filtering
INPUT
Incoming to firewall. For packets coming to the local server.
OUTPUT
Filters packets originating from the firewall
FORWARD
Packet for another NIC on the local server. For packets routed through the local server.
Nat
Network Address Translation
PREROUTING
Packets will enter this chain before a routing decision is made.
POSTROUTING
Routing decision has been made. Packets enter this chain just before handing them off to the hardware.
OUTPUT
NAT for locally generated packets on the firewall.
Mangle
TCP header modification
PREROUTING, POSTROUTING,
OUTPUT, INPUT,
FORWARD
Modification of the TCP packet quality of service bits before routing occurs.
Structure of IPTables Command Options
Syntax:
iptables –t [Table-types] [options] [chain] –j [target]
Table-types
filter, nat, mangle
Options
-A   –    Append a rule to the end of a chain
-I   –    Insert in chain as rulenum (default1=first)
-R   –    Replace chain rulenum
-L   –    List the all chains
-S   –    List all rules in the selected chain
-D   –    Delete chain rulenum (1=first)
-F   –    Flushes all of the rules in the current iptables chain.
–N   –    Create a new user-defined chain
-P   –    Policy rules change
-p         –    protocol (tcp,udp,icmp,all)
-s   –     source (hostname, ipaddress, with /mask (24 or      255.255.255.0). A “!” argument before the address specification inverts the sense of the address.
-d   –    destination
–sport    –    source port     [–sport X | –sport X:X]
–dport    –    destination port [–dport X | –dport X:X]
-i   –    input-interface (eth0)
-o   –    output-interface (eth0)
-n   –    numeric
–line-numbers  –    listing rules with line number
Chain
INPUT
OUTPUT
FORWARD
PREROUTING
POSTROUTING
Target
ACCEPT     –    Allow the packets
DROP       –    Drops the packets and give no response
REJECT     –    Rejects the packets and sends a rejection response
Iptables examples
1.  iptables chain rules listening types
[root@server1 Desktop]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
ACCEPT     udp  —  anywhere             anywhere            udp dpt:domain
ACCEPT     tcp  —  anywhere             anywhere            tcp dpt:domain
DROP       icmp —  client1.example.com  server1.example.com icmp echo-request
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
[root@server1 Desktop]# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     udp  —  0.0.0.0/0            0.0.0.0/0           udp dpt:53
ACCEPT     tcp  —  0.0.0.0/0            0.0.0.0/0           tcp dpt:53
DROP       icmp —  192.168.1.101        192.168.1.100       icmp type 8
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
[root@server1 Desktop]# iptables -L -n –line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     udp  —  0.0.0.0/0            0.0.0.0/0           udp dpt:53
2    ACCEPT     tcp  —  0.0.0.0/0            0.0.0.0/0           tcp dpt:53
3    DROP       icmp —  192.168.1.101        192.168.1.100       icmp type 8
Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
       
[root@server1 Desktop]# iptables -t filter -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
ACCEPT     udp  —  anywhere             anywhere            udp dpt:domain
ACCEPT     tcp  —  anywhere             anywhere            tcp dpt:domain
DROP       icmp —  client1.example.com  server1.example.com icmp echo-request
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
       
[root@server1 Desktop]# iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
        
[root@server1 Desktop]# iptables -t mangle -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination        
2.  Delete the particular iptables chain rule
[root@server1 Desktop]# iptables -L INPUT –line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     udp  —  anywhere             anywhere            udp dpt:domain
2    ACCEPT     tcp  —  anywhere             anywhere            tcp dpt:domain
3    DROP       icmp —  client1.example.com  server1.example.com icmp echo-request
[root@server1 Desktop]# iptables -D INPUT 3
[root@server1 Desktop]# iptables -L INPUT –line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    ACCEPT     udp  —  anywhere             anywhere            udp dpt:domain
2    ACCEPT     tcp  —  anywhere             anywhere            tcp dpt:domain
3.  How to flush the all iptables chain rules
[root@server1 Desktop]# iptables –F
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@server1 Desktop]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
4.  Block all incoming and outgoing packets on a network gateway
[root@server1 Desktop]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination        
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
        
[root@server1 Desktop]# iptables -P INPUT DROP
[root@server1 Desktop]# iptables -P OUTPUT DROP
[root@server1 Desktop]# iptables -P FORWARD DROP
[root@server1 Desktop]# iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination        
Chain FORWARD (policy DROP)
target     prot opt source               destination        
Chain OUTPUT (policy DROP)
target     prot opt source               destination
        
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@server1 Desktop]# ping 192.168.1.101
PING 192.168.1.101 (192.168.1.101) 56(84) bytes of data.
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
5.  I have a two linux system
a>    Server1.example.com                   –           192.168.1.100
b>    Client1.example.com                    –           192.168.1.101
Practice 1
I have decided server1.example.com block icmp echo request service from client1.example.com.
Ping 192.168.1.100
Destination
Source
[root@server1 Desktop]# iptables -t filter -I INPUT -s 192.168.1.101
-d 192.168.1.100 -p icmp –icmp-type echo-request -j REJECT
[root@server1 Desktop]# iptables -L INPUT –line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination        
1    REJECT     icmp —  client1.example.com  server1.example.com icmp echo-request reject-with icmp-port-unreachable
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@server1 Desktop]# ping -c 3 192.168.1.101
PING 192.168.1.101 (192.168.1.101) 56(84) bytes of data.
64 bytes from 192.168.1.101: icmp_seq=1 ttl=64 time=0.283 ms
64 bytes from 192.168.1.101: icmp_seq=2 ttl=64 time=0.166 ms
64 bytes from 192.168.1.101: icmp_seq=3 ttl=64 time=0.171 ms
[root@client1 Desktop]# ping -c 3 192.168.1.100
PING 192.168.1.100 (192.168.1.100) 56(84) bytes of data.
From 192.168.1.100 icmp_seq=1 Destination Port Unreachable
From 192.168.1.100 icmp_seq=2 Destination Port Unreachable
From 192.168.1.100 icmp_seq=3 Destination Port Unreachable
Practice 2
Now I have decided server1.example.com block icmp ping request to client1.example.com
Source
Destination
Ping 192.168.1.101
[root@server1 Desktop]# ping -c 3 client1.example.com
PING client1.example.com (192.168.1.101) 56(84) bytes of data.
64 bytes from client1.example.com (192.168.1.101): icmp_seq=1 ttl=64 time=0.193 ms
64 bytes from client1.example.com (192.168.1.101): icmp_seq=2 ttl=64 time=0.244 ms
64 bytes from client1.example.com (192.168.1.101): icmp_seq=3 ttl=64 time=0.218 ms
[root@server1 Desktop]# iptables -t filter -I OUTPUT -s 192.168.1.100 -d 192.168.1.101 -p icmp –icmp-type echo-request -j REJECT
[root@server1 Desktop]# iptables -L OUTPUT
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination        
REJECT     icmp —  server1.example.com  client1.example.com icmp echo-request reject-with icmp-port-unreachable
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@server1 Desktop]# ping -c 3 client1.example.com
PING client1.example.com (192.168.1.101) 56(84) bytes of data.
From server1.example.com (192.168.1.100) icmp_seq=1 Destination Port Unreachable
From server1.example.com (192.168.1.100) icmp_seq=1 Destination Port Unreachable
From server1.example.com (192.168.1.100) icmp_seq=1 Destination Port Unreachable
6.  I have a three system lap setup details.
System 1          –           server1.example.com   –           192.168.1.100
System 2          –           client1.example.com    –           192.168.1.101
System 3          –           client2.example.com    –           192.168.1.102
Practise 1
System 1 configured as an ftp server. I have decided client1.example.com not access ftp server using iptables.
[root@server1 Desktop]# iptables -t filter -I INPUT -s client1.example.com -p tcp –dport 21 -j REJECT
[root@server1 Desktop]# iptables -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
REJECT     tcp  —  client1.example.com  anywhere            tcp dpt:ftp reject-with icmp-port-unreachable
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@client1 ~]# ftp server1.example.com
ftp: connect: Connection refused
ftp> bye
[root@client2 ~]# ftp server1.example.com
Connected to server1.example.com (192.168.1.100).
220 (vsFTPd 2.2.2)
Name (server1.example.com:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> bye
Practice 2
System 1 configured as an ftp server block all network except client1.example.com
[root@server1 Desktop]# iptables -t filter -I INPUT -s ! client1.example.com -p tcp –dport 21 -j REJECT
Using intrapositioned negation (`–option ! this`) is deprecated in favor of extrapositioned (`! –option this`).
[root@server1 Desktop]# iptables -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination        
REJECT     tcp  — !client1.example.com  anywhere            tcp dpt:ftp reject-with icmp-port-unreachable
[root@client1 ~]# ftp server1.example.com
Connected to server1.example.com (192.168.1.100).
220 (vsFTPd 2.2.2)
Name (server1.example.com:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> bye
221 Goodbye.
[root@client2 ~]# ftp server1.example.com
ftp: connect: Connection refused
ftp> bye
[root@client2 ~]# logout
Connection to client2.example.com closed.
[root@server1 Desktop]#
Practice 3
System 1 server1.example.com ftp and ssh services does not access from system 2 client1.example.com in a single iptables chain rules
[root@server1 Desktop]# iptables -t filter -I INPUT -s 192.168.1.101 -p tcp –dport 21:22 -j REJECT
[root@server1 Desktop]# service iptables save
[root@server1 Desktop]# service iptables restart
[root@client1 ~]# ssh server1.example.com
ssh: connect to host server1.example.com port 22: Connection refused
[root@client1 ~]# ftp server1.example.com
ftp: connect: Connection refused
ftp> bye

[root@client1 ~]#

TCP Wrapper

TCP Wrapper is a host-based Networking ACL system, used to controlling access to network services.
 TCP Wrapper Work Flow
Required Packages
[root@client1 Desktop]# rpm -qa tcp_wrappers*
tcp_wrappers-7.6-57.el6.x86_64
tcp_wrappers-libs-7.6-57.el6.x86_64
The Most Important library packages
/lib64/libwrap.so.0
/lib64/libwrap.so.0.7.6
TCP Wrappers Configuration Files
To determine if a client is allowed to connect to service, TCP Wrappers reference the following two files, which are commonly referred to as
“hosts access” files:
·         /etc/hosts.allow
·         /etc/hosts.deny
Help command
#man hosts_options
#man hosts_access
Note:
To determine if a network service binary is linked to “libwrap.so”, type the following command as the root user:
ldd | grep libwrap
Example
[root@client1 Desktop]# ldd /usr/sbin/sshd | grep libwrap
            libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f22184a9000)
[root@server1 Desktop]# ldd /usr/sbin/vsftpd | grep libwrap
            libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f906a243000)
Advantages of TCP Wrappers
TCP Wrappers provide the following advantages over other network service control techniques:
·         Transparency to both the client and the wrapped network service — Both the connecting client and the wrapped network service are unaware that TCP Wrappers are in use. Legitimate users are logged and connected to the requested service while connections from banned clients fail.
·         Centralized management of multiple protocols — TCP Wrappers operate separately from the network services they protect, allowing many server applications to share a common set of access control configuration files, making for simpler management.
Important points when using TCP Wrappers to protect network services:
1.       If access to a service is allowed in “hosts.allow”, a rule denying access to that same service in “hosts.deny” is ignored.
2.       The rules in each file are read from the top down and the first matching rule for a given service is the only one applied. The order of the rules is extremely important
3.       If no rules for the service are found in either file, or if neither file exists, access to the service is granted.
4.       TCP wrapped services do not cache the rules from the hosts access file, so any changes to hosts.allow or hosts.deny take effect immediately without restarting network services.
Default Log Files
The TCP Wrappers will do all its logging via syslog according to yout /etc/syslog.conf file. The following table lists the standard locations where messages from TCP Wrappers will appear:
1.       AIX                                                         –              /var/adm/messages
2.       HP-UX                                                   –              /usr/spool/mqueue/syslog
3.       Linux                                                     –              /var/log/messages
4.       FreeBSD, OpenBSD, NetBSD       –              /var/log/messages
5.       Mac OS X                                             –              /var/log/system.log
6.       Solaris                                                   –              /var/log/syslog
Formatting Access Rules
The format for both /etc/hosts.allow and /etc/hosts.deny is identical.
daemon_list : client_list : option : option …
daemon_list : client_list [ : shell_command ]
Daemon list:
                                A comma – separated list of process names (not service names) or the ALL wildcard.
Client list:
                                A comma – separated list of hostnames, host IP addresses, special patterns, or wildcards which identify the hosts affected by the rule.
Options:
                                An optional action or colon – separated list of actions performed when the rule is triggered. Option fields support expansions, launch shell commands, allow or deny access, and alter logging behaviour.
Wildcards
Wildcards allow TCP Wrappers to more easily match groups of daemons or hosts.
ALL                 Specifies all networks
LOCAL            Specifies the local network
EXCEPT          Excludes a particular user/client
KNOWN          Indicates all hosts that can be resolved by the system
UNKNOWN    Indicates all hosts that can’t be resolved by the system
PARANOID     Specifies that the forward and reverse lookup IP address don’t match
Examples
Server1.example.com –           192.168.1.100
Client1.example.com  –           192.168.1.101
Client2.example.com  –           192.168.1.102
Network                      –           192.168.1.0/24
1.      Configure server1.example.com does not ssh access client1.example.com except client2.example.com
Server1.example.com
[root@server1 ~]# vim /etc/hosts.allow
sshd : client1.example.com : deny
sshd : client2.example.com : allow
:wq!
or
vim /etc/hosts.allow
sshd : client2.example.com
vim /etc/hosts.deny
sshd : client1.example.com
or
vim /etc/hosts.allow
sshd : client1.example.com EXCEPT client2.example.com : deny
client1.example.com
[root@client1 Desktop]# ssh server1.example.com
ssh_exchange_identification: Connection closed by remote host
client2.example.com
[root@client2 Desktop]# ssh server1.example.com
root@server1.example.com’s password:
Last login: Sun Nov  4 16:32:51 2012 from client1.example.com
2.      Deny the all daemon network services in example.com except vsftpd daemon services.
#vim /etc/hosts.allow
ALL EXCEPT vsftpd : .example.com : deny
Or
#vim /etc/hosts.allow
Vsftpd : .example.com
#vim /etc/hosts.deny
ALL : .example.com
Or
#vim /etc/hosts.deny
ALL EXCEPT vsftpd : .example.com
Note:
ALL : .example.com
ALL : *.example.com
ALL : 192.168.1.
ALL : 192.168.1.0/24
ALL : 192.168.1.100
ALL : 192168.1.0/255.255.255.0
ALL : *.example.com EXCEPT my.org
ALL : ALL EXCEPT *.example.com : deny
3.      Allow all the daemon network services with in example.com only other all all network restricted.
#vim /etc/hosts.allow
ALL : ALL EXCEPT *.example.com : deny
Or
#vim /etc/hosts.deny
ALL : ALL EXCEPT *.example.com
4.      TCP Wrapper configure using shell commands example
Configure all daemon service running allowed details stored particular log file.
[root@server1 ~]# touch /var/log/tcp_wrappers.log
[root@server1 ~]# vim /etc/hosts.allow
ALL : *.example.com \ : spawn /bin/echo %d from %c user %u >> /var/log/tcp_wrappers.log \ : spawn /bin/date >> /var/log/tcp_wrappers.log : allow
[root@server1 ~]# cat /var/log/tcp_wrappers.log
sshd from client2.example.com user unknown
Sun Nov  4 22:53:03 IST 2012
vsftpd from client2.example.com user unknown
Sun Nov  4 22:54:03 IST 2012

Deny requests for a particular service

[root@myvm1 ~]# cat /etc/hosts.allow
sshd: .slashroot.in
[root@myvm1 ~]#

In the above shown example sshd service is only allowed from “slashroot.in” domain.

[root@myvm1 ~]# cat /etc/hosts.allow
vsftpd: .slashroot.in
[root@myvm1 ~]#

In the above shown example, vsftpd service is only allowed from slashroot.in domain.

Again keep the fact in mind that a conflicting entry in hosts.deny will be ignored, because hosts.allow is processed first and if a request pattern is allowed, it will never process hosts.deny file at all.

Also you can deny these same requests as shown in the above examples, by making the same entry in hosts.deny, but in that case your hosts.allow must be empty or else must not contain similar rule for allowing.

Let’s see another pattern for allowing and denying hosts.

[root@myvm1 ~]# cat /etc/hosts.allow
ALL: 172.16.
[root@myvm1 ~]#

In the above example all hosts with the ip address 172.16.*.* is allowed to make connections to all TCP wrapper based services on the hosts.

In the above example if you add ALL: 172.16.104.54, in the file hosts.deny will not be of any use, because you have already allowed all requests from 172.16.*.* in hosts.allow file.

You can also make the same entry with IP and subnet mask based style, as shown below.

[root@myvm1 ~]# cat /etc/hosts.allow
ALL: 172.16.0.0/255.255.0.0
[root@myvm1 ~]#

If you want to deny or allow a large number of hosts, then you can also do that by mentioning the list of ip/hostnames in another file and pointing to that file in /etc/hosts.allow.

[root@myvm1 ~]# cat /etc/hosts.allow
sshd: /etc/sshd.hosts
[root@myvm1 ~]#

In the above rule, an important point to note is that the rule starts with a “/”, mentioning the path for the file.

Previously we saw that you can allow/deny an entire domain, but what if you want to make exceptions to some hosts on that domain.

[root@myvm1 ~]# cat /etc/hosts.allow
ALL: .slashroot.in EXCEPT example.slashroot.in
[root@myvm1 ~]#

In the above example all hosts from slashroot.in domain will be allowed except example.slashroot.in.

In the exact similar manner, you can also deny one particular service, after allowing the rest to a group of hosts or domain, as shown below.

[root@myvm1 ~]# cat /etc/hosts.allow
ALL EXCEPT sshd: 172.16.0.0/255.255.0.0
[root@myvm1 ~]#

In the above shown method all hosts from 172.16.0.0 network are allowed for all the services except ssh.

The <options> field in the tcp wrapper entry can also be used to make all entry in one files itself(Yeah that’s correct, you can use a single file for accept and deny rules. This is the best method to avoid confusion.), the syntax for such entry should be made, by taking an extra care.

[root@myvm1 ~]# cat /etc/hosts.deny
vsftpd : example1.slashroot.in : allow
sshd : example1.slashroot.in : deny
sshd : example2.slahroot.in : allow
[root@myvm1 ~]#

In the above example, i have made the entry of both allowing and denying connections to service in hosts.deny file(i have kept my hosts.allow file empty). “allow” and “deny” are part of the options filed in the entry.

Another important fact that must be kept in mind is the length of the access rule that you are making in tcp wrapper files.

One rule per line is the way it must be made. Otherwise rules might get skipped without applying them while processing. There is a workaround for this problem, by including “/”,  for all those rules that are lengthy. An example is shown below.

[root@myvm1 ~]# cat /etc/hosts.allow
vsftpd : 172.16.103.150 \ : spawn /bin/echo ftp access prohibited>>/var/log/ftp.log \ : deny
[root@myvm1 ~]#

In the above example, we have used backslashes to denote that the rule is one line. Also we have spawned echo process to make a text redirect to ftp log file. This kind of actions can be taken with the help of options field as shown above.

Like we have used spawn to echo some text content in ftp log, this can be made very detailed log with the help of some options.

[root@myvm1 ~]# cat /etc/hosts.allow
vsftpd : 172.16.103.150 \ : spawn /bin/echo %c %h %p %u ftp access prohibited>>/var/log/ftp.log \ : deny
[root@myvm1 ~]#

In the above example, i have used

%c for complete client information like username and hostname

%h is used to determine client’s ip address

%p is used to log process id of the process

%u is used for username of the client who is requesting the service.

You can make much more interesting things to trigger on matching a rule, using the same spawn method and redirection.

A complete mannuel entry for TCP wrapper can be found by running the below command as shown below.

[root@myvm1 ~]# man hosts_options
[root@myvm1 ~]#

Hope this article was helpful in understanding the concept of TCP wrappers in Linux.

SELinux

·       Security Enhanced Linux (SELinux) is another layer of security for the Linux OS.

·         Developed by the National Security Agency (NSA)
·         It adds protection for different files, applications, processes and so on.
ImageImage
Note:
            Instead of turning it off, however, you could use SELinux in “permissive” mode, which allows everything to function normally but logs warnings when action or commands would have been blocked. Running in this mode is good for troubleshooting and gaining an understanding of how SELinux works. For the REDHAT exam, however, you need to know how to work with SELinux enabled and enforcing.
SELinux Required Packages
Default Installed Packages
policycoreutils-2.0.83-19.18.el6.x86_64
selinux-policy-3.7.19-126.el6.noarch
selinux-policy-targeted-3.7.19-126.el6.noarch
libselinux-utils-2.0.94-5.2.el6.x86_64
libselinux-python-2.0.94-5.2.el6.x86_64
libselinux-2.0.94-5.2.el6.x86_64
Required Installation Packages for advanced SELinux management purpose
yum install selinux-policy*
yum install setroubleshoot*
yum install setools*
yum install policycoreutils*
yum install mcstrans*
There are three available modes for SELinux
1.      Disabled          –           SELinux is turned off and doesn’t restrict anything
2.      Permissive       –           SELinux is turned on, but it logs warnings only when an action normally would have been blocked.
3.      Enforcing         –           SELinux is turned on and blocks actions related to services.
SELinux Management Command
Sestatus            –           shows the current status of SELinux
Getenforce       –           shows the enforcing status of SELinux
Setenforce       –           changes the enforcing status of SELinux
Getsebool        –           returns the Boolean value of a service option
Setsebool         –           sets the Boolean value of a service option
Chcon              –           changes the context of a file, directory, or service
Restorecon       –           resets the context of an object
System-config-selinux –           graphical
Semanage boolean –l   –           list all boolean
Semanage fcontext –l  –           list all context
Semanage port –l         –           list all port number
Sestatus command
-b         –           displays all Boolean and their statuses
-v         –           provides verbose output
[root@server1 Desktop]# sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 24
Policy from config file:        targeted
[root@server1 Desktop]# getenforce
Enforcing
Configuring SELinux
The main config file is “/etc/selinux/config” and “/etc/sysconfig/selinux”
[root@server1 Desktop]# cat /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing – SELinux security policy is enforced.
#     permissive – SELinux prints warnings instead of enforcing.
#     disabled – No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these two values:
#     targeted – Targeted processes are protected,
#     mls – Multi Level Security protection.
SELINUXTYPE=targeted
Setenforce command
When changing the mode in which SELinux runs, you are still required to reboot the system.
setenforce [ Enforcing | Permissive |1|0]
[root@server1 Desktop]# setenforce 0
[root@server1 Desktop]# getenforce
Permissive
[root@server1 Desktop]# setenforce 1
[root@server1 Desktop]# getenforce
Enforcing
[root@server1 Desktop]# reboot
                                                                 
 
SELinux File contexts
SELinux uses three different contexts to enforce security:
1.      User
2.      Role
3.      Domain (also called “type”)
Now to RHEL6 is the addition of a fourth context known as “Level” (this level represents the sensitivity level of a file or directory).
User:
Unconfined_u             Unprotected user
System_u                     System user
User_u                         Normal user
Role:
Object_r                                   File
System_r                                  Users and processes
Domain:
            Unconfined_r              Unprotected file or process
Each file, folder and service has an associated label that contains all three contexts.
For example SSH service
[root@server1 Desktop]# ps -ZC sshd
LABEL                             PID TTY          TIME CMD
system_u:system_r:sshd_t:s0-s0:c0.c1023 2260 ? 00:00:00 sshd
1st field “system_u”     -> system user
2ndfieed “system_r”     -> users and processes
3rd field “unconfined_t” -> domain
[root@server1 Desktop]# ll -Z /etc/ssh/sshd_config
-rw——-. rootroot system_u:object_r:etc_t:s0       /etc/ssh/sshd_config
“chcon” command
Contexts are important when creating websites because if the site doesn’t have the correct context, it is not accessible by the web server. To change the context of a file or directory, you can use the “chcon” command.
Syntax: chcon [option] context file
Option
-f         –           Suppresses error message
-u         –           Sets user context
-r          –           Sets role context
-t          –           Sets type context (domain)
-R        –           Change recursively
-v         –           provides verbose output
Example
1.      Change the user context from normal user to system user:
[root@server1 Desktop]# touchmyfile
[root@server1 Desktop]# ls -Z myfile
-rw-r–r–. rootroot unconfined_u:object_r:admin_home_t:s0 myfile
[root@server1 Desktop]# chcon -vu system_umyfile
changing security context of `myfile’
[root@server1 Desktop]# ls -Z myfile
-rw-r–r–. rootroot system_u:object_r:admin_home_t:s0 myfile
Tips
“chcon” command is to reference the context of another file.
This capability is useful when you’re using SELinux to enforce security on websites.
When create a new customer site, you can use the “chcon” command to reference the template site and apply the correct context:
#chcon –vR –reference /var/www/html/default_site /var/www/html/customer_site
If you make a mistake or just want to reset the original context of a file or directory, you can use the “restorecon” command.
Syntax: restorecon [options]
Options:
            -i          ignore files that don’t exit
            -p         shows progress
            -v         shows changes as they happen
            -F         resets context
Reset the context of your file back to its original context:
# restorecon -F myfile
verify the changes was applied correctly
#ls -Z myfile
-rw-r–r– root root root:object_r:admin_home_t:s0 myfile
SELinux Service and Boolean options
To view these Boolean options, you can use the “getsebool” command combined with grep to look for specific options
syntax: getsebool -a | grep boolean
[root@server1 repodata]# getsebool -a | grep ftp
allow_ftpd_anon_write –> off
allow_ftpd_full_access –> off
allow_ftpd_use_cifs –> off
allow_ftpd_use_nfs –> off
ftp_home_dir –> off
ftpd_connect_db –> off
httpd_enable_ftp_server –> off
tftp_anon_write –> off
[root@server1 repodata]# getsebool -a | grep samba
samba_create_home_dirs –> off
samba_domain_controller –> off
samba_enable_home_dirs –> off
samba_export_all_ro –> off
samba_export_all_rw –> off
samba_run_unconfined –> off
samba_share_fusefs –> off
samba_share_nfs –> off
use_samba_home_dirs –> off
virt_use_samba –> off
you might be thinking that this is a huge list, so how can you tell which options to change so that Apache, ftp, samba can provide you with different services? the “semanage” command can provide you with a description of each Boolean, It is also very useful if you need a specific settings changed.
[root@server1 ~]# semanage boolean -l | grep ftp
ftp_home_dir                   -> off   Allow ftp to read and write files in the user home directories
tftp_anon_write                -> off   Allow tftp to modify public files used for public file transfer services.
allow_ftpd_full_access         -> off   Allow ftp servers to login to local users and read/write all files on the system, governed by DAC.
allow_ftpd_use_nfs             -> off   Allow ftp servers to use nfs used for public file transfer services.
allow_ftpd_anon_write          -> off   Allow ftp servers to upload files,  used for public file transfer services. Directories must be labeled public_content_rw_t.
allow_ftpd_use_cifs            -> off   Allow ftp servers to use cifs used for public file transfer services.
ftpd_connect_db                -> off   Allow ftp servers to use connect to mysql database
httpd_enable_ftp_server        -> off   Allow httpd to act as a FTP server by listening on the ftp port.
After deciding which Boolean you’d like to change, you need to enable or disable the value appropriately. To enable or disable a Boolean option, you can use the “setsebool” command. When using the command, you also need to use the -P option for the change to be persistent.
syntax: setsebool -P [boolean = on(1) }| off(0)]
[root@server1 ~]# setsebool -P allow_ftpd_anon_write on
[root@server1 ~]# getsebool -a | grep ftp
allow_ftpd_anon_write –> on
allow_ftpd_full_access –> off
allow_ftpd_use_cifs –> off
allow_ftpd_use_nfs –> off
ftp_home_dir –> off
ftpd_connect_db –> off
httpd_enable_ftp_server –> off
tftp_anon_write –> off
SELinux Troubleshooting
SELiux have a two log files
/var/log/audit/audit.log –           Logs SELinux denials
/var/log/messages         –           Logs SELinux denials
Each log file provides specific error messages when denials occur, making them easier to search using “grep”. Two common commands you can use to hunt for error messages include
# grep “SELinux is preventing” /var/log/messages
# grep “denied” /var/log/audit/audit.log
Problems can arise in SELinux for numerous reasons. However, the top three include
Labelling problems
Using a nonstandard directory tends to cause problems if the directory or files aren’t labeled correctly.
Correct context
When you’re moving files, they can lose or retain incorrect contexts, causing access errors. Use the matchpathcon command to verify the correct context.
Confined service
If certain Booleans are not enabled, a service may have trouble operating or communicating with other services.
Review Questions
1. What is the point of using SELinux?
2. What are SELinux Booleans?
3. What command can you use to change the context of files?
4. What command can you use to query Boolean values?
5. What command and option do you use to view the description of Boolean values?
6. How would you view all Boolean options for the HTTP service?
7. Which log file is used to keep track of policy violations?
8. How would you disable SELinux protection for NFS, allowing shares to be
read/write?
Answers to the Review Questions
1. SELinux provides enhanced granular security for the Linux operating system.
2. SELinux Booleans provide restrictions to different aspects of a service.
3. chcon
4. getsebool
5. semanage boolean -l
6. getsebool –a | grep http
7. The /var/log/audit/audit.log file contains all policy violations.
8. setsebool –P nfs_export_all_rw=1