Managing Users and Groups - Beginning the Linux Command Line, Second edition (2015)

Beginning the Linux Command Line, Second edition (2015)

CHAPTER 6. Managing Users and Groups

This chapter is about the user environment. You will learn how to set up a user account, which is an important task, even if you are not a computer administrator. You will also learn about the way authentication is handled using the PAM (pluggable authentication module) and nsswitch systems, as well as explore the configuration files that contain the definition of the working environment for your users. For instance, you will see how to provide a user with default settings by using the /etc/profile file and all related files. Also, you will get a look at the sudomechanism, which allows you to perform administration tasks without needing to log in as root.

Setting Up User Accounts

Before starting to discuss how to create user accounts, it is important to understand what a user is. On Linux a user is not always exclusively bound to a person that logs in to a computer. A user account is an entity that is created on a Linux system to grant permissions that allow the user to perform specific tasks. User accounts exist for people that need access to a computer, but also for services that need access to specific files and other system resources.

There are different ways to create a user. You can use one of the commands that are available, like useradd or adduser. (useradd is the default utility; some distributions have a utility named adduser, which in most cases is just a symbolic link to useradd. On Ubuntu,adduser is an interactive script that walks the person that invokes it through the different steps that are needed to create user account.)

It is also possible to create a user by editing the user database directly. This database is stored in the two configuration files, /etc/passwd en /etc/shadow, and you can modify it using the vipw command, or just plain vi. If you decide to change the configuration files directly, it’s a good idea to use vipw, not plain The vipw command does a check on the consistency of the configuration files once you are done, which is not the case for vi. Also, vipw writes to a temporary file, which prevents locking problems caused by other users accessing the file simultaneously.

Before taking your first steps in user management, you need to understand a little bit more about users and their properties. In the following sections, you’ll first learn which properties a user has. Following that, you’ll read how to manage users using commands like useradd andusermod, and how to modify the user database directly.

Understanding Users and Their Properties

Before starting to create users, it makes sense to know about the different properties that Linux users typically have. These properties are stored in the /etc/passwd and /etc/shadow files. Based on this knowledge, you’ll be better able to create the user according to your specific needs. When creating a user, you need to provide a value for the following properties, which you can read more about in the next sections:

· Username

· Password

· User ID (UID)

· ID of the primary group of the user

· Comment field

· Home directory

· Default shell

Username

Every user has a unique username. This name is used when the user authenticates to the system. In most cases, it will be a real name, like lori, but you can use a numeric name as well, such as an employee number. I recommend using letters and numbers only in the username. After installation, your computer will already have some usernames. One of them is the user name root, which is used for system administration purposes.

You’ll also find that some other system accounts are created by default. These are needed for system tasks and services, and you should never change or remove them. The names of these accounts depend on the services that are installed on your computer. In general, you can recognize them because they have a User IDentification number (UID) that is lower than 500 or 1000.

Password

Every user should have a password. This is required for authentication to the Linux system. When choosing a password, make sure that it is strong. A strong password is a password that can’t be found in any dictionary and is a combination of upper and lowercase letters as well as numbers. User passwords should be difficult to guess, and in general it is a good idea not to use passwords shorter than six characters. When setting a password, the administrator can set some properties for the password as well, such as the expiration date of the password. The user root can also disable the password if he or she doesn’t want the user to log in anymore. As an administrator, you can determine how long it takes before the user password expires.

The password and related settings are storedin the /etc/shadow file, which is covered later in this chapter.

UID

The UID is another major piece of information when creating a user. For your computer, this is the only way to identify a user; usernames are just a convenience for humans (who can’t quite handle numbers as well as a computer does). In general, all users need a unique UID. Most Linux distributions start generating UIDs for local users at 1000. In the default Linux configuration, a total of 16 bits was available for creating UIDs. This means that the highest available UID is 65535. On modern Linux distributions, UIDs beyond 65535 can be used. If you exceed this limit, you’ll need a directory server such as OpenLDAP. Typically, UIDs below 500 are reserved for system accounts that your computer needs to start services such as a web server or the printing process. The UID 0 is also a special one: the user with it has complete administrative permissions to the computer. UID 0 is typically reserved for the user root.

Group Membership

On Linux, all users must be a member of at least one group. This is referred to as the primary group assignment. Apart from the primary group, users can be a member of additional groups as well. The primary group setting is stored in the /etc/passwd file, and secondary groups are in the/etc/group file, which is discussed later in this chapter.

Gecos Field

The official name for the next field in the documentation is the General Electric Comprehensive Operating System (Gecos) field, and it is used to include some comment to make it easier to identify the user. It is a good habit to put a description of the user account in this field, although you can do without it as well. The finger utility (see Chapter 2) displays the content of the Gecos field if someone requests information about a user. You can put in any description you like.

Home Directory

Most users have a home directory. This directory, which typically resides in /home, is where users can store files. You will also find that some default configuration files often exist in the user’s home directory. These configuration files make the user’s default environment. Also, some subdirectories are created that allow users to store different types of files. Apart from the home directory, the only directory where users are allowed to write files is /tmp. You are free to change this at will, of course; you’ll read how to do so in Chapter 7, which is about permissions. InListing 6-1, you can see an example of the contents of the home directory of user linda, which is /home/linda, with all of the default files that were copied into that directory. These default files are stored in the /etc/skel directory. When a user account is created, the contents of the /etc/skel directory is copied to the users home directory.

Listing 6-1. Example of a Home Directory and Its Contents

nuuk:/home/linda # ls
.bash_history .fonts .muttrc .xim.template public_html
.bashrc .gnu-emacs .profile .xinitrc.template
.dvipsrc .inputrc .urlview .xtalkrc
.emacs .kermrc .xcoralrc Documents
.exrc .mozilla .xemacs bin

Shell

Any user who needs to log in to your computer needs a shell (not all users need to log in though). This is the environment where the user types commands that need to be executed on the computer. SUSE and Red Hat use /bin/bash as the default shell, where Ubuntu uses the /bin/dashshell. Most users won’t notice the difference; after all, the shell is just a command interpreter.

You should know that not every user needs a shell. A user with a shell is allowed to log in locally to your system and access any files and directories stored on that system. If you’reusing your system as a Samba file server, for example, the user will typically never need to log in to your system directly. In this case, it is a good idea to use /bin/false or /sbin/nologin as the default shell; this will prohibit users from ever logging in to your system.

Commands for User Management

For user management, your distribution provides some commands. If you want to add users from the command line, useradd is just the ticket. You can use this command to add a user and all of the properties mentioned previously. The other commands for user management are just as convenient. Following is an overview of all commands available to manage user accounts:

· useradd: Adds users to the local authentication system

· usermod: Modifies properties for users

· userdel: Deletes users from a system

· passwd: Modifies passwords for users

Using useradd is simple. In its easiest form, it just takes the name of a user as its argument; thus useradd zeina creates a user called zeina to the system. Most Linux distributions will create a home directory for the user in /home. If you’re using SUSE Linux (or any other distribution where you notice that a home directory hasn’t been created), use the option -m with useradd to ensure the creation of the home directory.

If a user has been added without a home directory, unfortunately, there is no easy way to create that home directory later. (There is a hard way though. You’ll understand all about that after reading Chapter 7, which is about file system permissions.) This hard way consists of copying over all files in the /etc/skel directory to the user home directory, and applying correct permissions to these files after they have been copied. Following is a list of the most important options that you can use with useradd:

· -c comment: Allows you to enter a comment field to the user account. If this comment has white spaces or other special characters, make sure that they are in quotations. Information set this way can be requested with the finger command, and this comment field typically is used for the user’s name. You will notice that for some of the system processes, this field gives a short description of the process that is responsible for the user account.

· -e date: Sets the expiration date for the user. Use this option to automatically disable the user’s account on the specified date. This can be entered in the YYYY-MM-DD format or as the number of days since January 1, 1970. You’ll probably prefer to specify the date.

· -G groups: Makes the user a member of some additional groups. By default, the user becomes a member of only those groups listed in /etc/default/useradd.

· -g gid: Sets the primary group of a user (see the section “Group Membership” later in this chapter for more details).

· -m: Creates a home directory automatically. For instance, if you use this option when creating a user named linda, the home directory that is created is /home/linda.

Image Note The useradd command also has the option -p. If you read the man page, you’ll notice that this option can be used to change the password of a user. There is a catch though; the -p option can only be used to specify a password that is already encrypted by a program that uses thecrypt (3) function. This is not typically the way you want to change a password, so use the passwd command instead.

If you understand the useradd command, it’s not hard to understand usermod as well. This command works on the same user properties as useradd. However, you will notice that some options are not available with usermod. For instance, you can’t use usermod to create a home directory for a user who doesn’t have a home directory yet.

If you want to change password related properties for a user, use chage instead of usermod. This command offers all you need to define validity settings for user passwords. In exercise 6-1 you’ll learn how to work with this command.

If a user account is no longer needed, you can use userdel as follows: to remove a user with the name chris, issue userdel chris. By default, userdel does not remove the home directory and mail spool for the user. If you want these to be removed as well, use the option -r. So,userdel -r chris removes chris and his home directory as well. You will notice that this does not work if in chris’s home directory files exist that are not owned by this user. If you are sure that you want to remove these as well, add the -f option.

Image Tip Before removing a user and his or her home directory, it might be a good idea to make a backup of that home directory and all other files that the user has created first. The following command shows how to do this. It uses find to locate all files that are owned by user chris and copies them to the directory /root/chris. This location ensures that no one else but root has permissions to read and, if needed, recover these files:

find / -user chris -exec cp {} /root/chris \;

Chapter 4 has more details on the find command.

EXERCISE 6-1: CREATING USERS

1. Open a root shell and type useradd lara.

2. Still as root, type su - lara to log in as user lara. Verify that the user has a home directory. To do this, type pwd, you should see /home/lara as the result. If this is not the case, as root type userdel lara and useradd -m lara, to create the user again but this time with a home directory as well.

3. Still from the lara shell, type id. This should show that currently you’re logging in as user lara.

4. Use the Ctrl+Alt+F2 key sequence to open a virtual console. At the login prompt, type the user name lara, and when asked for a password press Enter. You’ll get an access denied error message because no password has been set for the new user.

5. Open a root shell and type echo password | passwd --stdin lara. This command sets the password for user lara. Repeat step 4 of this exercise, you should now be able to log in as user lara.

6. From a root shell, type chage lara. You’ll be prompted for a series of password related settings. Enter the settings you want to use to restrict access to the account of user lara.

Working with Default Values for User Management

When managing users, two configuration files are involved that allow you to specify default settings for users. First is /etc/defaults/useradd, which specifies default values for the useradd command. Next is /etc/login.defs, which is used to specify the default user environment.

Setting Default Values Using /etc/default/useradd

As you have seen, a few options come with the useradd command. If an option isn’t specified, useradd will read its configuration file in /etc/default/useradd, where it finds some default values such as what groups the user should become a member of and where to create the user’s home directory. When using an option with useradd, you will always overwrite the default values. Listing 6-2 shows the contents of this file as it is used on a Fedora system.

Listing 6-2. Default Options for Creating Users in the Configuration File /etc/default/useradd

[root@fedora ~]# cat /etc/default/useradd
# useradd defaults file
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes

In this example /etc/default/useradd file, the following options are used:

· GROUP=100: Ensures that new users will get the group with group ID (GID) 100 as their default primary group.

· HOME=/home: Specifies that user home directories must be created in /home.

· INACTIVE=-1: Makes sure that the user account is set to inactive, until the moment that someone sets a password for the user.

· EXPIRE=: Makes sure that the user password expires after a given number of days.

· SHELL=/bin/bash: Specifies what to use as the default shell for new users.

· SKEL=/etc/skel: Specifies the name of the skeleton directory that has some default configuration files for new users. When creating a user who has a home directory with useradd -m, the contents of this skeleton directory are copied to the user’s home directory.

· CREATE_MAIL_SPOOL=yes: Ensures that new users will have a directory in /var/mail where the mail process can store mail messages. If your users don’t need to work with the internal Linux mail facility (for more about this, see the section “Sending Mail from the Command Line” in Chapter 2), you can give this variable the value no.

Creating a Default environment Using /etc/login.defs

The /etc/login.defs file defines some generic settings that determine all kinds of things relating to user login. Some of the settings in /etc/login.defs can be conflicting with settings in /etc/default/useradd. If this is the case, the /etc/login.defs settings take precedence. The login.defsfile is a readable configuration file that contains variables. Each line in this file corresponds to one variable and its value. The variable relates to logging in or to the way in which certain commands are used.. The following list contains some of the more interesting variables that you can use in the login.defs file:

· DEFAULT_HOME: By default, a user will be allowed to log in, even if his or her home directory does not exist. If you don’t want that, change this parameter’s default value of 1 to the value 0.

· ENV_PATH: This variable contains the default search path that’s applied for all users who do not have UID 0.

· ENV_ROOTPATH: This variable works in the same manner as ENV_PATH, but for root.

· FAIL_DELAY: After a login failure, it will take a few seconds before a new login prompt is generated. This variable, set to 3 by default, specifies how many seconds it takes.

· GID_MAX and GID_MIN: This lets you specify the minimum and maximum GID used by the groupadd command (see “Commands for Group Management” later in this chapter).

· LASTLOG_ENAB: If enabled by setting the Boolean value to 1, LASTLOG_ENAB specifies that all successful logins must be logged to the file /var/log/lastlog. This only works if the lastlog file also exists. (If it doesn’t, create it by using touch /var/log/lastlog.)

· PASS_MIN_LEN: This is the minimum number of characters that must be used for new passwords.

· UID_MAX and UID_MIN: These are the minimum and maximum UIDs to be used when adding users with the useradd command.

· USERGROUPS_ENAB: This parameter, if set to yes, ensures that if a user is created, a group with the same name of the user is created as well. This group is set as the primary group of the user.

Managing Passwords

If your user really needs to do anything on your system, he or she needs a password. By default, login for a user you create is denied, and no password is supplied. Basically, your newly created user can’t do anything on your computer because the password is disabled. As root you’ll need to use passwd <username> to set a password for the user so that the user can log in. Once login has been enabled, users can use passwd themselves as well.

If the user uses the command to change his or her password, he or she will be prompted for the old password and then the new one. Only the user root can change passwords for other users. To do this, root can specify the name of the user he or she wants to change the password for as the argument of the passwd command. For example, root can use the command passwd linda to change the password for user linda, which is always useful in case of forgotten user passwords.

The passwd command can be used in three ways. First, you can use it for password maintenance (such as changing a password, as you have just seen). Second, it can also be used to set an expiration date for the password. Third, the passwd command can be used for account maintenance. For example, an administrator can use it to lock a user’s account so that login is temporarily disabled. In the next section, you’ll learn more about password management.

Performing Account Maintenance with passwd

In an environment in which many users use the same computer, it’s crucial that you perform some basic account maintenance. These tasks include locking accounts when they are unneeded for a longer time, unlocking an account, and reporting password status. Also, an administrator can force a user to change his or her password after logging in for the first time. To perform these tasks, the passwd command has the following options:

· -l: Enables an administrator to lock an account. For example, passwd -l jeroen locks the account for user jeroen.

· -u: Unlocks a previously locked account. For instance, the account for user jeroen, which was locked in the previous example, would be unlocked with the command passwd -u jeroen.

· -S: Reports the status of the password for a given account:

nuuk:/home/linda # passwd -S linda
linda PS 12/10/2018 0 99999 7 -1

This status line contains the following information:

· Name of the user

· Date on which the password was set

· Days before a password may be changed

· Days after which the password must be changed

· Days before the password is to expire that the user is warned

· Days after which the password expires that the account is locked

· -e: Forces the user to change his or her password upon next login.

Managing Password Expiration

Although not many people are aware of the password expiration feature, it allows you to manage the maximum number of days that a user can use the same password. As an alternative to using the chage command which has been discussed earlier in this chapter, the passwd command has four options to manage expirations:

· -n min: This option is applied to set the minimum number of days that a user must use his or her password. If this option is not used, the user can change his or her password anytime.

· -x max: With this option, you can set the maximum number of days that the user can use his or her password without changing it.

· -c warn: Use this option to send a warning to the user when his or her password is about to expire. The argument of this option specifies how many days the user is warned before his or her password expires.

· -i inact: Use this option to make an account expire automatically if it hasn’t been used for a given period. The argument of this option specifies the exact duration in days of this period.

Image Caution By default, a password can be used for 99,999 days. So, if you do nothing, a user may use his or her password for 273 years without changing it. If you don’t want that, make sure you use the –x option.

Behind the Commands: Configuration Files

In the previous section, you learned about the commands to manage users from a console environment. All of these commands put user-related information into the user database, which is stored in the configuration files /etc/passwd, /etc/shadow, and /etc/group. The aim of this section is to give you some insight into these configuration files.

/etc/passwd

The first and probably most important of all user-related configuration files is /etc/passwd, which is the primary database for user information: everything except the user password is stored in this file. Listing 6-3 gives you an impression of what the fields in this file look like.

Listing 6-3. Contents of the User Database File /etc/passwd

root@RNA:~# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
dhcp:x:100:101::/nonexistent:/bin/false
syslog:x:101:102::/home/syslog:/bin/false
klog:x:102:103::/home/klog:/bin/false
mysql:x:103:106:MySQL Server,,,:/var/lib/mysql:/bin/false
bind:x:104:109::/var/cache/bind:/bin/false
sander:x:1000:1000:sander,,,:/home/sander:/bin/bash
messagebus:x:105:112::/var/run/dbus:/bin/false
haldaemon:x:106:113:Hardware abstraction layer,,,:/home/haldaemon:/bin/false
gdm:x:107:115:Gnome Display Manager:/var/lib/gdm:/bin/false
sshd:x:108:65534::/var/run/sshd:/usr/sbin/nologin
linda:x:1001:1001::/home/linda:/bin/sh
zeina:x:1002:1002::/home/zeina:/bin/sh

You can see that /etc/passwd uses different fields to store user properties. These fields are separated with a colon. The following list gives the order of fields from left to right; see the section “Understanding Users and Their Properties” earlier in this chapter for more details:

· Username

· Password

· UID

· GID

· GECOS

· Home directory

· Shell

As an administrator, you can manually edit /etc/passwd and the related /etc/shadow. If you intend to do this, however, don’t use any editor. Use vipw instead. This tailored version of the Vi editor is specifically designed for editing these critical files. Any error can have serious consequences, such as no one being able to log in. Therefore, if you make manual changes to any of these files, you should check their integrity. Besides vipw, another way to do this is to use the pwck command, which you can run without any options to see whether there are any problems you need to fix. Listing 6-4 shows you the results of pwck on a healthy user environment. As you can see, it notifies you about nonexisting directories, and if it finds a line that contains a serious error, it proposes to remove that line.

Listing 6-4. To Check the Integrity of the User Database, Use the pwck Command

[root@fedora ~]# 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 ftp: directory /var/ftp does not exist
user avahi-autoipd: directory /var/lib/avahi-autoipd does not exist
user pulse: directory /var/run/pulse does not exist
invalid password file entry
delete line 'linda:x:501:::/home/linda:/bin/bash'? y
no matching password file entry in /etc/passwd
delete line 'linda:!!:14224:0:99999:7:::'? y
pwck: the files have been updated

/etc/shadow

Encrypted user passwords are stored in the /etc/shadow file. The file also stores information about password expiration. Listing 6-5 shows an example of its contents.

Listing 6-5. Example Contents of the /etc/shadow File

root:$1$15CyWuRM$g72U2o58j67LUW1oPtDS7/:13669:0:99999:7:::
daemon:*:13669:0:99999:7:::
bin:*:13669:0:99999:7:::
sys:*:13669:0:99999:7:::
dhcp:!:13669:0:99999:7:::
syslog:!:13669:0:99999:7:::
klog:!:13669:0:99999:7:::
mysql:!:13669:0:99999:7:::
bind:!:13669:0:99999:7:::
sander:$1$Qqn0p2NN$L7W9uL3mweqBa2ggrBhTB0:13669:0:99999:7:::
messagebus:!:13669:0:99999:7:::
haldaemon:!:13669:0:99999:7:::
gdm:!:13669:0:99999:7:::
sshd:!:13669:0:99999:7:::
linda:!:13671:0:99999:7:::
zeina:!:13722:0:99999:7:::

Just as in /etc/passwd, the lines in /etc/shadow are divided into several fields as well. The first two fields matter especially for the typical administrator. The first field stores the name of the user, and the second field stores the encrypted password. Note that in the encrypted password field, the ! and * characters can be used as well. The ! denotes the login is currently disabled, and the * denotes a system account that can be used to start services but that is not allowed for interactive shell login (so basically it has the same effect as the !). Following is a short list of all the fields in /etc/shadow. Use the passwd command to change these fields:

· Login name.

· Encrypted password.

· Days between January 1, 1970, and the date when the password was last changed.

· Minimum: Days before password may be changed. (This is the minimum amount of time that a user must use the same password.)

· Maximum: Days after which password must be changed. (This is the maximum amount of time that a user may use the same password.)

· Warn: Days before password expiration that user is warned.

· Inactive: Days after password expiration that account is disabled. (If this happens, administrator intervention is required to unlock the password.)

· Expire: Days between January 1, 1970, and the date when the account was disabled.

· Reserved field (this field is currently not used).

EXERCISE 6-2: MANAGING USER PROPERTIES

This exercise continues where Exercise 6-1 has stopped and allows you to set some parameters for user lara.

1. Open a root shell, and type passwd -l lara. This will lock access to the account of user lara.

2. Use Ctrl+Alt+F2 to open a virtual console and try logging in as user lara. You’ll get access denied.

3. As root, type grep lara /etc/shadow and notice the exclamation mark at the start of the password field. If the password file in /etc/shadow starts with an exclamation mark, login is denied.

4. Type passwd -u lara to unlock the account of user lara and try logging in again. You should now be able to do so.

Group Membership

In any Linux environment, a user can be a member of two different kinds of groups. First, there’s the primary group, which every user has. (If a user doesn’t have a primary group, he or she won’t be able to log in.) The primary group is the group that is specified in the fourth field of/etc/passwd.

There are two approaches to handling primary groups. On Ubuntu and Red Hat, all users get their own private groups as their primary groups, and this private group has the same name as the user. On SUSE, a group with the name users is created, and all users are added as members to that group.

A user can be a member of more than just the primary group and will automatically inherit the permissions granted to these other groups (more about permissions in Chapter 7). The most important difference between a primary group and other groups is that the primary group will automatically become group owner of any new file that a user creates - you’ll read more about this in chapter 7. If a user has his or her own private group, this won’t be a great challenge for your computer’s security settings (as the user is the only member). If, however, a scheme is used where all users are member of the same group, this means that everyone has access to all files this user creates by default.

Creating Groups

As you’ve already learned, all users require group membership. You’ve read about the differences between the primary group and the other groups, so let’s have a look at how to create these groups. We’ll discuss the commands that you can run from the shell and the related configuration files.

Commands for Group Management

Basically, you manage the groups in your environment with three commands: groupadd, groupdel, and groupmod. So, as you can see, group management follows the same patterns as user management. And, there’s some overlap between the two as well. For example, usermod as well asgroupmod can be used to make a user a member of some group. The basic structure for the groupadd command is simple: groupadd somegroup, where somegroup of course is the name of the group you want to create. Also, the options are largely self-explanatory: it probably doesn’t surprise you that the option -g gid can be used to specify the unique GID number you want to use for this group. Because groups don’t have many properties, there are no other important options.

Behind the Commands: /etc/group

When a group is created with groupadd, the information entered needs to be stored somewhere, and that’s the /etc/group file. As shown in Listing 6-6, this is a rather simple file that has just a few fields for each group definition.

Listing 6-6. Content of /etc/group

plugdev:x:46:sander,haldaemon
staff:x:50:
games:x:60:
users:x:100:
nogroup:x:65534:
dhcp:x:101:
syslog:x:102:
klog:x:103:
scanner:x:104:sander
nvram:x:105:
mysql:x:106:
crontab:x:107:
ssh:x:108:
bind:x:109:
sander:x:1000:
lpadmin:x:110:sander
admin:x:111:sander
messagebus:x:112:
haldaemon:x:113:
powerdev:x:114:haldaemon
gdm:x:115:
linda:x:1001:
zeina:x:1002:

The first field in /etc/group is reserved for the name of the group. The second field stores the password for the group (an ! signifies that no password is allowed for this group). You can see that most groups have an x in the password field, and this refers to the /etc/gshadow file where you can store encrypted group passwords. However, this feature isn’t used often because it is very uncommon to work with group passwords. You’ll notice that many Linux distributions don’t even have an /etc/gshadow file anymore.

The third field of /etc/group provides a unique group ID, and, finally, the last field lists the names of the members of the group. These names are only required for users for whom this is not the primary group; primary group membership itself is managed from the /etc/passwdconfiguration file. However, if you want to make sure that a user is added to an additional group, you have to do it here or use usermod -G.

The Use of Group Passwords

As mentioned, group passwords are used so rarely, you probably won’t ever need them. But what can they be used for anyway? In all cases, a user has a primary group. When the user creates a file, this group is assigned as the group owner for that file automatically. This means that all members of the same group can normally access the file. If a user wants to create files that have a group owner different from their primary group, the user can use the newgrp command. This opens a subshell, in which the user has another primary group that is set on a temporary basis.

For example, newgrp sales would set the primary group of a user to the group sales. Using this command would work without any question if the user is a member of the group sales. However, if the user is not a member of that group, the shell will prompt the user to enter a password. This password is the password that needs to be assigned to that group. To set a group password, you need the passwd -g command. Because this feature is hardly ever used, you’ll find that this feature is not available on all Linux distributions.

To make users a member of other than their primary group, you can use different commands. A very common command, is usermod. You should however notice that this command shows different behavior on the different Linux distributions, so by all means, read the man page or help before using it. On Red Hat, you’ll use usermod -aG groupname username to add a user to additional secondary groups. Make sure you’ll use the -a option as without this option you’ll overwrite all current secondary group assignments.

A more universal way to add users to secondary groups, is by using the vigr or vi /etc/group command. These commands open an editor directly on the /etc/group file, which allows you to add the user name in the last field of the line where the group is defined. If you want to use this approach, make sure to use vigr and not vi /etc/group, because the vigr command makes sure that you won’t have any locking issues that can occur when the file is accessed by multiple users simultaneously. In exercise 6-3 you’ll work with some of these commands.

EXERCISE 6-3: MANAGING GROUPS

1. Open a root shell.

2. Type for i in daphne marcha isabella; do useradd $i; done. This executes a small shell scripting structure to add three users while using only one command.

3. Type groupadd sales and groupadd account to add the groups sales and account.

4. Type id daphne. You’ll see that currently this user only is a member of the primary group.

5. Type grep sales /etc/group. You’ll notice that no users are listed in the fourth field of this file, so currently, the group sales has no members.

6. Type usermod -aG sales daphne. This adds user daphne to the group sales.

7. Type id daphne. You’ll now see that she is a member of the sales group.

8. Type usermod -G account daphne and use id daphne again to verify current group membership. You’ll notice that daphne is indeed a member of the group account, but no longer a member of the group sales.

9. Use usermod -aG sales isabella and usermod -aG sales,account marcha to add the other users to a secondary group as well.

10.Verify that you have succeeded, using id marcha; id daphne; id sales as root. Notice the use of the semicolon, which allows you to rune several commands on one line.

Managing the User’s Shell Environment

To make sure that a user account can do its work properly, the user needs a decent shell environment as well. When creating a user, a shell environment is created as well, and this environment will do in most situations. Sometimes, however, a user has specific needs, and you need to create a specific environment for him or her. Without going into detail about specific shell commands, this section provides an overview of how you create a shell environment. I’ll first explain about the files that can be used as login scripts for the user, and next you’ll learn about files that are used to display messages for users logging in to your system.

Image Note The tasks described next are typically ones that you would perform on a file server that is accessed by users directly. However, if a user never logs in to the computer, there is no need to perform these tasks.

Creating Shell Login Scripts

When a user logs in to a system, the /etc/profile configuration file is used. This generic shell script (which can be considered a login script) defines environment settings for all users upon login. Think of settings like variables, that define the working environment for users. Also, commands can be included that need to be issued when the user first logs in to a computer. The /etc/profile file is a generic file processed by all users logging in to the system. It also has a user-specific version (.profile) that can be created in the home directory of the user. The user-specific .profile of the shell login script is executed last, so if there is a conflict in settings between the two files, the settings that are user specific will always be used. In general, it isn’t a good idea to give a login file to too many individual users; instead, work it all out in/etc/profile. This makes configuring settings for your users as easy as possible.

Image Note If you are working on SUSE Linux, you shouldn’t modify the /etc/profile file. When updating the computer, the update process may overwrite your current /etc/profile. Instead, make your modifications to /etc/profile.local, which is included when logging in.

Now /etc/profile and the user-specific .profile are not the only files that can be processed when starting a shell. If a user starts a subshell from a current environment, such as by executing a command or by using the command /bin/sh again, the administrator may choose to define additional settings for that. The name of this configuration file is /etc/bashrc, and it also has a user-specific version, ~/.bashrc. On some distributions the most important part of the default shell settings is in profile and .profile; other distributions use bashrc and .bashrcto store these settings.

Note: It can be confusing to understand if you need to use /etc/profile or /etc/bashrc to include settings for execution upon login. On many distributions, the /etc/profile command includes the line source /etc/bashrc. This allows administrators to put all relevant commands in the /etc/bashrc file, and have that executed upon start of a subshell, as well as upon login.

After making changes to these configuration files, you can source them to activate the new settings. To do this, you can use the source command or its equivalent, the . (dot) command. The advantage of this technique is that you don’t have to log out and in again to activate the changes. The following two example lines show how to do this:

source ~/.bashrc
. ~/.bashrc

Showing Messages to Users Logging In

It may be useful to display messages to users logging in to your computer. However, this only works if a user logs in to a nongraphical desktop. On a graphical desktop, the user is not able to see messages that are in these files. You can use two files for this: /etc/issue and /etc/motd. The first, /etc/issue, is a text file whose content is displayed to users before they log in. You may, for example, use the file to display a message instructing users how to log in to your system, or include a message if login has been disabled on a temporary basis.

Another way to show messages to users logging in is by using /etc/motd. This file shows messages to users after they complete the login procedure. Typically, this file can be used to display messages related to day-to-day system maintenance.

Applying Quota to Allow a Maximum Amount of Files

As a part of maintaining the user environment, you should know about user quota. This can be used to limit the amount of disk space available to a user. Configuring user quota is a five-step procedure:

1. Install the quota software.

2. Prepare the file system where you want to use quota.

3. Initialize the quota system.

4. Apply quota to users and groups.

5. Start the quota service.

Quotas are always user or group related and apply to a complete volume or partition. That is, if you have one disk in your computer, with one partition on it that holds your complete root file system, and you apply a quota of 100MB for user zeina, this user can create no more than 100MB of files, no matter where on the file system. The Linux quota system does not allow you to limit the maximal amount of data that a directory can contain. If you want to accomplish that, put the directory on a separate partition or volume and limit the size of the volume.

The quota system works with a hard limit, a soft limit, and a grace period:

· The soft limit is a limit that cannot be surpassed on a permanent basis, but the user can create more data than the quota allows on a temporary basis. That means that the soft limit is a limit that you shouldn’t surpass, but if you do, the quota system tolerates it on a temporary basis.

· The grace period relates to the soft limit. It is the length of time that the user can temporarily exceed the soft limit.

· The hard limit is an absolute limit, and after it’s reached (or when the grace period elapses, whichever is sooner), the user will not be permitted to create new files. So users can never create more files than specified in the hard limit.

Working with soft and hard limits is confusing at first glance, but it has some advantages: if a user has more data than the soft limit allows, he or she still can create new files and isn’t stopped in his or her work immediately. The user will, however, get a warning to create some space before the hard limit is reached.

Installing the Quota Software

Most distributions don’t install the quota software by default. It’s easy to find out whether the quota software is installed on your system: if you try to use one of the quota management utilities (such as edquota) when the quota software has yet not been installed, you’ll see a message that it has to be installed first. Use the software management solution for your distribution to install the quota software, which typically is in the quota package in that case. In Chapter 8, you can read more about software installation.

Preparing the File System for Quota

Before you can use the quota software to limit the amount of disk space that a user can use on a given file system, you must add an option to /etc/fstab for all file systems that must support quota.

Image Tip If it’s not possible to restart your server at this moment so that the file system can be mounted with the newly added options, you can use mount -o remount,usrquota,grpquota instead. For example, if you need to apply the quota options to your root file system and can’t reboot now, just use mount -o remount,usrquota,grpquota /. At the same time, change your fstab as well to make sure that the new settings will also be applied when your server reboots.

Here’s the procedure to modify fstab:

1. Open /etc/fstab with an editor.

2. Select the column with options. Add the option usrquota if you want to apply quota to users and grpquota for groups. Repeat this procedure for all file systems where you want to use quota.

3. Remount all partitions in which quota has been applied (or restart your computer).

Initializing Quota

Now that you’ve finished the preliminary steps, you need to initialize the quota system. This is necessary because all file systems have to be searched for files that have already been created, and for a reason that’s probably obvious: existing files count toward each user’s quota, and so a report must be created in which the quota system can see which user owns which files. The report generated by this quota initialization is saved in two files that should be in the root of the mount point where you want to apply the quota: aquota.user is created to register user quotas, andaquota.group is created for group quotas.

To initialize a file system for the use of quotas (which will also create the quota files for you), you need to use the quotacheck command. This command can be used with some options, and I’ll list only the most important ones here:

· -a: This option ensures that all file systems are searched when initializing the quota system.

· -u: This option ensures that user information is searched. This information will be written to the aquota.user file.

· -g: This option ensures that group information is searched as well. This information is written to the aquota.group file.

· -m: Use this option to make sure that no problems will occur on file systems that are currently mounted.

· -v: This option ensures that the command will work in verbose mode to show exactly what it is doing.

So, the best way to initialize the quota system is to use the quotacheck -augmv command, which (after a while) creates the files aquota.user and aquota.group to list all quota information for current users. This can take a few minutes on a large file system, as the quota system has to calculate current file usage on the file system where you want to create the quota. So if you want to apply quota to /home where /home is on the dedicated partition /dev/sda3, which uses Ext3, make sure to do the following:

1. Include the following line in /etc/fstab:

/dev/sda3 /home ext3 usrquota,grpquota 0 0

2. Activate the new setting using the following command:

mount -o remount,rw,usrquota,grpquota /home

3. Run the quotacheck -a command to generate the quota files automatically.

4. Make sure that the quota files are in /home/aquota.user and /home/aquota.group.

Setting Quota for Users and Groups

Now that the quota databases have been created, it’s time for the real work because you’re ready to apply quota to all users and groups on your system. You’ll do this with the edquota command, which uses the vi editor to create a temporary file. This temporary file is where you’ll enter the soft and hard limits you’ve decided upon for your users and groups. If, for example, you want to apply a soft limit of 100,000 blocks and a hard limit of 110,000 blocks for user florence, follow these steps:

1. The edquota command works only with blocks and not bytes, kilobytes, or anything else. So, to set quota properly, you need to know the block size that’s currently used. To find that, use the dumpe2fs | less command. You’ll find the block size in the second screen.

2. Issue the command edquota -u florence. This opens the user’s quota file in the quota editor as you can see in Listing 6-7.

Listing 6-7. Example User Quota File

Disk quotas for user florence (uid 1014):
Filesystem blocks soft hard inodes soft hard
/dev/mapper/system-root 116 0 0 25 0 0
~
~
~
~
~
~
~
~
~
~
~
~
~
"/tmp//EdP.af6tIky" 3L, 220C 1,1 All

3. In the editor screen, represented by Listing 6-7, six numbers specify the quota for all file systems on your computer. The first of these numbers is the number of blocks that are currently being used by the user you’re creating the quota file for. The second and third numbers are important as well: the second number is the soft limit for the number of blocks, and the third number is the hard limit on blocks in kilobytes. The fifth and sixth numbers do the same for inodes, which roughly equal the number of files you can create on your file system. The first and fourth numbers are used to record the number of blocks and inodes that are currently being used for this user.

4. Close the editor and write the changes in the quota files to disk.

In this procedure, you learned that quota can be applied to the number of inodes and blocks. If quotas are used on inodes, they specify the maximum number of files that can be created. Most administrators think it doesn’t make sense to work this way, so they set the values for these to 0. A value of 0 indicates that this item currently has no limitation.

After setting the quota, if the soft limit and hard limit are not set to the same value, you need to use the edquota -t command to set the grace time. This command opens another temporary file in which you can specify the grace time you want to use, either in hours or in days. The grace time is set per file system, so there’s no option to specify different grace time settings for different users.

Once you have set quotas for one user, you may want to apply them to other users. Instead of following the same procedure for all users on your system, you can use the edquota -p command. For example, edquota -p florence alex copies the quotas currently applied for user florence to user alex.

Image Caution To set quotas, the user you are setting quotas for must be known to the quota system. This is not done automatically. To make sure that new users are known to the quota system, you must initialize the quota system again after creating the new users. I recommend setting up acron job (see Chapter 9) to do this automatically.

When all the quotas have been set the way you want, you can use the repquota command to monitor the current quota settings for your users. For example, the repquota -aug command shows current quota settings for all users and groups on all volumes. You can see an example of this in Listing 6-8. Now that you’ve set all the quotas you want to work with, you just have to start the quota service, and you’ll do this with the /etc/init.d/quota start command.

Listing 6-8. Use repquota -aug to Show a List of Current Quota Usage

nuuk:~ # repquota -aug
*** Report for user quotas on device /dev/mapper/system-root
Block grace time: 7days; Inode grace time: 7days
Block limits File limits
User used soft hard grace used soft hard grace
----------------------------------------------------------------------
root -- 2856680 0 0 134133 0 0
uucp -- 8 0 0 2 0 0
wwwrun -- 4 0 0 1 0 0
sander -- 108 0 0 25 0 0
linda -- 140 0 0 29 0 0
sanne -- 120 0 0 25 0 0
stephanie -- 116 0 0 25 0 0
alex -- 120 0 0 25 0 0
caroline -- 116 0 0 25 0 0
lori -- 116 0 0 25 0 0
laura -- 116 0 0 25 0 0
lucy -- 116 0 0 25 0 0
lisa -- 116 0 0 25 0 0
lea -- 116 0 0 25 0 0
leona -- 116 0 0 25 0 0
lilly -- 116 0 0 25 0 0
florence -- 116 110000 100000 25 0 0

Techniques Behind Authentication

When a user authenticates, a lot of settings have to be applied. For instance, the system needs to know where to get the login information from and what restrictions apply to the user. To do this, your system uses a pluggable authentication module, or PAM. PAM modules make authentication modular; by using PAM modules, you can enable functionality for specific situations. Also, your system needs to know where it has to read information about users. For this purpose, it uses the /etc/nsswitch.conf file. In this file, it reads—among other things—what files to consult to get user information. On the following pages, you can read how to configure both of these systems for viable user authentication.

Understanding Pluggable Authentication Modules

Normally, the local user database in the Linux files /etc/passwd and /etc/shadow is checked at login to a Linux workstation. In a network environment, however, the login program must fetch the required information from somewhere else (for example, an LDAP directory service such as OpenLDAP). But how does the login program know where it has to search for authentication information? That’s where PAM modules come in.

PAM modules are what make the login procedure on your workstation flexible. With a PAM, you can redirect any application that has anything to do with authentication to any service that handles authentication. A PAM is used, for example, if you want to authenticate with a private key stored on a USB stick, to enable password requirements, to prevent the root user from establishing a telnet session, and in many other situations. The cool thing about a PAM is that it defines not only how to handle the login procedure, but also authentication for all services that have something to do with authentication. The only requirement is a PAM that supports your authentication method.

The main advantage of a PAM is its modularity. In a PAM infrastructure, anything can be used for authentication, provided there’s a PAM module for it. So, if you want to implement some kind of strong authentication, ask your supplier for a PAM module, and it will work. PAM modules are stored in the directory /lib/security, and the configuration files specifying how these modules must be used (and by which procedures) are in /etc/pam.d. Listing 6-9 is an example of just such a configuration file, in which the login procedure learns that it first has to contact an LDAP server before trying any local login.

Listing 6-9. Sample PAM Configuration File

auth sufficient /lib/security/pam_ldap.so
account sufficient /lib/security/pam_ldap.so
password sufficient /lib/security/pam_ldap.so
session optional /lib/security/pam_ldap.so
auth requisite pam_unix2.so
auth required pam_securetty.so
auth required pam_nologin.so
#auth required pam_homecheck.so
auth required pam_env.so
auth required pam_mail.so
account required pam_unix2.so
password required pam_pwcheck.so nullok
password required pam_unix2.so nullok use_first_pass use_authok
session required pam_unix2.so
session required pam_limits.so

The authentication process features four different instances, and these are reflected in Listing 6-9. Authentication is handled in the first instance; these are the lines that start with the keyword auth. During the authentication phase, the user login name and password are first checked, followed by the validity of the account and other account-related parameters (such as login time restrictions). This happens in the lines that start with account. Then, all settings relating to the password are verified (the lines that start with password). Last, the settings relating to the establishment of a session with resources are defined, and this happens in the lines that start with session.

The procedure that will be followed upon completion of these four instances is defined by calling the different PAM modules. This occurs in the last column of the example configuration file in Listing 6-9. For example, the module pam_securetty can be used to verify that the user root is not logging in to a Linux computer via an insecure terminal. Think of a remote connection where user root tries to log in with telnet, which by default uses unencrypted passwords.

The keywords sufficient, optional, required, and requisite are used to qualify the degree of importance that the conditions in a certain module are met. Except for the first four lines (which refer to the connection a PAM has to make to a server that provides LDAP authentication services and work with the option sufficient), conditions defined in all modules must be met; they are all required. Without going into detail, this means that authentication will fail if one of the conditions implied by the specified module is not met.

By default, many services on Linux work with PAM, and you can see this from a simple ls command in the directory /etc/pam.d, which will show you that there is a PAM file for login, su, sudo, and many other programs.

The true flexibility of PAM is in its modules, which you can find in /lib/security. Each of these modules has a specific function. The next section provides a short description of some of the more interesting modules.

Discovering PAM Modules

The usefulness of a system like PAM is entirely determined by its modules. Some of these modules are still experimental, and others are pretty mature and can be used to configure a Linux system. I’ll discuss some of the most important modules.

pam_deny

The pam_deny module can be used to deny all access. It’s very useful if used as a default policy to deny access to the system. If you ever think there is a security hole in one of the PAM enabled services, use this module to deny all access.

pam_env

The module pam_env is used to create a default environment for users when logging in. In this default environment, several system variables are set to determine what the environment a user is working in looks like. For example, there is a definition of a PATH variable in which some directories are included that must be in the search path of the user. To create these variables, pam_env uses a configuration file in /etc/security/pam_env.conf. In this file, several variables are defined, each with its own value to define essential items like the PATH environment variable.

pam_limits

Some situations require an environment in which limits are set to the system resources that a user can access. Think, for example, of an environment in which a user can use no more than a given number of files at the same time. To configure these limitations, you would modify the/etc/security/limits.conf file. To make sure that the limitations you set in /etc/security/ limits.conf are applied, use the pam_limits module.

In /etc/security/limits.conf, limits can be set for individual users as well as groups. The limits can be applied to different items, some of which are listed here:

· fsize: Maximum file size

· nofile: Maximum number of open files

· cpu: Maximum CPU time in minutes

· nproc: Maximum number of processes

· maxlogins: Maximum number of times this user can log in simultaneously

The following code presents two examples of how these limitations can be applied. In the first line, the user ftp is limited to start a maximum of one process simultaneously. Next, everyone who is a member of the group student is allowed to log in four times simultaneously.

ftp hard nproc 1
@student - maxlogins 4

When applying these limitations, you should remind yourself of the difference between hard and soft limits: a hard limit is absolute, and a user cannot exceed it. A soft limit can be exceeded, but only within the settings that the administrator has applied for these soft limits. If you want to set the hard limit to the same as the soft limit, use a character as shown in the previous code example for the group student.

pam_mail

The useful pam_mail module looks at the user’s mail directory and indicates whether there is any new mail. It is typically applied when a user logs in to the system with the following line in the relevant PAM configuration file:

Login session optional pam_mail.conf

pam_mkhomedir

If a user authenticates to a machine for the first time and doesn’t have a home directory yet, pam_mkhomedir can be applied to create this home directory automatically. This module will also make sure that the files in /etc/skel are copied to the new home directory. This module is especially useful in a network environment in which users authenticate through an authentication server and do not always work on the same machine.

pam_nologin

If an administrator needs to conduct system maintenance like installing new hardware, and the computer must be brought down for a few moments, the pam_nologin module may prove useful. This module makes sure that no users can log in when the file /etc/nologin exists. So, before performing any maintenance, make sure to create this file. The user root will always be allowed to log in to the system, regardless of whether this file exists or not.

pam_permit

pam_permit is by far the most insecure PAM service available. It does only one thing, and that’s to grant access—always—no matter who tries to log in. All security mechanisms will be completely bypassed in this case, and even users who don’t have a valid user account can use the services that are configured to use pam_permit. The only sensible use of pam_permit is to test the PAM awareness of a certain module or to disable account management completely and create a system that is wide open to everyone.

pam_rootok

The pam_rootok module lets user root access services without entering a password. It’s used, for example, by the su utility to make sure the user root can su to any account, without having to enter a password for that user account.

pam_securetty

In the old days when telnet connections were still very common, it was important for the user root never to use a telnet session for login because telnet sends passwords in clear text over the network. For this purpose, the securetty mechanism was created: the file /etc/securetty can be created to provide a list of all TTYs from which root can log in. By default, these only include local TTYs 1 through 6. On modern distributions, this module is still used by default, which means that you can limit the TTYs where root can log in by manipulating this file. Listing 6-10 shows the default contents of this file on a computer running Fedora Linux.

Listing 6-10. The /etc/securetty File Is Used to Limit the Terminals Where Root Can Authenticate

nuuk:~ # cat /etc/securetty
#
# This file contains the device names of tty lines (one per line,
# without leading /dev/) on which root is allowed to login.
#
tty1
tty2
tty3
tty4
tty5
tty6
# for devfs:
vc/1
vc/2
vc/3
vc/4
vc/5
vc/6

pam_tally

The useful pam_tally module can be used to keep track of attempts to access the system. It also allows the administrator to deny access if too many attempts fail. pam_tally works with an application that uses the same name, pam_tally, which can be used to set the maximum number of failed logins that are allowed. All attempts are logged by default in the /var/log/faillog file. If this module is called from a configuration file, be sure to at least use the options deny=n and lock_time. The first determines the maximum number of login attempts a user can make, and the second determines how long an account will be locked after that number of login attempts has been reached. The value given to lock_time is expressed in seconds by default.

pam_time

Based upon the configuration file /etc/security/time.conf, the pam_time module is used to limit the times between which users can log in to the system. You can use this module to limit access for certain users to specific times of the day. Also, access can be further limited to services and specific TTYs that the user logs in from. The configuration file time.conf uses lines with the following form:

services;ttys;users;times

The next line is an example of a configuration line from time.conf that denies access to all users except root (the ! character in front of the times is used to deny access). This might be a perfect solution to prevent users from breaking into a system that they shouldn’t be trying to log in to anyway.

login ; tty* ; !root ; !Al0000-2400

pam_unix

pam_unix is probably the most important of all modules: it is used to redirect authentication requests through the /etc/passwd and /etc/shadow files. The module can be used with several arguments, such as nullok and try_first_pass. The nullok argument allows a user with an empty password to connect to a service, and the try_first_pass argument will always try the password a user has already used (if a password is asked for again). Notice that many PAM configuration files include a line to call the common configuration file common-auth. Thepam_unix file is called from here.

pam_warn

The pam_warn module is particularly useful with log errors: its primary purpose is to enable logging information about proposed authentication or password modification. For example, it can be used in conjunction with the pam_deny module to log information about users trying to connect to your system.

The role of /etc/nsswitch.conf

Whereas PAM is used to determine what exactly is allowed and what is not during the authentication process, /etc/nsswitch.conf is used to tell different Linux services where they should look for specific services. These services include authentication services, but other services as well, such as host-resolving services that tell your computer if it has to use DNS or something else, like the /etc/hosts file. The nsswitch mechanism is used not only while authenticating, but also at other moments. The only requirement is that the service in question has to be programmed to use nsswitch. You don’t have to worry about that though; this is the responsibility of the person who wrote the program.

Listing 6-11 shows the default contents of the nsswitch.conf file on SUSE Linux.

Listing 6-11. nsswitch.conf Lines Related to Authentication

nuuk:~ # cat /etc/nsswitch.conf
#
# /etc/nsswitch.conf
#
# An example Name Service Switch config file. This file should be
# sorted with the most-used services at the beginning.
#
# The entry '[NOTFOUND=return]' means that the search for an
# entry should stop if the search in the previous entry turned
# up nothing. Note that if the search failed due to some other reason
# (like no NIS server responding), then the search continues with the
# next entry.
#
# Legal entries are:
#
# compat Use compatibility setup
# nisplus Use NIS+ (NIS version 3)
# nis Use NIS (NIS version 2), also called YP
# dns Use DNS (Domain Name Service)
# files Use the local files
# [NOTFOUND=return] Stop searching if not found so far
#
# For more information, please read the nsswitch.conf.5 manual page.
#

# passwd: files nis
# shadow: files nis
# group: files nis

passwd: compat
group: compat

hosts: files dns
networks: files dns

services: files
protocols: files
rpc: files
ethers: files
netmasks: files
netgroup: files nis
publickey: files

bootparams: files
automount: files nis
aliases: files

As you can see, for different subsystems, the nsswitch.conf file tells where to look for configuration. The following specifications are available:

· files: Uses the normal default configuration files (/etc/passwd and /etc/shadow), which are stored locally. Red Hat uses this as the default to handle authentication.

· compat: Serves as an alternative way to tell the authentication processes only that they should look in the /etc/passwd and /etc/shadow configuration files. Using this option makes it easier to hook up your system to an LDAP-based authentication service.

· nis, nisplus: Refer to the legacy UNIX NIS authentication services.

· ldap: Uses an LDAP Directory Server for authentication.

· dns: Specifies that host and network-specific information must be looked up in DNS.

EXERCISE 6-4: WORKING WITH PAM

1. Open a root shell. Type cat /etc/securetty and check the contents of this file. You should see the TTY devices tty1 up to tty12 at least. The fact that these are included in the file ensures that user root can log in from all of these virtual terminals.

2. Use the Ctrl+Alt+F3 key sequence to open the virtual console tt3. Enter the username root and the root password. You’ll notice that you can log in as root.

3. Open the file /etc/securetty and remove the line that reads tty4.

4. Use Ctrl+Alt+F4 and try to log in from the virtual console that opens, using user name root and the associated password. This should not work.

5. Still from the virtual console tty4, log in using username lara and password “password”. This should be possible.

6. Use su - to open a root shell. This also is allowed.

7. Open the file /etc/pam.d/su and make sure it includes the following line:

login required pam_secure.tty.

8. Close the configuration file and write changes to disk. Type exit until you see the tty4 login prompt again.

9. Repeat steps 5 and 6 from this exercise and notice that you’re no long able to log in as user root from virtual console tty4.

Configuring Administrator Tasks with sudo

If you want to perform administration tasks, you could just log in as the user root. However, this has some security risks, the most important of which is that you might make a mistake and thus by accident remove everything from your computer. Therefore, on some Linux distributions such as Ubuntu, the root account is disabled by default. It doesn’t even have a password, so you cannot log in as root after a default installation. To perform tasks for which root privileges are required, use the sudo mechanism instead.

Even if the account for user root is not disabled by default, it may still be a good idea to use sudo. This is especially true for environments where specific users or groups of users need root permissions to accomplish a limited set of tasks. Imagine the developer who needs root permissions to compile new programs, the network administrator who just needs to be able to modify network parameters, or the help desk employee who needs to be able to reset a password for a user.

The idea of sudo is that specific administrator tasks can be defined for specific users. If one such user wants to execute one of the sudo commands that he or she has been granted access to, that user has to run it with sudo. For example, where normally the user root would enteruseradd -m caroline to add the user caroline if the user would work with root permissions, a user with sudo privileges would enter sudo useradd -m caroline, thus telling sudo that he or she needs to run a sudo task. Next, the user enters his or her password, and the user is created. In Listing 6-12, you can see what happens when user alex tries to create another user in this way.

Listing 6-12. Adding a User with sudo

alex@nuuk:~> sudo /usr/sbin/useradd -m caroline

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
alex’s password:
alex@nuuk:~>

As you can see, the user first uses the sudo command, followed by the complete path to the command he or she needs to use. That is because the user needs to run a command from the /usr/sbin directory, and this directory is not in the default user search path. Next, the user sees a message that indicates he or she should be careful and following that, the user needs to enter his or her password. This password is cached for the duration of the session, which means that if a short while later the user wants to use sudo again, he or she doesn’t have to enter his or her password again.

To create a sudo configuration, you need to use the editor visudo. This editor is used to open a temporary file which is later written to the file /etc/sudoers. In this file, you can define all sudo tasks that must be available on your computer. You should never open the/etc/sudoers file for editing directly because that involves the risk of completely locking yourself out if you make an error.

Image Tip On Ubuntu, visudo uses the text editor ano by default. If you are a Linux veteran who is used to Vi, you’ll probably won’t like this. Want to use Vi instead of nano? Then use the command export VISUAL=vi. Like what you see? Put it as the last line in /etc/profile or your own .profile, and from now on, every time you use either visudo or edquota, Vi is started instead of nano. In this book, I’m using the Vi alternative because it automatically saves all files in the locations where they have to be saved.

In Listing 6-13, you can see what the default configuration in /etc/sudoers looks like.

Listing 6-13. Default Configuration in /etc/sudoers

root@RNA:/etc# cat sudoers
# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
# Host alias specification
# User alias specification

# Cmnd alias specification

# Defaults

Defaults !lecture,tty_tickets,!fqdn

# User privilege specification
root ALL=(ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

It’s really just two lines of configuration. The first line is root ALL=(ALL) ALL, which specifies that user root has the right to run all commands from all machines. Next, you can see that the same is true for all users who belong to the user group admin. If, for example, you would like to specify that user linda is allowed to run the command /sbin/shutdown, no matter what host she is connecting from, add the following line:

Linda ALL=/sbin/shutdown

This line consists of three parts. In the first part, the username is entered. Instead of the name of a specific user, you can refer to groups as well, but if you do that, make sure to put a % sign before the group name. The second part—ALL in this example—refers to the name of the host where the user is logged on. Here, that host name has no limitations, but you can specify the name of a specific machine to minimize the risk of abuse by outsiders. Next, the command that this user is allowed to use (/sbin/shutdown, no options) is specified. This means that the user is allowed to run all options that can be used with this command. If you want to allow the user just one option, you need to include that option in the command line. If that’s the case, all options that do not match the pattern you have specified in sudoers are specifically denied.

Now that the sudo configuration is in place, the specified user can run his or her commands. To do this, the complete command should be referred to because the directories that typically house the root commands (/sbin, /usr/sbin) are not in the search path for normal users. So, user linda should use the following command to shut down the machine:

sudo /sbin/shutdown -h now

On many Linux servers, privileges are granted to a group of administrators to execute administration tasks using the sudo command. The most convenient way to configure this, is by making all administrator users a member of the group wheel, using usermod -aG wheel <username>. After making your administrator users a member of the group wheel, type visudo adn make sure that the following line is included:

%wheel ALL=(ALL) ALL

If this line is included, all users that are member of the group wheel are allowed to run administrator tasks. Before actually executing the task, they will be prompted for their password. If you don’t want a valid sudo user to be prompted for his password, make sure the following line is included:

%wheel ALL=(ALL) NOPASSWD: ALL

It may also be useful to define sets of specific commands that can be executed by users. For instance, a help desk agent many need to reset user properties and passwords, but may not need permissions to run all commands as user root. This can be configured by using a Cmnd_Alias that defines all commands that the users should be granted access to. This can start with the following line:

Cmnd_Alias HELPDESK = /usr/bin/passwd, /usr/sbin/usermod

After defining the command alias, the appropriate permissions must be granted to a user or group of users. The most convenient way of doing so, would be to allow all commands in the alias to the members of a specific group. The following would allow all members of the Linux group helpdesk to run all commands that are defined in the command alias:

%helpdesk ALL=HELPDESK

EXERCISE 6-5: CONFIGURING SUDO

1. Open a root shell.

2. Type visudo to open the sudo editor.

3. Include the following line:

Cmnd_Alias HELPDESK = /usr/bin/passwd, /usr/sbin/usermod

4. Further on in the file, include the following line:

%helpdesk ALL=HELPDESK

5. Write the changes to disk, using :wq!

6. As root, type groupadd helpdesk.

7. User usermod -aG helpesk lara.

8. Use su - lara to open a shell in which you are working as user lara.

9. Type sudo passwd marcha and verify that you can change the password of user marcha.

Summary

In this chapter, you have learned how to manage the user environment. First, you have read about management of users, passwords, and groups. You’ve also learned how to manage the default user environment in the shell files /etc/profile and ~/.profile. Next, you’ve learned how to use the quota system to limit the amount of disk space available to a user. After that, you’ve read how PAM and nsswitch.conf are used to determine where your Linux computer gets user-related information from. At the end of this chapter, you saw how to use sudo to allow nonroot users to perform administration tasks with root permissions. The following commands were covered in this chapter:

· useradd: Adds new users

· usermod: Modifies user properties

· userdel: Deletes users

· passwd: Sets or changes user passwords

· groupadd: Adds new groups

· groupdel: Deletes groups

· groupmod: Modifies group properties

· quotacheck: Enables quotas on all file systems that have the quota options

· addquota: Opens editor to change user quota settings

· repquota: Generates a report of current quota usage

· sudo: Allows end users to execute tasks with root permissions

In the next chapter, you’ll learn how to create a secure environment, working with Linux permissions.