Sunday 27 January 2013

User Management



A comprehensive guide for basic user management of a linux box:

Create Users
Creating a user is rather simple. While logged in as root, type:
useradd username
Where “username” is the name of the user you want to add. There are a couple options to this command as well.
-s allows you to specify what shell you want this user to have. For instance, the default is the “bash” shell, but if you wanted a user to have the ZSH shell you’d do the following:
useradd username -s /bin/zsh
-d will specify a home directory. Usually in most modern linux systems, this gets specified automatically with useradd as /home/<username>. If you wish to specify someplace different simply do this:
useradd -d /new/path/of/home username
-g will specify what group you want this user to have as its default group. This is option as the system will auto-assign a group to the user.
-m – this tells the system that to create the user´s home directory if it does not exist. The files and directories contained in the skeleton directory (which can be defined with the -k option) will be copied to the home directory. By default the “skeleton” directory is /etc/skel. Any file in this directory will be copied to newly created home directories.
-k This allows you to assign a skel directory other than the default.
For the rest of the useradd options please see
man useradd

       By default, no home directories are created.

passwd
Once your user is created you’ll want to set a password for that user. While logged in as root or the user that will be changed, type:
passwd username
Where “username” is the name of the user whose password you want to change. If “passwd” is typed, the password will be changed for the user, you are logged in as. This command also works to change passwords for already existing users. If you wish to change the password for yourself, just type “passwd” and do not specify a user.

/etc/passwd
lets say this is a line out of my /etc/passwd file:
tuxtraining:x:1000:100:tuxtraining:/home/tuxtraining:/bin/bash
Each field is seperated by a “:”, this is what each field represents.
Username: This is the name for a user when a user logs in. It should be between 1 and 32 characters in length.
Password: An x character indicates that encrypted password is stored in /etc/shadow file. (See Below)
User ID (UID): Each user must be assigned a user ID (UID). UID 0 (zero) is reserved for root and UIDs 1-99 are reserved for other predefined accounts. Further UID 100-999 are reserved by system for administrative and system accounts/groups.
Group ID (GID): The primary group ID (stored in /etc/group file). It tells the system which group this user belongs to.
User ID Info: The comment field. It allow you to add extra information about the users such as user’s full name, phone number etc. This field use by finger command.
Home directory: The absolute path to the directory the user will be in when they log in. If this directory does not exists then users directory becomes /
Command/shell: The absolute path of the default shell (usually /bin/bash).

/etc/shadow
The /etc/passwd file can be readable by other uses on the system. Even though an encrypted password can be used in the /etc/passwd file, it is safer practice to place an x in the password field, telling /etc/password to look in the /etc/shadow file for the encrypted password. In the /etc/shadow file there will be a line for every user and they’re encrypted password. Only a user with root privileges can view this file.
tuxtraining:$srtiJOIUHJRGrst5gubrthj98456yW1iog475srt5strh8R.:14536:0:99999:7:::
Again, each field is separated by colons “:”
User name : It is your login name
Password: It your encrypted password. The password should be minimum 6-8 characters long including special characters/digits
Last password change (lastchanged): Days since Jan 1, 1970 that password was last changed
Minimum: The minimum number of days required between password changes i.e. the number of days left before the user is allowed to change his/her password
Maximum: The maximum number of days the password is valid (after that user is forced to change his/her password)
Warn : The number of days before password is to expire that user is warned that his/her password must be changed
Inactive : The number of days after password expires that account is disabled
Expire : days since Jan 1, 1970 that account is disabled i.e. an absolute date specifying when the login may no longer be used
The last 6 fields provides password aging and account lockout features (you need to use chage command to setup password aging). According to man page of shadow – the password field must be filled. The encrypted password consists of 13 to 24 characters from the 64 character alphabet a through z, A through Z, 0 through 9, . and /. Optionally it can start with a “$” character. This means the encrypted password was generated using another (not DES) algorithm. For example if it starts with “$1$” it means the MD5-based algorithm was used.

Modify Users
The usermod command can change just about anything that you can create with useradd. You can change the shell (-s) the UID (-u), the login name (-l , though this will not change permissions set to your old login name), the initial group (-g), supplemenary groups (-G)
The syntax is generall the same too:
usermod <options> <username>
Comman usages are to lock a user account (-L) This puts a ‘!’ in front of the encrypted password, effectively disabling the password. Another is to unlock it (-U).
See: man usermod

Delete users
While logged in as root, type:
userdel -r username
Where “username” is the name of the user you want to remove. This will remove the user’s home directory. You can delete the user without the “-r” option and delete the user’s home directory manually. If the group the user was in, is no longer needed, you may delete it by editing the “/etc/group” file.

Create a Group
 groupadd [-g gid [-o]] [-r] [-f] group
The groupadd command creates a new group account using the values specified on the command line and the default values from the system. The new group will be entered into the system files as needed. None of these options (below) are necessary. You can add a group simply by:
groupadd group
(with “group” being the name of the group)
That being said options which apply to the groupadd command are
-g gid The numerical value of the group’s ID. This value must be unique, unless the -o option is used. The value must be non-negative. The default is to use the smallest ID value greater than 500 and greater than every other group. Values between 0 and 499 are typically reserved for system accounts.
-r This flag instructs groupadd to add a system account. The first available gid lower than 499 will be automatically selected unless the -g option is also given on the command line. This is an option added by Red Hat.
-f This is the force flag. This will cause groupadd to exit with an error when the group about to be added already exists on the system. If that is the case, the group won’t be altered (or added again). This option also modifies the way -g option works. When you request a gid that it is not unique and you don’t specify the -o option too, the group creation will fall back to the standard behavior (adding a group as if neither -g or -o options were specified). This is an option also added by Red Hat.

Modify a Group
groupmod [-g gid [-o]] [-n group_name ] group
The groupmod command modifies the system account files to reflect the changes that are specified on the command line. The options which apply to the groupmod command are
-g gid The numerical value of the group’s ID. This value must be unique, unless the -o option is used. The value must be non-negative. Values between 0 and 99 are typically reserved for system groups. Any files which the old group ID is the file group ID must have the file group ID changed manually.
-n groupname The name of the group will be changed from group to groupname.

Delete a Group
groupdel group
The groupdel command modifies the system account files, deleting all entries that refer to group. The named group must exist.
You must manually check all filesystems to insure that no files remain with the named group as the file group ID. You can do this easily with the find command.
find /var/tmp -gid 1000

/etc/group
/etc/group is a file that defines the groups to which users belong. In Linux multiple users can be categorized into groups. Linux file system permissions are organized into three classes, user, group, and others. The use of groups allows additional abilities to be delegated in an organized fashion, such as access to disks, printers, and other peripherals.
It stores group information or defines the user groups i.e. it defines the groups to which users belong. There is one entry per line, and each line has the format (all fields are separated by a colon (:)
video:x:100:tuxtraining,bob,mary
Like previous files talked about in Part 1, the fields are separated by colons. This is what each field represents:
group_name: It is the name of group. If you run ls -l command, you will see this name printed in the group field.
Password: Generally password is not used, hence it is empty/blank. It can store encrypted password. This is useful to implement privileged groups.
Group ID (GID): Each user must be assigned a group ID. You can see this number in your /etc/passwd file.
Group List: It is a list of user names of users who are members of the group. The user names, must be separated by commas.
Users on Linux systems are assigned to one or more groups for following reasons:
To share files or other resource with a small number of users
Ease of user management
Ease of user monitoring
Group membership gives you or your user special access to files and directories or devices which are permitted to that group

/etc/gshadow
Like /etc/shadow, /etc/gshadow contains secure group account information only readable by the root account such as group passwords.

finger
The finger command reads the /etc/password file and displays information of a user. It is executed like below
finger username
It will tell you a user’s name (if given in comments), home directory, default shell, and if they’re on the system and if so, for how long.

chfn
The chfn command changes finger information and extends what is provide in /etc/passwd. You use it like follows:
chfn -option username
The “-options” for chfn are as follows:
-f Assigns a full name to the user
-o Allows the assignment of a location of a office
-p Assigns an office phone number
-h Assigns a home phone number

How PAM Works

PAM (Pluggable Authentication Modules) is one of those dark corners of Linux where most users don’t venture – in fact, I’d be willing to bet that the majority of Linux users don’t even know what it is. And yet, PAM is at the heart of every single thing in Linux to do with authentication.
Take our guided tour of PAM, join our science lab and perform our experiments (no bunsen burner necessary!) and see how PAM gives you fine-grain control over your security policy.

Getting to know PAM

PAM is a framework that assists applications in performing what I’ll call “authentication-related activities”. The core pieces of PAM are a library (libpam) and a collection of PAM modules, which are dynamically linked libraries (.so) files in the folder /lib/security.
Each module performs one specific task, and a “PAM-aware” application typically uses a stack of several modules to get the job done. Figure 1 below shows the overall architecture.
PAM recognizes four kinds of authentication-related activity, named as follows:
  • auth is the most obvious activity – the actual business of proving who you are by supplying valid credentials. The traditional way of doing this is with a user-name and password, but other methods are possible such as the possession of a physical token or even biometric methods such as fingerprints or retinal scans.
  • account is the business of deciding if, (now we know who you are,) we’re going to let you log in. For example, a PAM module that implemented time-of-day login restrictions would fall into the account category.
  • session allocates the resources that a user might need during a login session, for example, mounting the user’s home directory, setting resource usage limits, printing a message of the day, etc.
  • password updates a user’s credentials (usually their password).
For brevity I’ll refer to these four activities as “PAM activities”.

Which programs use PAM?

Well, any program that needs to authenticate users, control logins, allocate resources to users, or update login credentials can make its life easier by using PAM. Obvious candidates are programs like:
  • login the program that lets you log in on character terminals.
  • gdm lets you log in to a graphical desktop.
  • su lets you start a shell with a new identity.
  • passwd lets you choose a new password.
The benefit of PAM is that it separates the details of how “authentication-related activities” are to be performed from the applications that need to carry out these activities. This makes it relatively easy to change your security policy, or to add new authentication mechanisms, simply by reconfiguring PAM. In the era before PAM, changes like that would have required source-code changes to the applications themselves.

Is a program PAM-aware?

How can we tell if a particular program uses PAM? Well, one way is to look at the config files in /etc/pam.d. In theory, that should tell us which programs are using PAM. A more scientific way is to see if the program is linked against the PAM library. You can do this with a command such as:
$ ldd /bin/login | grep libpam

        libpam.so.0 => /lib/libpam.so.0 (0xb7f47000)

        libpam_misc.so.0 => /lib/libpam_misc.so.0 (0xb7f43000)
If you see similar output, the program uses PAM. If there is no output, it doesn’t.
The stack of modules that each PAM-aware application uses to perform each of our four authentication-related activities is specified in a PAM configuration file in the folder /etc/pam.d. The file is named after the application, so for example /etc/pam.d/sshd is the configuration file for the program sshd.
Figure 2, above, shows one line from such a file; this particular line adds the module pam_unix.so to the auth stack. An application can assemble all four stacks (one for each PAM activity) if it needs to, but many applications only need one or two of them.
Now, the basic idea goes like this: when a PAM-aware application wants to perform a PAM activity, it asks the PAM library to do the job. The PAM library then calls each of the modules in that activity’s stack, in turn. Each of the modules “does its thing”, and returns a pass/fail indication to the library.
The PAM library combines these pass/fail results into a pass/fail result for the stack as a whole. This result is then returned to the application. The way in which the pass/fail results of the individual modules are combined is determined by the control flag associated with the module. This flag is the second field of the entries in the pam config file. The possible settings are:
  • requisite: If this module fails, PAM immediately returns a failure result to the application; no further modules in the stack are called.
  • required: If this module fails, PAM returns a failure result to the application but it will continue to call the next module in the stack. (If you find you have trouble remembering the distinction between requisite and required, then join the club! So do we…)
  • sufficient: If this module succeeds, PAM returns a ‘pass’ result to the application and no further modules in the stack are called. (This assumes, of course, that a required module hasn’t failed higher up the stack.
  • optional: The pass/fail result of this module is ignored, which generally means that the module is being called to perform some operation, rather than participating in the pass/fail decision for the stack. For example, the pam_keyinit module is used as an ‘optional’ module by sshd to create a new ’session keyring’ for the new login.
(Recent versions of PAM support a more fine-grained result from a module than just pass/fail, and a more complex configuration syntax to define how these results are combined to provide an overall result for the stack. See the manual page for pam.conf – if you have one – for the details. However, the basic pass/fail behaviour is enough to be going on with!)
You will also see the include keyword used as a control flag. This is a little different from the others. It tells PAM to include some other pre-defined module stack (in programming terms you’d think of it as calling a subroutine). This is used to ‘factor out’ common PAM behaviours (ie common module stacks) into a separate file.
For example, in RHEL5 you’ll find that many PAM config files include the stack defined in the file system-auth. Or, in Ubuntu, you’ll find four files: common-auth, common-account, common-session and common-passwd that serve a similar purpose. Red Hat also uses a sort of ‘meta-module’ called pam_stack, that runs a stack of modules specified in a separate file, and serves much the same purpose.
Now that you’ve got some idea how PAM hangs together, you might like to take a look at the big table at the end of this tutorial, which lists some commonly-used PAM modules. Note that not all of these modules may be included in your particular distribution. On the other hand, you’ll come across modules that aren’t in this table.
Linux being an open system and all that, folks have written PAM modules to do all kinds of things. Take a look at http://www.kernel.org/pub/linux/libs/pam/modules.html for some links.
We’re about to go over some experiments in changing the PAM configuration. None of them is especially exciting by itself, but my hope is that they will give you enough confidence and understanding of how PAM works to start making experiments of your own.

Allow any user to su to root without a password.

What you need to do: Edit the file /etc/pam.d/su and comment out any lines relating to the auth stack, replacing them with the single line:
auth    sufficient    pam_permit.so
How to test it: Log in as a normal user and verify that you can now use su to become root without supplying a password. This may seems like a very insecure arrangement, but it’s less dangerous than having folks just log in as root in the first place. You can log in as a normal user then run a command like
$ su -c "date 09201155"
to adjust the system clock, for instance (an activity that requires you to be root).

Prevent all users from using su

What you need to do: Edit the file /etc/pam.d/su so that the only line relating to the auth stack reads:
auth     requisite    pam_deny.so
How to test it: Log in as a normal user and verify that any attempt to become root now fails instantly. You’re not even asked for a password. Of course you could also disable su by turning off execute permission on the program itself. Although disabling su might feel like you’re making things more secure, you’re actually forcing a system administrator to log in directly as root, rather than just transitioning briefly to root when he needs root privilege.

Allow only members of the wheel group to use su

What you need to do: First you’ll need to have at least one user account that is a member of the wheel group. For example, to add user chris to the wheel group, enter this command as root:
# usermod -G wheel chris
Now you should edit the file /etc/pam.d/su so that the auth stack looks like this:
auth    sufficient    pam_rootok.so

auth    required      pam_wheel use_uid

auth           include       system-auth
How to test it: Log in as chris (or whichever user you added to the wheel group) and try to use su. You’ll be asked for the root password and then you should get a root shell. Now try to use su whilst logged in as a user who is not a member of the wheel group. You’ll still get asked for the root password, but your attempt to become root will fail. You might like to try changing the control flag for the pam_wheel module to requisite – that is, change the line in /etc/pam.d/su to:
auth    requisite      pam_wheel use_uid
What difference in behaviour would you expect to see? Test it to see if you’re right. Do you begin to see how the configuration of PAM determines your security policy?

Disable direct root login

The idea here is to prevent users from logging in as root, so that they must log in as a normal user then use su to achieve root status. (Before doing this, ensure that you have at least one account that can use su to become root, or you will lock yourself out from the machine.) We need to handle two cases – logging in on virtual terminals, and logging in on the graphical desktop.
What you need to do: To disable root logins on virtual terminals, edit the file /etc/pam/d/login and add the entry
auth    required    pam_securetty.so
at the top of the auth stack. (It may already be there.) As we saw, this module will prevent root login on terminal devices that aren’t listed in /etc/securetty. So now we can empty this file with these commands:
# cp /etc/securetty /etc/securetty.saved



# echo "" > /etc/securetty
(Note that having an empty /etc/securetty file is quite different from not having one at all. The former disables root logins on all terminals, the latter enables root logins on all terminals.) Next, to prevent root logins on the desktop, add the same line to the top of the auth stack in the file /etc/pam.d/gdm.
How to test it: Try logging in as root (supplying the correct password) both on a virtual terminal and on the graphical desktop. Both should fail. Verify that you can still log in as a non-root user. Notice that if you perform Experiment 3 in addition, you have substantially strengthened your system because to become root you must first log in as a member of the wheel group, then use su to become root. Knowledge of the root password, by itself, is not sufficient to gain root access.

Enforce strong passwords

In this experiment we’ll use the pam_passwdqc module on the password stack to ensure that users choose strong passwords. (Note that this will only make any difference when users set or change their passwords; it won’t winkle out weak passwords that are already set.)
What you need to do: Red Hat already uses the pam_cracklib module to check password strength in the common system-auth file. We simply need to replace the pam_cracklib line with a line that looks something like this:
password    requisite    pam_passwdqc.so  min=12,10,10,8,6 retry=3



Figure 3 above attempts to illustrate the parameters to pam_passwdqc. The test of a password’s strength is based on its length, 
but you can set different minimum lengths depending on the number of character classes in your password. 
There are four character classes: lower case, upper case, digits, and other characters. 
Upper case letters used as the first character and digits used as the last character of a password don’t count.

How to test it: Try changing your password to various strings; in each case count the number of characters and the number of character classes in the string and predict if it should be an acceptable password. There are a few examples in the table below.
Password
Length
Character Classes
OK?
monpiastoria
12
1
Yes
LinuxFormat
11
2
Yes
beld*Grob
9
3
Yes
4Me+You
7
4
Yes
splodgerat
10
1
No
Four+five
9
2
No
gosH!!2
7
3
No
x4Z!
4
4
No

Prevent non-root users from shutting down the system

Many systems allow ordinary (non-root) users to shut down or reboot the system using commands like halt, shutdown and reboot. On a production machine this may not be a good idea. In this experiment, we’ll change the PAM configuration of these commands so that only root can halt the machine.
What you need to do: Taking the PAM configuration of the halt command as an example, edit the file /etc/pam.d/halt. On my Red Hat system the auth stack for halt looks like this:
auth sufficient pam_rootok.so auth required pam_console.so
Change the stack to look like this:
auth sufficient pam_rootok.so auth required pam_deny.so
How to test it: Log on as a non-root user and try to halt the system with the command halt. You should no longer be allowed to do this. For a more complete solution you would need to make similar changes to the config files for shutdown and reboot.

Commonly used PAM modules

Module
Activities
Description
pam_unix
auth, session, password
Performs traditional Unix-style authentication against hashed passwords stored in /etc/shadow. You’ll find it included in the pam config files of many applications, either directly or via an include directive.
pam_limits
session
Sets a limit on the system resources than can be used during a user session. By default the limits are taken from the file /etc/security/limits.conf; here you can set hard and soft limits for things such as the maximum number of process, the maximum file size, the maximum CPU time, and so on.
pam_rootok
auth
Succeeds if you’re root and fails if you’re not. It’s as simple as that. It is usually used in combination with some other authentication module to establish a policy of “if you’re root you can go ahead and do it; otherwise you need to authenticate.” The stack for this policy might look like this:
auth    sufficient    pam_rootok.so

auth    required      pam_unix.so
pam_cracklib
password
Performs password strength checking, testing the password against a system dictionary and a set of rules for identifying poor choices. It’s usually used on a password stack to verify password strength before handing the password on to the next module in the stack (typically pam_unix) to actually update the password.
pam_passwdqc
password
An alternative module for password strength checking; it also provides support for pass phrases and can provide randomly generated ones. Like pam_cracklib it would typically be used on a password stack to verify password strength before updating it. For a detailed example, see Experiment 5.
pam_permit
auth, account, session, password
This module just says “yes” to everything. It always returns success.
pam_deny
auth, account, session, password
This module just says “no” to everything. It always returns failure. Typically it would only be used right at the bottom of a PAM stack to guarantee failure.
pam_warn
auth, account, session, password
Simply logs a message (including the service name, the terminal, the user name and the remote host) to the message logging service syslogd. It might be used, for example, near the bottom of a PAM stack to log a failed authentication attempt, just prior to denying it with pam_deny.
pam_motd
session
Displays a message of the day file (by default, the file /etc/motd), typically after a successful login.
pam_securetty
aurg
No, this is not a misspelling of “security”. The pam_securetty module restricts root logins to “secure terminals”; that is, to terminals that are listed in the file /etc/securetty. (Remember, tty is Linux-speak for “terminal device”). The module has no effect for non-root logins. This kind of access control made more sense back in the days when Unix ran on multi-user minicomputers with twenty terminals plugged into RS232 ports; the securetty file could be used to restrict root logins to the terminal that was locked in the system administrator’s office. However it can still be useful to disable direct root logins completely … An idea we return to in the text.
pam_wheel
auth, account
Used by programs like su, this module allows root access only if the requesting user is a member of the group called wheel. (Historical note: The use of “wheel” to refer to a privileged group goes back a very long way. It was certainly in early versions of Unix, and according to The Jargon File (http://www.catb.org/jargon/index.html) it comes from the Twenex operating system in the 1960s. But I still have no idea why it is called “wheel”.)
pam_winbind
auth
Authenticates users against a Windows domain by talking to the winbind daemon (which in turn talks to the windows domain controller). This is an important component if you’re integrating Linux systems into an existing Windows infrastructure, and you want to maintain a common account database across the two.
pam_nologin
auth, account
Prevents users (other than root) from logging in to the system when the file /etc/nologin exists. In some distros, this file is created by the shutdown program to prevent users logging in when the system is about to be stopped.

No comments:

Post a Comment