Archive | March 1, 2014

Bonding/teaming on Redhat Linux 6

All the system admin would like to avoid server outage by having redundancy for root filesystem using mirroring,  Multiple FC links to SAN with help of multi-pathing and many more.So here the question is how do you provide redundancy in network level ? Having a multiple network card will not give any redundancy.In redhat Linux you need to configure bonding to accomplish the network level redundancy.Once you have configured the bonding/teaming by using two NIC cards,kernel will automatically detect the failure of any NIC and work smartly according to that without any riot.Bonding can be used for load sharing as well between two physical links.

The below diagram will explain how the bonding is happening .

NIC Bonding unixArena

Operating system used: Redhat Linux 6.3
NIC Details:

[root@mylinz2 network-scripts]# ifconfig -a |grep eth
eth2      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
eth4      Link encap:Ethernet  HWaddr 00:0C:29:79:17:04
eth3      Link encap:Ethernet  HWaddr 00:0C:29:79:17:F0
[root@mylinz2 network-scripts]#
Goal:
Configure bonding between eth2 and eth4 with name of bond0.

Step 1:

Add the below line in /etc/modprobe.conf to load the bonding module in to kernel.

alias bond0 bonding

In redhat 6.3 , you need to create new file called “bonding.conf” under /etc/modprobe.d/ with below mentioned line.

# cat /etc/modprobe.d/bonding.conf
alias bond0 bonding

Step 2:

Now time to create a bonding interface configuration file in /etc/sysconfig/network-scripts/ directory like the below one.

[root@mylinz2 network-scripts]# pwd
/etc/sysconfig/network-scripts
[root@mylinz2 network-scripts]# cat ifcfg-bond0
#This is congiguration file for bond0.Used NIC’s eth2 & eth4
DEVICE=bond0
IPADDR=192.168.10.25
NETMASK=255.255.255.0
USRCTL=no
ONBOOT=yes
BOOTPRO=none
BONDING_OTPS=”mode=0 miimon=100″
[root@mylinz2 network-scripts]#

Step:3

Create a configuration files under “/etc/sysconfig/network-scripts/” for network interfaces if not exists.If exists,have a contents like the below one.

[root@mylinz2 network-scripts]# cat ifcfg-eth2
DEVICE=eth2
HWADDR=00:0C:29:79:17:FA
BOOTPRO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no

[root@mylinz2 network-scripts]# cat ifcfg-eth4
DEVICE=eth4
HWADDR=00:0C:29:79:17:04
BOOTPRO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
USERCTL=no

Note:Do not copy paste the content from above output.MAC and DEVICE name will differ for each system.

Step:4

Now restart the network service to load the configuration.

Note:Do not restart the network service without server maintenance window.

[root@mylinz2 ~]# service network restart
Shutting down interface eth2:  Device state: 3 (disconnected) [  OK  ]Shutting down interface eth4:  Device state: 3 (disconnected) [  OK  ]Shutting down loopback interface:                             [  OK  ]Bringing up loopback interface:                               [  OK  ]Bringing up interface bond0:  Active connection state: activated
Active connection path: /org/freedesktop/NetworkManager/ActiveConnection/15
[  OK  ]Bringing up interface eth3:  Active connection state: activated
Active connection path: /org/freedesktop/NetworkManager/ActiveConnection/16
[  OK  ][root@mylinz2 ~]#

Step:5

Verify whether “bond0″ has come up with IP or not .

[root@mylinz2 Desktop]# ifconfig -a
bond0     Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
inet addr:192.168.10.25  Bcast:192.168.10.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe79:17fa/64 Scope:Link
UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
RX packets:22 errors:0 dropped:0 overruns:0 frame:0
TX packets:27 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3843 (3.7 KiB)  TX bytes:4169 (4.0 KiB)

eth2      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2031 (1.9 KiB)  TX bytes:2064 (2.0 KiB)

eth4      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1812 (1.7 KiB)  TX bytes:2105 (2.0 KiB)

In the above output,you can see NIC eth2 and eth4 have flag “SLAVE” and interface “bond0″ has flag MASTER.Another thing you note both, the NIC interface will show same MAC address.

Step:6

Performing the live test to ensure bonding is providing the fault tolerance.

First i am removing the LAN cable from eth4 and let see what happens.

[root@mylinz2 Desktop]# ifconfig -a
bond0     Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
inet addr:192.168.10.25  Bcast:192.168.10.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe79:17fa/64 Scope:Link
UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
RX packets:22 errors:0 dropped:0 overruns:0 frame:0
TX packets:27 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3843 (3.7 KiB)  TX bytes:4169 (4.0 KiB)

eth2      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2031 (1.9 KiB)  TX bytes:2064 (2.0 KiB)

eth4      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1812 (1.7 KiB)  TX bytes:2105 (2.0 KiB)

Still the bond0 interface is UP and RUNNING fine.At the same time,”RUNNING” flag has disappear from eth4.

Now i have connected LAN cable back to eth4 and pulling out from eth2.

[root@mylinz2 Desktop]# ifconfig -a
bond0     Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
inet addr:192.168.10.25  Bcast:192.168.10.255  Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe79:17fa/64 Scope:Link
UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
RX packets:22 errors:0 dropped:0 overruns:0 frame:0
TX packets:27 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3843 (3.7 KiB)  TX bytes:4169 (4.0 KiB)

eth2      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:15 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2031 (1.9 KiB)  TX bytes:2064 (2.0 KiB)

eth4      Link encap:Ethernet  HWaddr 00:0C:29:79:17:FA
UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
RX packets:11 errors:0 dropped:0 overruns:0 frame:0
TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1812 (1.7 KiB)  TX bytes:2105 (2.0 KiB)

Still “bond0″ interface running with UP & RUNNING flag.So you have successfully configured bonding on Redhat Linux 6.
To see complete bonding info,use below command.

[root@mylinz2 Desktop]# cat /proc/net/bonding/bond0
Ethernet Channel Bonding Driver: v3.6.0 (September 26, 2009)

Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 0
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eth2
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:0c:29:79:17:fa
Slave queue ID: 0

Slave Interface: eth4
MII Status: up
Speed: 1000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 00:0c:29:79:17:04
Slave queue ID: 0
[root@mylinz2 Desktop]#


To verify the current bonding mode,use below command.

[root@mylinz2 Desktop]# cat /sys/class/net/bond0/bonding/mode
balance-rr 0

You can modify the bonding mode by editing “mode” in the ifcfg-bond0  configuration file.

[root@mylinz2 Desktop]# cat /etc/sysconfig/network-scripts/ifcfg-bond0 |grep -i mode
BONDING_OTPS=”mode=0 miimon=100″

table.tableizer-table { border: 1px solid #CCC; font-family: ; font-size: 12px; } .tableizer-table td { padding: 4px; margin: 3px; border: 1px solid #ccc; } .tableizer-table th { background-color: #104E8B; color: #FFF; font-weight: bold; }

Policy Details

Ploicy Name Code Description
balance-rr 0 Round-Robin policy for fault tolerance
active-backup 1 Active-Backup policy for fault tolerance
balance-xor 2 Exclusive-OR policy for fault tolerance
broadcast 3 All transmissions are sent on all slave interfaces.
802.3ad 4 Dynamic link aggregation policy
balance-tlb 5 Transmit Load Balancing policy for fault tolerance
balance-alb 6 Active Load Balancing policy for fault tolerance

To list the currently configured bonds,

[root@mylinz2 Desktop]# cat /sys/class/net/bonding_masters
bond0

How to scan new FC LUNS and SCSI disks in Linux ?

How to scan new FC LUNS and  SCSI disks in Redhat Linux without rebooting the server?  Most of the Linux beginners have wondering how to do this and this article will be for them.It may look like very simple as we perform this in daily operation to scan luns but system has many work to do in background when you execute storage scanning commands. Redhat says this type of scan can be distributive,since it can cause delays while I/O operation timeout and remove devices unexpectedly from OS.So perform this scan when really you want to scan the disks and LUNS.

Scanning FC-LUN’s in Redhat Linux

1.First find out how many disks are visible in “fdisk -l” .

# fdisk -l 2>/dev/null | egrep ‘^Disk’ | egrep -v ‘dm-‘ | wc -l

2.Find out how many host bus adapter configured in the Linux box.you can use “systool -fc_host -v” to verify available FC in the system.

# ls /sys/class/fc_host
host0  host1

In this case,you need to scan host0 & host1 HBA.

3.If the system virtual memory is too low ,then do not proceed further.If you have enough free virtual memory,then you can proceed with below command to scan new LUNS.

# echo “1” > /sys/class/fc_host/host0/issue_lip
# echo “1” > /sys/class/fc_host/host1/issue_lip

Note: You need to monitor the “issue_lip” in /var/log/messages to determine when the scan will complete.This operation is an asynchronous operation.

4.Verify if the new LUN is visible or not by counting the available disks.

# fdisk -l 2>/dev/null | egrep ‘^Disk’ | egrep -v ‘dm-‘ | wc -l

If any new LUNS added ,then you can see more count is more then before scanning the LUNS.

Scanning SCSI DISKS in Redhat Linux

1.Finding the existing disk from fdisk.

[root@mylinz1 ~]# fdisk -l |egrep ‘^Disk’ |egrep -v ‘dm-‘
Disk /dev/sda: 21.5 GB, 21474836480 bytes

2.Find out how many SCSI controller configured.

[root@mylinz1 ~]# ls /sys/class/scsi_host/host
host0 host1 host2

In this case,you need to scan host0,host1 & host2.

3.Scan the SCSI disks using below command.

[root@mylinz1 ~]# echo “- – -” > /sys/class/scsi_host/host0/scan
[root@mylinz1 ~]# echo “- – -” > /sys/class/scsi_host/host1/scan
[root@mylinz1 ~]# echo “- – -” > /sys/class/scsi_host/host2/scan

4.Verify if the new disks are visible or not.

[root@mylinz1 ~]# fdisk -l |egrep ‘^Disk’ |egrep -v ‘dm-‘
Disk /dev/sda: 21.5 GB, 21474836480 bytes
Disk /dev/sdb: 1073 MB, 1073741824 bytes
Disk /dev/sdc: 1073 MB, 1073741824 bytes

From Redhat Linux 5.4 onwards, redhat introduced ”/usr/bin/rescan-scsi-bus.sh” script to scan all the SCSI bus and update the SCSI layer to reflect new devices.

But most of the time,script will not be able to scan new disks and you need go with echo command.

 What does the echo “1” to the issue_lip file do? – SCAN SCSI in Linux?

Question 1:  What will happen if we issue the below command ?
 
# echo “1” > /sys/class/fc_host/host/issue_lip
 
 
Answer : 
 
    This operation performs a Loop Initialization Protocol (LIP) and then scans the interconnect and causes the SCSI layer to be updated to reflect the devices currently on the bus. A LIP is, essentially, a bus reset,  and will cause device addition and removal. This procedure is necessary to configure a new SCSI target on a Fibre Channel interconnect. Bear in mind that issue_lip is an asynchronous operation.
 
    The command may complete before the entire scan has completed. You must monitor /var/log/messages to determine when it is done. The lpfc and qla2xxx drivers support issue_lip
 
 
Question2 : 
 
What will happen if we issue the below command ? what does “- – -” mean in the command?
 
# echo “- – -” > /sys/class/scsi_host/host0/scan
 
 
Answer: 
 
It means that you are echoing a wildcard value of “channel target and lun”, and the operating system will rescan the device path.

User and Group Administration

In Red Hat Linux, there are three different types of user accounts.

Root, Normal user, System account (pseudo-user)

Root user

  • The root user is the equivalent of the Administrator or Enterprise Admin account in the windows world.
  • It is most powerful account on the system and has access to everything.

Normal user

  • Normal user accounts have no write access to anything on the system except their home directory.
  • They can read and explorer much of the system, however

System account (pseudo-user)

  • The system user account is similar to a normal user account.
  • The main different is that system user normally don’t have a home directory and can’t log in the way normal user do.
  • Many system users are created or associated or service to help run them more securely. Think of the situation this way: If a system user is created for the Apache service (the web server), and the account becomes compromised, the attacker will have access only to the web server and its config files. This could be worse if the Apache service were running as the root user; in that case, the attacker would have full access to the system. These are just some additional reasons why you should never truly need the root account unless there is a problem with the system.

Command

Description

1.        Useradd Creates user or system accounts
2.        Groupadd Creates a group
3.        Passwd Set a password or resets a password for a user account
4.        Gpasswd Set encrypt group password
5.        Usermod Modifies user accounts
6.        Groupmod Modifies the properties of a group
7.        Userdel Remove a user or system account
8.        Groupdel Delete a group
9.        Id Shows UID/GID for the group of a given user
10.    Chsh To change the user login SHELL
11.    Chage Enables you to modify the parameters surrounding passwords (complexity, age, expiration)
12.    Pwck Verifies the consistency of passwords across database file
13.    Users Currently logged in user displayed
14.    Groups Print the groups a user is in
15.    Newusers create bulk user using file method
16.    system-config-users Graphically add the user and group
17.    userinfo Graphically to change the user information
18.    su Switching user
19.    sudo Sudo user
20.   finger The finger displays information about the system users.
21.   groupmems The groupmems command allows a user to administer his/her own group membership list without the requirement of superuser privileges

User, Group and password configuration files

Directory and Files

Description

/etc/passwd The password for a user
/etc/group The group to which the user belongs
/etc/shadow Encrypted password file
/etc/gshadow Encrypted password file for groups
/etc/shells The login shells, such as BASH or TCSH
/etc/skel The default initialization files for the login shell, such as .bash_profile, .bashrc, and .bash_logout; includes many user setup directories and files such as .kde for KDE and Desktop for GNOME
/etc/login.defs Default login definitions for users
/etc/defaults/useradd Default user account creation
/etc/securetty To specify the which tty device allowed root login account access
/home The user’s own home directory

The password file

Syntax of /etc/passwd:               account:password:UID:GID:GECOS:directory:shell
  • It contains basic information every user.
  • Other user in this file may relate to services such as mail, ftp, and sshd.
  • There are 7 columns of information in this file.

1.             Username        Login name of the user

2.             Password         Encrypted password for the user’s account

3.             User ID                       Unique number assigned by the system

4.             Group ID                    Number used to identify the group to which the user belongs

5.             Comment        Any user information, such as the user’s full name

6.             Home              The user’s home directory

7.             LoginShell       Shell to run when the user logs in; this is the default     shell, usually /bin/bash

[root@server1 ~]# grep -i “ayyappan” /etc/passwd

ayyappan:x:500:500:K.P.AYYAPPAN:/home/ayyappan:/bin/bash

the password filed is actually just placeholder (with an x). The reason is that the passwords are actually in different file /etc/shadow.

TipsYou can find out which users are currently logged in with the commandw                     – detailed informationwho                 – detailed data

whoami

who am i

[root@server1 ~]# w

09:19:09 up  1:41,  2 users,  load average: 0.00, 0.00, 0.00

USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT

root     tty1     :0               07:42    1:41m  6.05s  6.05s /usr/bin/Xorg :

root     pts/0    :0.0             08:28    0.00s  0.02s  0.00s w

[root@server1 ~]# who

root     tty1         2012-07-24 07:42 (:0)

root     pts/0        2012-07-24 08:28 (:0.0)

[root@server1 ~]# whoami

Root

[root@server1 ~]# who am i

root     pts/0        2012-07-24 08:28 (:0.0)

The group file

Syntax of /etc/group

                              group_name:passwd:GID:user_list

  • Every Linux user is assigned to a group.
  • There are 4 columns of information in the file.

1.      Group name

2.      Password

3.      Group ID

4.      Group members

[root@server1 ~]# grep -i “skylark” /etc/group

skylark:x:501:babu

The shadow and gshadow  file

Syntax of /etc/shadow

                ayyappan:Ep6mckrOLChF.:10063:0:99999:7:::

/etc/shadow and /etc/gshadow

  • The passwords are kept in a separate file called /etc/shadow.
  • Access is restricted to the root user.
  • A Corresponding password file, called /etc/gshadow, is also maintained for groups that require passwords.
  • /etc/shadow 8columns information
  • /etc/gshadow 4columns information

1.      Username

2.      Password

3.      Password history

4.      Min days

5.      Max days

6.      Warn days

7.      Inactive

8.      disabled

[root@server1 ~]# grep -i “ayyappan” /etc/shadow

ayyappan:$6$UroKWL5t$NxKyZk8e70M3f81rkNTunNNE2pMvRQhX1KoqN8/7Ov7416NX/p0lYpyKFW1LeKF4/FD9mFFvUQSrIj2jkjzMb1:15545:0:99999:7:::

1.      Group name

2.      Password

3.      Groupd ID

4.      Group members

[root@server1 ~]# grep -i “skylark” /etc/gshadow

skylark:$6$m12bWKNx4p/wJJZ$0tQWZ2sKorkiaEDV3B/yhXnUi/8uXinUVKOF7GmoWZDhx4SmemuiiGpbEGB93RBYI0106NNVyBIzAR4K77Ry20::arun

TipsVipw, vigr      à        edit the password, group, shadow and gshadows fileOptions-g         –           edit group databse

-p         –           edit password database

-q         –           quit

-s         –           edit shadow and gshadow database

User Account Initialization

When a user is created, everything from the /etc/skel directory is copied to the user’s newly created home directory (usually /home/). You can modify these “skeleton” files or can add own custom files. The benefit here is that user creation becomes standardized, ensuring that polices are adhered to. The customizable files are broken down into two different sections:

User-specific files and system-wide settings

User-Specific files

After a user is created and his home directory is populated, that user can now customize those files to fit his own personal needs. For example, the user might like to have certain PATH values or specific environment variables set. The following three files allow a user to customize the login experience to his own style.

~/.bashrc                     –           Defines functions and aliased

~/.bash_profile                       –           Sets environment variables

~/.bash_logout                        –           Defines any commands that should be executed before the log out

[root@server1 ~]# useradd -c “K.P. AYYAPPAN ” ayyappan

[root@server1 ~]# passwd ayyappan

[root@server1 ~]# ls -a /home/ayyappan/

.  ..  .bash_logout  .bash_profile  .bashrc  .gnome2  .mozilla

[root@server1 ~]# ls -a /etc/skel/

.  ..  .bash_logout  .bash_profile  .bashrc  .gnome2  .mozilla

Editing these files allows each user to be unique I the way he operations. Because each file is stored in the user’s home directory, that file is limited to use by that single user. What happens, though, if there is standard that you’d like set when users start out? Glad you asked.

Global user configuration

Just as in the /etc/skel directory, you can edit the following three additional files to provide a more standardized format for your users:

/etc/bashrc      –           Defines functions and aliases

/etc/profile      –           Sets environment variables

/etc/profile.d   –           Specifies a directory that contains scripts that are called by the /etc/profile file.

These files help you make sure that your users receive everything they need and when they get started. If you require that settings be changed for your users, customizing these files is the way to go. Just make sure that when you’re editing files for distribution, you make sure you’re editing system-wide config files and not the config files within a user’s home directory.

Tips

[root@server1 ~]# ls -a /home/ayyappan/

.  ..  .bash_history  .bash_logout  .bash_profile  .bashrc  .gnome2  .mozilla

.bashrc            –           This file is used to controls user variable and other profile during his login session. If you want to execute any command automatically user logon set that command in this file. For example if user “ayyappan” wants to clear screen immediately after her login. He needs to add command at end of this file.

vim .bashrc
# add your command only in the end of file
clear

Create a user and set exit command in his .bashrc files. Now ask your friends login with this user. Exit commands will logout the user as soon as user will login and user never will be able to login.

.bash_profile        –              This script file instructs user session to check .bashrc file for user aliases and functions. Further its set user command path.  Add your own home directory in command path. Edit this file. For example user “ayyappan” wants here home directory should be check while executing commands he can add this line in here .bash_profile files.

vim .bash_profile

PATH=$PATH:$HOME/BIN:/home/ayyappan

 

 

.bash_logout          –              This file is used to clear the terminal after the exit of current user.

vim /home/ayyappan/.bash_logout

# ~/.bash_logout

clear

 

Tips

To stop the overwriting of the file

[root@server1 Desktop]# set -o noclobber

[root@server1 Desktop]# echo “ayyappan” > test

bash: test: cannot overwrite existing file

[root@server1 Desktop]# set +o noclobber

[root@server1 Desktop]# echo “ayyappan” > test

[root@server1 Desktop]# cat test

Ayyappan

To stop logout form ctrl+D in terminal

[root@server1 Desktop]# set -o ignoreeof

Press ctrl+D

[root@server1 Desktop]# Use “exit” to leave the shell.

[root@server1 Desktop]# set +o ignoreeof

Now press ctrl+D

The default login file /etc/login.defs

  • This file controls specific relating to system-wide user logins and passwords.

[root@server1 ~]# grep -v ^# /etc/login.defs

MAIL_DIR    /var/spool/mail

PASS_MAX_DAYS  99999

PASS_MIN_DAYS   0

PASS_MIN_LEN      5

PASS_WARN_AGE 7

UID_MIN                                 500

UID_MAX                             60000

GID_MIN                                 500

GID_MAX                             60000

CREATE_HOME      yes

UMASK           077

USERGROUPS_ENAB yes

ENCRYPT_METHOD SHA512

MD5_CRYPT_ENAB no

These values should all be self-explanatory. You can edit them if you don’t like the give defaults, but make sure you remember that these are local to this system and don’t apply on other systems on your network unless you change them there as well. Initialization files can save you a great deal of time so that you don’t have to create custom profile and scripts for individual users every time they are created. This process does take some planning ahead, however, and making sure that your file and custom scripts are distributed to all users (even if they have already been created).

Switching Accounts

  • “su”     enables you to run a command as another user or switch user accounts

Examples

su  username

su – username

  • The “su” commands move you into the root user account without initializing any of root’s path or shell variables.
  • The “su – “ commands everything is initialized as if you were logging in from the console.
  • “sudo” enables you to run a command as the root user

The default user add file /etc/defaults/useradd

[root@server1 ~]# cat /etc/default/useradd

# useradd defaults file

GROUP=100

HOME=/home

INACTIVE=-1

EXPIRE=

SHELL=/bin/bash

SKEL=/etc/skel

CREATE_MAIL_SPOOL=yes

To specify the which tty device allowed root login account access

[root@server1 Desktop]# cat /etc/securetty

console

vc/1

vc/2

vc/3

vc/4

vc/5

vc/6

vc/7

vc/8

vc/9

vc/10

vc/11

tty1

tty2

tty3

tty4

tty5

tty6

tty7

tty8

tty9

tty10

tty11

User and Group Management Command man and help file

[root@server1 Desktop]# useradd –usage

useradd: unrecognized option ‘–usage’

Usage: useradd [options] LOGIN

Options:

-b, –base-dir BASE_DIR       base directory for the home directory of the new account

-c, –comment COMMENT         GECOS field of the new account

-d, –home-dir HOME_DIR       home directory of the new account

-D, –defaults                print or change default useradd configuration

-e, –expiredate EXPIRE_DATE  expiration date of the new account

-f, –inactive INACTIVE       password inactivity period of the new account

-g, –gid GROUP               name or ID of the primary group of the new

account

-G, –groups GROUPS           list of supplementary groups of the new

account

-h, –help                    display this help message and exit

-k, –skel SKEL_DIR           use this alternative skeleton directory

-K, –key KEY=VALUE           override /etc/login.defs defaults

-l, –no-log-init             do not add the user to the lastlog and

faillog databases

-m, –create-home             create the user’s home directory

-M, –no-create-home          do not create the user’s home directory

-N, –no-user-group           do not create a group with the same name as

the user

-o, –non-unique              allow to create users with duplicate

(non-unique) UID

-p, –password PASSWORD       encrypted password of the new account

-r, –system                  create a system account

-s, –shell SHELL             login shell of the new account

-u, –uid UID                 user ID of the new account

-U, –user-group              create a group with the same name as the user

-Z, –selinux-user SEUSER     use a specific SEUSER for the SELinux user mapping

[root@server1 Desktop]# groupadd –usage

groupadd: unrecognized option ‘–usage’

Usage: groupadd [options] GROUP

Options:

-f, –force                   exit successfully if the group already exists,

and cancel -g if the GID is already used

-g, –gid GID                 use GID for the new group

-h, –help                    display this help message and exit

-K, –key KEY=VALUE           override /etc/login.defs defaults

-o, –non-unique              allow to create groups with duplicate

(non-unique) GID

-p, –password PASSWORD       use this encrypted password for the new group

-r, –system                  create a system account

[root@server1 Desktop]# userdel –usage

userdel: unrecognized option ‘–usage’

Usage: userdel [options] LOGIN

Options:

-f, –force                   force removal of files,

even if not owned by user

-h, –help                    display this help message and exit

-r, –remove                  remove home directory and mail spool

-Z, –selinux-user            remove SELinux user from SELinux user mapping

Groupdel  groupname

[root@server1 Desktop]# passwd –help

Usage: passwd [OPTION…]

-k, –keep-tokens       keep non-expired authentication tokens

-d, –delete            delete the password for the named account (root only)

-l, –lock              lock the named account (root only)

-u, –unlock            unlock the named account (root only)

-f, –force             force operation

-x, –maximum=DAYS      maximum password lifetime (root only)

-n, –minimum=DAYS      minimum password lifetime (root only)

-w, –warning=DAYS      number of days warning users receives before password

expiration (root only)

-i, –inactive=DAYS     number of days after password expiration when an account

becomes disabled (root only)

-S, –status            report password status on the named account (root only)

–stdin                 read new tokens from stdin (root only)

Help options:

-?, –help              Show this help message

–usage                 Display brief usage message

[root@server1 Desktop]# gpasswd –help

gpasswd: unrecognized option ‘–help’

Usage: gpasswd [option] GROUP

Options:

-a, –add USER                add USER to GROUP

-d, –delete USER             remove USER from GROUP

-r, –remove-password         remove the GROUP’s password

-R, –restrict                restrict access to GROUP to its members

-M, –members USER,…        set the list of members of GROUP

-A, –administrators ADMIN,…

set the list of administrators for GROUP

Except for the -A and -M options, the options cannot be combined.

[root@server1 Desktop]# usermod –usage

Usage: usermod [options] LOGIN

Options:

-c, –comment COMMENT         new value of the GECOS field

-d, –home HOME_DIR           new home directory for the user account

-e, –expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE

-f, –inactive INACTIVE       set password inactive after expiration

to INACTIVE

-g, –gid GROUP               force use GROUP as new primary group

-G, –groups GROUPS           new list of supplementary GROUPS

-a, –append                  append the user to the supplemental GROUPS

mentioned by the -G option without removing

him/her from other groups

-h, –help                    display this help message and exit

-l, –login NEW_LOGIN         new value of the login name

-L, –lock                    lock the user account

-m, –move-home               move contents of the home directory to the

new location (use only with -d)

-o, –non-unique              allow using duplicate (non-unique) UID

-p, –password PASSWORD       use encrypted password for the new password

-s, –shell SHELL             new login shell for the user account

-u, –uid UID                 new UID for the user account

-U, –unlock                  unlock the user account

-Z, –selinux-user            new SELinux user mapping for the user account

[root@server1 Desktop]# groupmod –usage

groupmod: unrecognized option ‘–usage’

Usage: groupmod [options] GROUP

Options:

-g, –gid GID                 change the group ID to GID

-h, –help                    display this help message and exit

-n, –new-name NEW_GROUP      change the name to NEW_GROUP

-o, –non-unique              allow to use a duplicate (non-unique) GID

-p, –password PASSWORD       change the password to this (encrypted)

PASSWORD

[root@server1 Desktop]# id –help

Usage: id [OPTION]… [USERNAME]

Print user and group information for the specified USERNAME,

or (when USERNAME omitted) for the current user.

-a              ignore, for compatibility with other versions

-Z, –context   print only the security context of the current user

-g, –group     print only the effective group ID

-G, –groups    print all group IDs

-n, –name      print a name instead of a number, for -ugG

-r, –real      print the real ID instead of the effective ID, with -ugG

-u, –user      print only the effective user ID

–help     display this help and exit

–version  output version information and exit

[root@server1 Desktop]# chsh –usage

chsh: unrecognized option ‘–usage’

Usage: chsh [ -s shell ] [ –list-shells ] [ –help ] [ –version ]

[ username ]

[root@server1 Desktop]# chage –usage

chage: unrecognized option ‘–usage’

Usage: chage [options] [LOGIN]

Options:

-d, –lastday LAST_DAY        set date of last password change to LAST_DAY

-E, –expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE

-h, –help                    display this help message and exit

-I, –inactive INACTIVE       set password inactive after expiration

to INACTIVE

-l, –list                    show account aging information

-m, –mindays MIN_DAYS        set minimum number of days before password

change to MIN_DAYS

-M, –maxdays MAX_DAYS        set maximim number of days before password

change to MAX_DAYS

-W, –warndays WARN_DAYS      set expiration warning days to WARN_DAYS

User and Groups Management Examples

1.      Create two user account and set password

[root@server1 ~]# useradd -c “R.B. Ayyappan Babu” ayyappan

[root@server1 ~]# passwd ayyappan

Changing password for user ayyappan.

New password:

BAD PASSWORD: it is WAY too short

BAD PASSWORD: is too simple

Retype new password:

passwd: all authentication tokens updated successfully.

[root@server1 ~]# useradd -c “T.V. REEGAN KUMAR” reegan

[root@server1 ~]# passwd reegan

Changing password for user reegan.

New password:

BAD PASSWORD: it is WAY too short

BAD PASSWORD: is too simple

Retype new password:

passwd: all authentication tokens updated successfully.

2.      Create two group and password

[root@server1 ~]# groupadd skylark

[root@server1 ~]# groupadd cordia

[root@server1 ~]# gpasswd skylark

Changing the password for group skylark

New Password:

Re-enter new password:

[root@server1 ~]# gpasswd cordia

Changing the password for group cordia

New Password:

Re-enter new password:

3.      Delete (remove) user password (without need password login user account)

[root@server1 ~]# passwd -d ayyappan

Removing password for user ayyappan.

passwd: Success

[root@server1 ~]# su – reegan

[reegan@server1 ~]$ su – ayyappan

[ayyappan@server1 ~]$ su – reegan

Password:

[reegan@server1 ~]$ logout

[ayyappan@server1 ~]$ logout

[reegan@server1 ~]$ logout

4.      Remove the group password

[root@server1 ~]# grep -i “skylark” /etc/gshadow

skylark:$6$ECeZYcwRCL/Je$ugbDKhVRsxf2t3wY1swVR6aCnjKvN2nnvJsmBwl28uNqBofoOT.EyO9k3bYdeU1DrH2D3WcHBJbC6/ILjbweQ/::

[root@server1 ~]# gpasswd -r skylark

[root@server1 ~]# grep -i “skylark” /etc/gshadow

skylark:::

5.      Lock and unlock user login password

First to check the status

[root@server1 Desktop]# passwd -S ayyappan

ayyappan PS 2012-10-01 0 99999 7 -1 (Password set, SHA512 crypt.)

[root@server1 Desktop]# passwd -l ayyappan           or         usermod –L ayyappan

Locking password for user ayyappan.

passwd: Success

[root@server1 Desktop]# su – reegan

[reegan@server1 ~]$ su – ayyappan

Password:

su: incorrect password

[root@server1 Desktop]# passwd -u ayyappan

Unlocking password for user ayyappan.

passwd: Warning: unlocked password would be empty.

passwd: Unsafe operation (use -f to force)

[root@server1 Desktop]# passwd -fu ayyappan or    usermod –U ayyappan

Unlocking password for user ayyappan.

passwd: Success

[root@server1 Desktop]# su – reegan

[reegan@server1 ~]$ su – ayyappan

[ayyappan@server1 ~]$

Or

[root@server1 Desktop]# passwd ayyappan

[root@server1 Desktop]# passwd reegan

[root@server1 Desktop]# usermod -L ayyappan

[root@server1 Desktop]# su – reegan

[reegan@server1 ~]$ su – ayyappan

Password:

su: incorrect password

[reegan@server1 ~]$ logout

[root@server1 Desktop]# usermod -U ayyappan

[root@server1 Desktop]# su – reegan

[reegan@server1 ~]$ su – ayyappan

Password:

[ayyappan@server1 ~]$ logout

[reegan@server1 ~]$ logout

6.      Delete the username and groupname

[root@server1 Desktop]# userdel -rf ayyappan

[root@server1 Desktop]# userdel -rf reegan

[root@server1 Desktop]# groupdel cordia

[root@server1 Desktop]# groupdel skylark

7.      To change the username “ayyappan” to “babu” and group name “rooman” to “skylark”

[root@server1 ~]# usermod -l babu ayyappan

[root@server1 ~]# groupmod -n skylark rooman

[root@server1 ~]# grep -i “ayyappan” /etc/passwd

babu:x:500:500::/home/ayyappan:/bin/bash

[root@server1 ~]# grep -i “skylark” /etc/group

skylark:x:501:

8.      User “ayyappan” add to primary group “skylark

User “babu” add to primary and secondary group “skylark” and “cordia”

[root@server1 Desktop]# usermod -g skylark ayyappan

[root@server1 Desktop]# usermod -G cordia babu

[root@server1 Desktop]# usermod -G cordia,skylark babu

9.      To check the user id (UID) and (GID) then change.

RHEL default is 500 and maximum limit is 65534.

[root@server1 Desktop]# id ayyappan

uid=500(ayyappan) gid=502(skylark) groups=502(skylark)

[root@server1 Desktop]# id babu

uid=501(babu) gid=501(babu) groups=501(babu),502(skylark),503(cordia)

[root@server1 Desktop]# usermod -u 700 ayyappan

[root@server1 Desktop]# usermod -u 701 babu

[root@server1 Desktop]# groupmod -g 900 skylark

[root@server1 Desktop]# groupmod -g 901 cordia

[root@server1 Desktop]# id ayyappan

uid=700(ayyappan) gid=900(skylark) groups=900(skylark)

[root@server1 Desktop]# id babu

uid=701(babu) gid=501(babu) groups=501(babu),900(skylark),901(cordia)

[root@server1 Desktop]# groupmod -g 701 babu

[root@server1 Desktop]# id babu

uid=701(babu) gid=701(babu) groups=701(babu),900(skylark),901(cordia)

10.  Remove user from group

[root@server1 /]# usermod -g skylark ayyappan

[root@server1 /]# usermod -G skylark,cordia babu

[root@server1 /]# id ayyappan

uid=502(ayyappan) gid=504(skylark) groups=504(skylark)

[root@server1 /]# id babu

uid=503(babu) gid=503(babu) groups=503(babu),504(skylark),505(cordia)

[root@server1 /]# gpasswd -d ayyappan skylark

Removing user ayyappan from group skylark

gpasswd: user ‘ayyappan’ is not a member of ‘skylark’

[root@server1 /]# gpasswd -d babu skylark

Removing user babu from group skylark

[root@server1 /]# gpasswd -d babu cordia

Removing user babu from group cordia

[root@server1 /]# id babu

uid=503(babu) gid=503(babu) groups=503(babu)

11.  Move content of the home directory to the new location user for “ayyappan”

[root@server1 ~]# ls -l /home/

total 4

drwx——. 4 ayyappan ayyappan 4096 Jul 25 09:51 ayyappan

[root@server1 ~]# mkdir /newhome

[root@server1 ~]# usermod -m -d /newhome/ayyappan ayyappan

[root@server1 ~]# ls -l /home

total 0

[root@server1 ~]# ls -l /newhome/

total 4

drwx——. 4 ayyappan ayyappan 4096 Jul 25 09:51 ayyappan

12.  To create user without home directory and change the shell no login that user

[root@server1 ~]# useradd -M ftpuser

[root@server1 ~]# ls -l /home/

total 0

[root@server1 ~]# passwd ftpuser

[root@server1 ~]# su – ftpuser

su: warning: cannot change directory to /home/ftpuser: No such file or directory

-bash-4.1$ echo $SHELL

/bin/bash

[root@server1 ~]# chsh –l                  (to check the shell)

/bin/sh

/bin/bash

/sbin/nologin

/bin/tcsh

/bin/csh

[root@server1 ~]# chsh -s /sbin/nologin ftpuser

Changing shell for ftpuser.

Shell changed.

[root@server1 ~]# su – ftpuser

su: warning: cannot change directory to /home/ftpuser: No such file or directory

This account is currently not available.

13.  Create user without same group name as user

[root@server1 /]# useradd -N ayyappan; passwd ayyappan;id ayyappan

Changing password for user ayyappan.

New password:

BAD PASSWORD: it is WAY too short

BAD PASSWORD: is too simple

Retype new password:

passwd: all authentication tokens updated successfully.

uid=502(ayyappan) gid=100(users) groups=100(users)

14.  Which command to check the /etc/passwd and /etc/shadow file have proper format and contain valid data.

[root@server1 Desktop]# pwck

user ‘adm’: directory ‘/var/adm’ does not exist

user ‘uucp’: directory ‘/var/spool/uucp’ does not exist

user ‘gopher’: directory ‘/var/gopher’ does not exist

user ‘avahi-autoipd’: directory ‘/var/lib/avahi-autoipd’ does not exist

user ‘pulse’: directory ‘/var/run/pulse’ does not exist

user ‘saslauth’: directory ‘/var/empty/saslauth’ does not exist

pwck: no changes

pwck [options]

-q         –           report errors only

-r          –           read only mode

-s         –           sort entries in /etc/passwd and /etc/shadow by UID

15.  To show the user creating default option and how it change

[root@server1 Desktop]# useradd -D

GROUP=100

HOME=/home

INACTIVE=-1

EXPIRE=

SHELL=/bin/bash

SKEL=/etc/skel

CREATE_MAIL_SPOOL=yes

[root@server1 Desktop]# mkdir /changehome

[root@server1 Desktop]# chsh -l

/bin/sh

/bin/bash

/sbin/nologin

/bin/tcsh

/bin/csh

[root@server1 Desktop]# useradd -D -b /changehome/         [change default home directory]

[root@server1 Desktop]# useradd -D -s /bin/sh                     [change default shell]

[root@server1 ~]# useradd -D

GROUP=100

HOME=/changehome/

INACTIVE=-1

EXPIRE=

SHELL=/bin/sh

SKEL=/etc/skel

CREATE_MAIL_SPOOL=yes

[root@server1 ~]# useradd redhat

[root@server1 ~]# ls /changehome/

Redhat

[root@server1 ~]# su redhat

sh-4.1$ echo $SHELL

/bin/sh

sh-4.1$

16.  Bulk user and group add using for loop method

[root@server1 Desktop]# for USER in reegan mani anbu

> do

> useradd $USER

> echo “password” | passwd –stdin $USER

> done

Changing password for user reegan.

passwd: all authentication tokens updated successfully.

Changing password for user mani.

passwd: all authentication tokens updated successfully.

Changing password for user anbu.

passwd: all authentication tokens updated successfully.

[root@server1 Desktop]# for GROUP in skyark cordia

> do

> groupadd $GROUP

> done

17.  Manage Linux password expiration and aging using “chage” command.

List the password and its related details for a user

[root@server1 Desktop]# chage -l reegan

Last password change                                                             : Jul 26, 2012

Password expires                                                                    : never

Password inactive                                                                   : never

Account expires                                                                      : never

Minimum number of days between password change                        : 0

Maximum number of days between password change                       : 99999

Number of days of warning before password expires                        : 7

The reegan password is set to expire 10 days from the last password change.

[root@server1 Desktop]# chage -M 10 reegan

[root@server1 Desktop]# chage -l reegan

Last password change                                                             : Jul 26, 2012

Password expires                                                                    : Aug 05, 2012

Password inactive                                                                   : never

Account expires                                                                      : never

Minimum number of days between password change                        : 0

Maximum number of days between password change                       : 10

Number of days of warning before password expires                        : 7

Set the account expiry date for an user

[root@server1 Desktop]# chage -E 2012-08-06 reegan

[root@server1 Desktop]# chage -l reegan

Last password change                                                             : Jul 26, 2012

Password expires                                                                    : Aug 05, 2012

Password inactive                                                                   : never

Account expires                                                                      : Aug 06, 2012

Minimum number of days between password change                        : 0

Maximum number of days between password change                       : 10

Number of days of warning before password expires                        : 7

Set the account password inactive x number of days

[root@server1 Desktop]# chage -M 10 reegan

[root@server1 Desktop]# chage -l reegan

Last password change                                                             : Jul 26, 2012

Password expires                                                                    : Aug 05, 2012

Password inactive                                                                   : Aug 15, 2012

Account expires                                                                      : never

Minimum number of days between password change                        : 0

Maximum number of days between password change                       : 10

Number of days of warning before password expires                        : 7

Disable all default

[root@server1 Desktop]# chage -m 0 -M 99999 -I -1 -E -1 reegan

[root@server1 Desktop]# chage -l reegan

Last password change                                                             : Jul 26, 2012

Password expires                                                                    : never

Password inactive                                                                   : never

Account expires                                                                                  : never

Minimum number of days between password change                        : 0

Maximum number of days between password change                       : 99999

Number of days of warning before password expires                        : 7

18.  How to add bulk user using “newusers” command.

[root@server1 Desktop]# touch adduser.txt              [create one text file]

[root@server1 Desktop]# vim adduser.txt                 [add user details /etc/passwd file model]

babu:password:501:501::/home/babu:/bin/bash

kumar:password:502:502::/home/kumar:/bin/bash

:wq!

[root@server1 Desktop]# newusers adduser.txt        [use “newusers” command]

[root@server1 Desktop]# ls /home/

babu  kumar  ayyappan

19.  Groupmems command examples

#groupmems [options] [action]

[options]

-g groupname

[action]

-a add username

-d delete username

-l list

-p purge all members from the groups

[root@server1 Desktop]# groupmems -g ibm -a ayyappan

[root@server1 Desktop]# groupmems -g ibm -a kumar

[root@server1 Desktop]# groupmems -g ibm -l

babu  ayyappan  kumar

ACL

Access Control List

[root@server1 Desktop]# for USER in ayyappan babu reegan

> do

> useradd $USER

> echo “password” | passwd –stdin $USER

> done

Changing password for user ayyappan.

passwd: all authentication tokens updated successfully.

Changing password for user babu.

passwd: all authentication tokens updated successfully.

Changing password for user reegan.

passwd: all authentication tokens updated successfully.

[root@server1 Desktop]# groupadd skylark

[root@server1 Desktop]# for USER in ayyappan babu reegan

> do

> usermod -G skylark $USER

> done

[root@server1 Desktop]# id ayyappan

uid=500(ayyappan) gid=500(ayyappan) groups=500(ayyappan),503(skylark)

[root@server1 Desktop]# id babu

uid=501(babu) gid=501(babu) groups=501(babu),503(skylark)

[root@server1 Desktop]# id reegan

uid=502(reegan) gid=502(reegan) groups=502(reegan),503(skylark)

[root@server1 Desktop]# mkdir /example

[root@server1 Desktop]# chown ayyappan:skylark /example

[root@server1 Desktop]# ls -ld /example

drwxr-xr-x. 2 ayyappan skylark 4096 Aug  3 12:34 /example

[root@server1 Desktop]# su – ayyappan

[ayyappan@server1 ~]$ cd /example/

[ayyappan@server1 example]$ mkdir account

[ayyappan@server1 example]$ ll

total 4

drwxrwxr-x. 2 ayyappan ayyappan 4096 Aug  3 12:36 account

[ayyappan@server1 example]$ getfacl account

# file: account

# owner: ayyappan

# group: ayyappan

user::rwx

group::rwx

other::r-x

[ayyappan@server1 example]$ setfacl -m u:reegan:rwx account

[ayyappan@server1 example]$ setfacl -m g:skylark:r-x account

[ayyappan@server1 example]$ setfacl -m o:— account

[ayyappan@server1 example]$ getfacl account

# file: account

# owner: ayyappan

# group: ayyappan

user::rwx

user:reegan:rwx

group::rwx

group:skylark:r-x

mask::rwx

other::—

[ayyappan@server1 example]$ su – reegan

Password:

[reegan@server1 ~]$ cd /example/

[reegan@server1 example]$ cd account/

[reegan@server1 account]$ touch test

[reegan@server1 account]$ ll

total 0

-rw-rw-r–. 1 reegan reegan 0 Aug  3 12:39 test

[reegan@server1 account]$ su – babu

Password:

[babu@server1 ~]$ cd /example/account/

[babu@server1 account]$ touch babutest

touch: cannot touch `babutest’: Permission denied

[babu@server1 account]$ ll

total 0

-rw-rw-r–. 1 reegan reegan 0 Aug  3 12:39 test

[babu@server1 account]$ logout

[reegan@server1 account]$ logout

[ayyappan@server1 example]$ logout

[root@server1 Desktop]# useradd kumar; passwd kumar

Changing password for user kumar.

New password:

BAD PASSWORD: it is based on a dictionary word

Retype new password:

passwd: all authentication tokens updated successfully.

[root@server1 Desktop]# su – kumar

[kumar@server1 ~]$ cd /example/account/

-bash: cd: /example/account/: Permission denied

[kumar@server1 ~]$ logout

RHCE Linux – nologin file in etc directory and securetty file

You are the administrator of example.com domain. Configure to deny local login to all normal users on your domain server. As well as allow to root login only on First Terminal.

First login from root user and run these command

[root@server1 Desktop]# touch /etc/nologin

[root@server1 Desktop]# cat /etc/securetty

console

vc/1

vc/2

vc/3

vc/4

vc/5

vc/6

vc/7

vc/8

vc/9

vc/10

vc/11

tty1

#tty2

#tty3

#tty4

#tty5

#tty6

#tty7

#tty8

#tty9

#tty10

#tty11

:wq!

[root@server1 Desktop]# useradd ayyappan

[root@server1 Desktop]# echo “redhat” | passwd –stdin ayyappan

[root@server1 Desktop]# init 3

Alt + F2

File and directories permission

              

Linux file and directories permission is two types

1.       Basic permission

2.       Special permission

Linux permission separate three categories

Users, groups, others

Basic Permission command

1.      Chmod           ->         changes the permission file and directories

2.      Chown            ->         change the file “owner(user)” and “group”

3.      Chgrp ->         change the file “group ownership”

4.      Umask            ->         defines or displays the default permission for creation of files or directories

Read               4          r

Write              2          w

Execute           1          x

Octal value

File permission set

Description

0

1

–x

Execute

2

-w-

Write

3

-wx

Write, execute

4

r–

Read

5

r–

Read, execute

6

rw-

Read,write

7

rwx

Read,write,execute

Special Permission

Three special types of permissions are available for executable files and public directories setuid, setgid and sticky bit.

Setuid             s           4          this flag is used to allow multi user access

Setgid              s           2          this flag is used to allows multi group access

Sticy bit          t           1          this flag prevent accidental delete by users or groups

s” permission

The “s” permission is used on directories to keep the user or group ID for a file created in the directories.

To set the user ID for any new files created in the directory to the owner of the directories use the

“chmod u+s directory (or file)” command.

To set the group ID for any new files created in the directory to the directory group use the

“chmod g+s directory (or file)” command.

“t” permission

Sticky bit is used for directories to protect files within them.

Files in a directory with the sticky bit set can only be deleted or renamed by the root user or the owner of the directory.

Using command “chmod +t directory (or file)”

Examples

1.      How to check and change the file permission using symbolic and numeric method?

Chmod –options mode file

-v         –           output

-R        –           change file and directories recursively

[root@server1 Desktop]# mkdir /example

[root@server1 Desktop]# ls -ld /example

drwxr-xr-x. 2 root root 4096 Jul 29 10:32 /example

[root@server1 Desktop]# cd /example/

[root@server1 example]# touch testfile

[root@server1 example]# ll

total 0

-rw-r–r–. 1 root root 0 Jul 29 10:33 testfile

Note:

Default directory permission is 755(user=rwx,group=r-x,others=r-x)

Default file permission is 644 (user=rw-,group=r–,others=r–)

Assign all permission user, group and other can read, write and execute

[root@server1 Desktop]# chmod -v 777 /example    or        chmod –v ugo+ /example

mode of `/example’ retained as 0777 (rwxrwxrwx)

[root@server1 example]# ls -ld /example

drwxrwxrwx. 2 root root 4096 Jul 29 10:33 /example

remove the group and other side write permission

[root@server1 Desktop]# chmod -v go-w /example

mode of `/example’ changed to 0755 (rwxr-xr-x

Remove the execute permission in others

[root@server1 Desktop]# chmod -v o-x /example

mode of `/example’ changed to 0754 (rwxr-xr–)

Assign the all permission in the file read, write and execute

[root@server1 Desktop]# cd /example/

[root@server1 example]# ll

total 0

-rw-r–r–. 1 root root 0 Jul 29 10:33 testfile

[root@server1 example]# chmod -v ugo+x testfile

mode of `testfile’ changed to 0755 (rwxr-xr-x)

[root@server1 example]# ll

total 0

-rwxr-xr-x. 1 root root 0 Jul 29 10:33 testfile

All permission assign all directory, sub directory and file using recursive mode ‘R’

[root@server1 /]# chmod -Rv 777 /example

mode of `/example’ retained as 0777 (rwxrwxrwx)

mode of `/example/testfile’ changed to 0777 (rwxrwxrwx)

2.      How to check and change ownership (user) and group file permission?

Check the ownership and group permission

[root@server1 /]# ls -ld /example

drwxrwxrwx. 2 root root 4096 Jul 29 10:33 /examp

Assign the ownership permission using “chown” command

[root@server1 /]# chown -v madhu /example

changed ownership of `/example’ to madhu

[root@server1 /]# ls -ld /example

drwxrwxrwx. 2 madhu root 4096 Jul 29 10:33 /example

Assign the owner and group permission using “chown” command

[root@server1 /]# usermod -G skylark madhu

[root@server1 /]# chown -v madhu:skylark /example

changed ownership of `/example’ to madhu:skylark

[root@server1 /]# ls -ld /example

drwxrwxrwx. 2 madhu skylark 4096 Jul 29 10:33 /example

Assign the group permission only using “chgrp” command

[root@server1 /]# chgrp -v root /example

changed group of `/example’ to root

[root@server1 /]# ls -ld /example

drwxrwxrwx. 2 madhu root 4096 Jul 29 10:33 /example

[root@server1 /]# chgrp -v skylark /example

changed group of `/example’ to skylark

How to change that directory contains files and subdirectory?

[root@server1 /]# chown -Rv root:root /example/

changed ownership of `/example/testfile’ to root:root

changed ownership of `/example/’ to root:root

3.      “umask” command examples

“umask” default value                         = 022

Default files permission                      = 644  (rw-r–r–)

Default folder permission       = 755  (drwx-r-xr-x)

How to assign the default permission particular folder

Default permission u=rwx, g=rwx, o=r (774)

U=rwx,g=rwx,o=rwx                        777

U=rwx,g=rwx,o=r–               774  –

——————————-

Umask value  =                      003

——————————-

This subtracts 003 from the system defaults for files and directories 666 and 777.

[root@server1 Desktop]# mkdir -v /example

mkdir: created directory `/example’

[root@server1 Desktop]# ls -ld /example

drwxr-xr-x. 2 root root 4096 Jul 29 17:51 /example

[root@server1 Desktop]# chmod -v 774 /example

mode of `/example’ changed to 0774 (rwxrwxr–)

[root@server1 Desktop]# cd /example/

[root@server1 example]# touch test

[root@server1 example]# mkdir testdir

[root@server1 example]# ll

total 4

-rw-r–r–. 1 root root    0 Jul 29 17:55 test

drwxr-xr-x. 2 root root 4096 Jul 29 17:55 testdir

[root@server1 example]# umask -S 003 /example/

u=rwx,g=rwx,o=r

[root@server1 example]# touch test-1

[root@server1 example]# mkdir testdir-1

[root@server1 example]# ll

total 8

-rw-r–r–. 1 root root    0 Jul 29 17:55 test

-rw-rw-r–. 1 root root    0 Jul 29 17:56 test-1

drwxr-xr-x. 2 root root 4096 Jul 29 17:55 testdir

drwxrwxr–. 2 root root 4096 Jul 29 17:56 testdir-1

4.      Example for the “s” and “t” permission

[root@server1 example]# ls -ld /example/

drwxrwxr–. 4 root root 4096 Jul 29 18:05 /example/

assign full permission

[root@server1 example]# chmod -v 777 /example/

mode of `/example/’ changed to 0777 (rwxrwxrwx)

[root@server1 example]# su – ayyappan

[ayyappan@server1 ~]$ cd /example/

[ayyappan@server1 example]$ cat > ayyappan

this is ayyappan file

[ayyappan@server1 example]$ su – madhu

[madhu@server1 ~]$ cd /example/

[madhu@server1 example]$ cat > madhu

this is madhu file

[madhu@server1 example]$ ll

total 8

-rw-rw-r–. 1 ayyappan ayyappan 20 Jul 29 19:07 ayyappan

-rw-rw-r–. 1 madhu  madhu  19 Jul 29 19:08 madhu

[madhu@server1 example]$ logout

[ayyappan@server1 example]$ logout

Assign “s” permission

[root@server1 example]# chmod ug+s /example/

[root@server1 example]# ls -ld /example/

drwsrwsrwx. 2 root root 4096 Jul 29 19:12 /example/

[root@server1 example]# su – ayyappan

[ayyappan@server1 ~]$ cd /example/

[ayyappan@server1 example]$ touch ayyappan-s-per

[ayyappan@server1 example]$ ll ayyappan-s-per

-rw-rw-r–. 1 ayyappan root 0 Jul 29 19:11 ayyappan-s-per

[ayyappan@server1 example]$ logout

Assign “t” sticky bit permission

[root@server1 example]# chmod +t /example

[root@server1 example]# ls -ld /example/

drwsrwsrwt. 2 root root 4096 Jul 29 19:12 /example/

[root@server1 example]# su – ayyappan

[ayyappan@server1 ~]$ cd /example/

[ayyappan@server1 example]$ ll

total 8

-rw-rw-r–. 1 ayyappan ayyappan 20 Jul 29 19:07 ayyappan

-rw-rw-r–. 1 ayyappan root    0 Jul 29 19:11 ayyappan-s-per

-rw-rw-r–. 1 madhu  madhu  19 Jul 29 19:08 madhu

-rw-rw-r–. 1 madhu  madhu   0 Jul 29 19:09 madhufile

[ayyappan@server1 example]$ rm -rf madhufile

rm: cannot remove `madhufile’: Operation not permitted

[ayyappan@server1 example]$ rm -rf ayyappan

[ayyappan@server1 example]$ logout

[root@server1 example]#

Now remove the “t” sticky bit permission

[root@server1 example]# chmod -v -t /example/

mode of `/example/’ changed to 6777 (rwsrwsrwx)

[root@server1 example]# su – madhu

[madhu@server1 ~]$ cd /example/

[madhu@server1 example]$ ll

total 4

-rw-rw-r–. 1 ayyappan root   0 Jul 29 19:11 ayyappan-s-per

-rw-rw-r–. 1 madhu  madhu 19 Jul 29 19:08 madhu

-rw-rw-r–. 1 madhu  madhu  0 Jul 29 19:09 madhufile

[madhu@server1 example]$ rm -rf ayyappan-s-per

[madhu@server1 example]$ logout

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

SWAP Partition

Linux uses the SWAP space configured on one or more hard drive partitions to store in frequently used programs and data. SWAP space can extend the amount of effective RAM on your system.

Normally, Linux (on a 32bit Intel-style computer) can use a maximum 4GB of SWAP space in partitions no larger than 2GB. This 4GB cab be spread over a maximum of eight partitions. The typical rule of thumb suggests that SWAP space should be two times the amount of RAM.
Example
     1GB physical RAM = 2GB SWAP space
Two method of SWAP partition creating
1.  Fdisk utility
2.  File method
#fdisk –l
/dev/sda1  à boot
/dev/sda2  à /
/dev/sda3  à Linux SWAP
/dev/sda4  à Extended partition
#fdisk /dev/sda
n
+1024M
t
5
82
p
w
#partprobe /dev/sda        or         #partx –a /dev/sda
#reboot
#mkswap –L SWAP /dev/sda5
#swapon /dev/sda5          or         #swapon –a
#vim /etc/fstab
LABEL=SWAP-sda5 swap swap defaults   0 0
Or
/dev/sda5       swap swap defaults   0 0
#mount –a
#swapoff /dev/sda5
Remove entry form “/etc/fstab”
#reboot
Create SWAP space from file method
First create a blank file
#touch /swap
#dd if=/dev/zero of=/swap bs=1M count=100
#mkswap  –L  SWAP  /swap
#swapon /swap
#vim /etc/rc.local
Swapon /swap
Swap run time verify status
#cat /proc/swaps
/dev/sda3  partition  4194296    0    -1
/swap      file       102392                  0      -2