From Fedora Project Wiki
Warning.png
This page is a draft only
It is still under construction and content may change. Do not rely on the information on this page.

Administration Guide

Table Of Contents

Single Page View

Stop (medium size).png
Section is ready for editing

User Accounts

Introduction

Creation and management of users and user groups is a fundamental practice of system administration on multi-user systems such as Linux. Each user is given an account in the system. This provides a method to distinguish different accounts in the system with associated set of privileges. Each account is further assigned a separate and secure storage area for files and preferences. With this model, each user can specify custom working environment and account specific activities.

Fedora includes two types of accounts: system and non-system accounts. System accounts include the root user and others such as the apache user. System accounts are created during the installation process and used by various system daemons and utilities to perform system-wide tasks. Fedora reserves UIDs 0-499 for system accounts. This is why they are sometimes referred to as low ID accounts.

Note.png
UID is the abbreviation of the term User Identifier
It represents unique numerical equivalent of the
username, which computer uses as a reference to username. Similarly, GID is numerical value that represents Group Identifier. UID 0 (zero) is always reserved for root user.

Non-system accounts start from uid 500. These accounts are used by non-system users for performing their regular tasks. Usually, the first non-system user account is created during the first boot following the system installation. Further user and group accounts are created using standard procedures, explained later in this guide.

Process of Account Creation

This section explains what happens when a new user is added to a Fedora system.

When the system administrator executes

/usr/sbin/useradd dan

from the command line, the following steps occur:

1 . A new line is appended to the /etc/passwd file and it looks similar to:

dan:x:502:502::/home/dan:/bin/bash

It consists of seven colon delimited fields associated with the following meaning:

  • dan - this is the username
  • x - this is the password field; x signifies an empty field and that an encrypted (shadow) password will be placed in /etc/shadow file
  • first 502 - this is the uid (username identifier)
  • second 502 - this is the gid (group identifier) of the user's primary group
  • blank field - this is the "comment" field; the user's full name usually goes here
  • /home/dan - this is the location of the user's home directory in the file system
  • /bin/bash - this is the user's default shell
Idea.png
Entries above show Fedora defaults for new user accounts
Shadow passwords are used by default, UID and GID are the next available numbers, the comment field is empty, all user directories are created as subdirectories of /home and the default shell is bash (Bourne Again Shell). These defaults may be altered by specifying options to the useradd command (more about this on the next page).
Note.png
A GID of the same numerical value as UID represents the Fedora concept of User Private Groups (UPG)
A User Private Group is created every time a new account is added to the system. It has the same name as the new user and the user is the only member of that group. The main advantage of this concept is easier management of user groups on UNIX-like systems. Traditionally, newly created files can not be modified by other users, including members of the file creator's primary group. This is controlled through the umask setting, which is configured in the /etc/bashrc file. Since UPG has only one member and each user has their own private group, this group protection becomes redundant.

2 . A new line is appended to the /etc/shadow file and it looks similar to:

dan:!!:13490:0:99999:7:::

It consists of eight colon delimited fields associated with the following meaning:

  • dan - this is the username
  • !! - two exclamation marks indicate that the password has not been set yet and the account is locked
  • 13490 - represents the number of days (since January 1, 1970) since the password was last changed
  • 0 - represents the number of days before the password may be changed (0 indicates it may be changed at any time)
  • 99999 - represents the number of days after which the password must be changed (99999 indicates user can keep his or her password unchanged for 274 years
  • 7 - represents the number of days remaining before the users password expires (7 means a full week)
  • first blank field - represents the number of days after the password expires that the account will be disabled
  • second blank field - represents the number of days since January 1, 1970 that an account has been disabled
  • third blank field - reserved field for possible future use
Idea.png
The useradd command does not create a password.
At the time of command execution, the password field is initialized and populated with x and !! in the /etc/passwd and /etc/shadow files, respectively. A password is created by using the /usr/bin/passwd command, which replaces !! field with encrypted representation of the user's password. This is security related and prevents the user's password from being displayed as plain text at any time.

3 . A new line is appended to the /etc/group file. It looks similar to:

dan:x:502:

The new line consists of three colon delimited fields associated with the following meaning:

  • dan - this is the group name
  • x - this is the group password field; x indicates that the system is using shadow passwords
  • 502 - this is the gid and it matches the value of uid of the user with the same name

4 . A new line is appended to the /etc/gshadow file. It looks similar to:

dan:!::

The colon delimited fields in this line indicate:

  • dan - this is group name
  • ! - this is group password field in which ! indicates that the group account is locked

5 . The home directory for user dan is created as /home/dan. It has ownership of user dan and group dan but only user dan has read, write and execute permissions on directory. All the other permissions are denied.

6 . Files from the /etc/skel directory are copied to the user's home directory (for example the .bashrc and .bash_profile files which control user's default shell environment).

7 . The system administrator can now run the /usr/bin/passwd dan command to set the user's password, this unlocks the user's account giving the user the ability to login and use the system.

Account Management - Command Line Interface

This section explains how to add new accounts and change account parameters using command line utilities.

Adding Accounts

To add a new user account from the command line run:

su -c "/usr/sbin/useradd luke"

Enter the root password when prompted.

The above command creates a new user account with the username luke, whose primary group is luke. The directory /home/luke is created as the user's home directory and the user's shell environment is set to /bin/bash. (These are Fedora defaults for user accounts.)

Upon creation, the user account is locked. To unlock the account, run:

su -c "passwd luke"

To set user's password, enter the root password at the first password prompt. You are then be presented with the following:

Changing password for user luke.
New UNIX password:

Type in what you want the user's password to be (remember passwords are case sensitive) and press [Enter] . Prompt changes to:

Retype new UNIX password:

Type the same password again and press [Enter] . Prompt returns:

passwd: all authentication tokens updated successfully.

User luke is now able to logon and use the system.

Important.png
Choose passwords wisely!
Passwords are an essential element of system security. Avoid using dictionary words and use a combination of lower and upper case letters, numbers and special characters.

User account defaults are controlled through the /etc/login.defs configuration file. Administrators can manually change values in this file and create a different set of account defaults. Settings from /etc/login.defs file can be overridden by supplying options to the useradd command. For example:

su -c "/usr/sbin/useradd -c 'Luke McAlister' -g primary -G additional,another -d /home/second -s /bin/tcsh luke2"

creates a new user account for the user luke2 with the following characteristics:

  • user's full name is Luke McAlister
  • user's primary group is primary
  • user luke2 is also a member of additional and another groups
  • /home/second is created as the home directory for luke2
  • TCShell is set as the shell environment for luke2
Idea.png
For the full list of available command options, refer to useradd(8) manual page.

Adding Group Accounts

To add a new group account, from the command line run:

su -c "/usr/sbin/groupadd black"

and enter the root password when prompted.

The above command creates a new group account with the group name black.

Modifying Account Parameters

To edit user account parameters, use the usermod command. Depending on what account parameters need modification, usermod command may need to be supplied with an option specific to that parameter. For example, to change the comment field for the account, run:

su -c "/usr/sbin/usermod -c 'Luke McAlister' luke"

Enter the root password at the password prompt.

This alters the account information in /etc/passwd file, placing the user's full name in the fifth field. The line changes from:

luke:x:503:503::/home/luke:/bin/bash

to

luke:x:503:503:Luke McAlister:/home/luke:/bin/bash

You can also edit user's group membership using the usermod command. When a user is created, a new group with the same name as the username is created. This group is the user's Primary Group. Files or directories created by said user inherit said users Primary Group. Use the id command to view Primary and Secondary Group memberships:

id
uid=500(user1) gid=500(user1) groups=10(wheel),500(user1) context=user_u:system_r:unconfined_t

The above example shows that the Primary Group for the user user1, is gid 500 (user1). The user1 user is also a member of the wheel Secondary Group. Primary Groups are defined in /etc/passwd:

user1:x:500:500:UserOne:/home/user1:/bin/bash

The fourth field shows the Primary Group ID (500) for the user. The /etc/passwd file uses the following syntax: account:password:UID:GID:GECOS:directory:shell

The Primary Group can be temporarily changed using the newgrp command. However, the user must already be a member of the group specified:

newgrp testing

The results can be seen using the id and touch commands:

id
uid=500(user1) gid=502(testing) groups=10(wheel),500(user1),502(testing) context=user_u:system_r:unconfined_t

Note, the Primary Group is now gid 502 (testing).

touch file1
ls -l file1
-rw-r--r-- 1 user1 testing 0 2007-10-13 20:31 file1

The file1 file belongs to the testing group instead of the user1 group. Type exit to return to your original Primary Group; the output of the exit command is exit:

exit
exit
id
uid=500(user1) gid=500(user1) groups=10(wheel),500(user1) context=user_u:system_r:unconfined_t

The Primary Group is now back to user1. Also note the id command has not displayed the testing group. Changes to group membership require you to log out and then log in, before the changes are displayed using the id and groups commands. Users can also be members of Secondary Groups. Secondary groups are defined in /etc/group. Use the groups and id commands to view group membership:

groups
user1 wheel testing
id
uid=500(user1) gid=500(user1) groups=10(wheel),500(user1),502(testing) context=user_u:system_r:unconfined_t

To add a user to a Secondary Group, use the following command:

su -c "/usr/sbin/usermod -a -G <group> <username>"

Enter the root password when prompted.

This adds the user specified with <username> to the Secondary Group specified in <group>. To add a user to multiple Secondary Groups list the group names in comma-separated form:

su -c "/usr/sbin/usermod -a -G <group1>,<group2>,<group3> <username>"

Enter the root password when prompted.

Removing a user from a group is a little different. Use the usermod command without the -a append switch to specify the group memberships you want to keep. For example, if the mentioned user is a member of group1, group2, group3, and group4, but you want to remove the user from group4, then run the following command:

su -c "/usr/sbin/usermod -G group1,group2,group3 <username>"

This command keeps the user's group memberships of group1, group2, and group3, while removing membership from the group4.

For the full list of available command options, refer to the usermod(8) manual page.

Important.png
Be careful with the -G command option!
If the user is a member of multiple groups, all the groups must be listed as parameters in a comma-separated form: -G <group1,group2,group3,group4>. When you omit a group name you remove the user from that group.

Modifying Group Accounts

To modify group account parameters, use the groupmod command. This command can change two group account parameters, the group ID (GID) and group name. To change the group ID (GID) of the group black, run:

su -c "/usr/sbin/groupmod -g 600 black"

Enter root password at the prompt. This command would change the GID of the group black to 600. If you do not use -o option, the GID numerical value supplied to the command must be unique.

Idea.png
The groupmod command does not change group ownership of files.
You must manually change group ID (GID) ownership of all the files owned by the group's previous group ID.

To assign a new name to the group account, run:

su -c "/usr/sbin/groupmod -n blue black"

Enter the root password at the prompt. This changes the group's name from black to blue.

Changing Password Expiration Information

To change the user's password expiration information use the chage command. This command changes the number of days between password changes and the date of the last password change and is used by the system to determine when the user is forced to change the password. For example, to set the number of days the password of the user dan to be valid for 90 days (three months), run:

su -c "chage -M 90 dan"

Enter the root password at the prompt. The above option is usually used in conjunction with -W option, which sets the number of days before expiration the user is warned about the pending expiration:

su -c "chage -W 10 -M 90 dan"

Enter the root password when prompted. The above command forces the user dan to change the password after 90 days. User dan is warned about this every day, starting 10 days before the password expiration.

Idea.png
For the full list of available command options, refer to the chage(1) manual page.

Account Management - Using A Graphical User Interface

This section explains how to manage user and group accounts using a graphical user interface (GUI). User Manager is the application used to create and manage user and group accounts.

Idea.png
To run User Manager, you must have the X Window system installed,configured and the system-config-users package installed.

To start User Manager select System > Administration > Users and groups from the main panel menu or from the command line run system-config-users and enter the root password at the prompt.

File:Docs Drafts AdministrationGuide UserAccounts usermanager.png

By default, User Manager does not display system accounts. To enable the listing of system accounts, from the main menu select Edit > Preferences

File:Docs Drafts AdministrationGuide UserAccounts usermanagerprefs.png

and uncheck the box next to Hide system users and groups. You can use the Preferences window to modify the default behavior of automatically assigning the next available UID or GID to user and group accounts or creating the GID of the user's private group with the identical value as the user's UID. This is achieved by unchecking the appropriate boxes in the New users pane of the Preferences window.

To search for the user, enter first few letters of the username in the search filter field and click the Apply filter button.

You can sort the users list by clicking on the column name. Text fields are sorted in alphabetical order and numerical fields in the ascending order of the values in the field.

Adding A New User

To add a new account click the Add User button on the main toolbar.

File:Docs Drafts AdministrationGuide UserAccounts newuser.png

Type the username, user's full name and password (remember passwords are case-sensitive) in appropriate fields. Pre-selected fields represent the defaults for Fedora - /bin/bash is default shell, /home/<username> is created as user's home directory, private group with the same name will be created for user and next available UID will be used. If you choose to, you can change any of these options. Once you supply all the information, click [OK] button to create account.

Adding A New Group

To list the existing groups in the User Manager window click on the Groups tab. The same rules apply for sorting available columns and searching for a particular group as applied to the Users tab.

File:Docs Drafts AdministrationGuide UserAccounts groupstab.png

To create a new group, click the Add Group button on the main toolbar of the User Manager.

File:Docs Drafts AdministrationGuide UserAccounts addgroup.png

Type the group name in the Group Name field and click [OK] . By default, the new group will be added with the next available GID. You can manually change this behavior by checking the box Specify group ID manually and selecting a different, unused number from the list.

Modifying User Accounts

File:Docs Drafts AdministrationGuide UserAccounts usermanagerselect.png

To display the properties of a user account, select the account from the list and click the Properties button, which is now active, on the main toolbar of the User Manager window. The User Properties window opens, with User Data tab focused:

File:Docs Drafts AdministrationGuide UserAccounts userpropertiesdata.png

You can change the account name, user's full name, password, home directory and user's shell by altering information in appropriate fields.

Click the Account info tab.

File:Docs Drafts AdministrationGuide UserAccounts userpropertiesaccinfo.png

Check Enable account expiration box and enter the date to expire user account on that day. Check Local password is locked box to lock the user account.

Click the Password info tab.

File:Docs Drafts AdministrationGuide UserAccounts userpropertiespwd.png

Time of the last password change is displayed. Check Enable password expiration box. This will allow you to disable password change for user, force the user to change their password and warn the user about that change in advance and when the account will become inactive. Each of the four fields accepts integers, representing number of days.

Click the Groups tab.

File:Docs Drafts AdministrationGuide UserAccounts userpropertiesgrp.png

Change the user's group membership by checking or unchecking the box next to group name. If the user is a member of multiple groups, set the user's primary group by selecting the group from the Primary group drop-down list.

Modifying Group Accounts

To modify group accounts select the group from the Groups tab of the User Manager

File:Docs Drafts AdministrationGuide UserAccounts usermanagergrpselect.png

To view group properties, click the Properties button on the main toolbar. The Group Properties window opens

File:Docs Drafts AdministrationGuide UserAccounts grouppropertiesdata.png

with the Group Data tab in focus. To change the group name, edit text in the Group Name field.

Click the Group Users tab.

File:Docs Drafts AdministrationGuide UserAccounts grouppropertiesusers.png

To add users to this group, check the box next to appropriate user names on the list.

Additional Information

For additional help and more information on managing user accounts look at:

Websites

username and password guidelines

username and group file(s) information

Manual Pages

  • passwd(1) ---Learn more about the file format information for the /etc/passwd file.
  • group(5) ---Learn more about the file format information for the /etc/group file.
  • shadow(5) ---Learn more about the file format information for the /etc/shadow file.
  • useradd(8) ---Learn how to create or update user accounts.
  • userdel(8) ---Learn how to delete user accounts.
  • usermod(8) ---Learn how to modify user accounts.
  • chpasswd(8) ---Learn how to batch update user passwords.
  • chage(1) ---Learn how to change user password aging information.
  • chfn(1) ---Learn how to change a user's GECOS (finger) information.
  • chsh(1) ---Learn how to change a user's login shell.
  • groupadd(8) ---Learn how to create a new group.
  • groupdel(8) ---Learn how to delete a group.
  • groupmod(8) ---Learn how to modify a group.
  • gpasswd(1) ---Learn how to administer the /etc/group and /etc/gshadow files.
  • grpck(1) ---Learn how to verify the integrity of the /etc/group and /etc/gshadow files.
  • chgrp(1) ---Learn how to change group-level ownership.
  • chmod(1) ---Learn how to change file access permissions.
  • chown(1) ---Learn how to change file owner and group.
Idea.png
This section is ready for editing

Permissions

Introduction

Managing user permissions is an important administrative task. There are many commmand line tools available such as chown, chgrp, and chmod. Use command line tools in either : symbolic and numeric mode to alter user permissions. The symbolic method uses symbols such as u, +, x, r, and so on, to representing owners, groups, and permissions to alter permissions. The numeric method uses a numbering scheme.

Each file and directory has permissions for the owner (UID), group (GID), and everyone else (WORLD). The permissions for each group consist of three (binary) bits. There are 10 bits in total: --- --- --- (the 10th bit is the setuid or sticky bit - this will be described later). To alter permissions for owner use first three bits. Use the next three bits to alter permissions of group, and use the last three bits to alter permissions for everyone else.

Use the ls -l command to view file and directory permissions:

ls -l file1
-rw-rw-r-- 1 user1 group1 0 Oct 22 17:51 file1

The above example shows the following permissions for the file1 file:

  • user1: read and write
  • group1: read and write
  • everyone else: read

The three main symbols used to represent permissions are r, w, and x. These represent read, write, and execute permissions respectively. File permissions are as follows:

  • read: files can be opened and viewed using commands such as cat and less
  • write: edit, save, and delete files
  • execute: allows you to execute the file (files will not be executable unless you also have read permissions)

Permissions for directories are as follows:

  • read: list the contents using the ls command
  • write: edit, save, and delete files within said directory
  • execute: allows you to change into said directory using the cd command. Execute permissions are required to perform a long listing using the ls -l command. Without execute permissions the ls -l command will return output similar to the following:
ls -l test1/
ls: cannot access test1/file1: Permission denied
ls: cannot access test1/file2: Permission denied
total 0
-????????? ? ? ? ?                ? file1
-????????? ? ? ? ?                ? file2
Important.png
Directory write Permissions
If a user has write permissions on a directory, that user can remove any file within that directory regardless of file permissions.

The Concept Of umask

The User File Creation Mask or umask value is the bash built-in that defines the default mode for newly created files or directories. The umask value is determined when the effective permissions value of the new files is subtracted from a value of the full file permissions. On Linux systems, full file permissions are:

  • 777 - for directories
  • 666 - for files

The default umask values on Fedora are set in /etc/bashrc. The default umask for user root is 0022 and for regular users (users whose UID is identical to their primary group's GID), umask value is set to 0002. For practical purposes, the first 0 is ignored - it denotes that this value is an octal number. To calculate the default creation mode (effective permissions) of all files and directories created by root user, subtract 022 from the full access mode value of 777 for directories or 666 for files. This means that:

  • new files created by root have permissions set to 644 (666 - 022), or rw-r--r-- in a symbolic denotation
  • new directories created by root have permissions set to 755 (777 - 022), or rwxr-xr-x in a symbolic denotation

Using the same technique, default permissions for files and directories created by normal users are:

  • 664 (666 - 002) or rw-rw-r-- for files
  • 775 (777 - 002) or rwxrwxr-x for directories

User can change this behavior by running umask command with a desired mode as a command argument:

umask 0022

This will cause all new files created by user to have permissions set to 644 and all new directories' permissions set to 755. The change will be in effect until the shell environment is re-initialized. To make permanent changes add umask command to user's ~/.bashrc file. For example, user may wish to have all new files and directories accessible only by himself. In other words, effective permissions on new files should be 600 or rw------- and on new directories 700 or rwx------. To achieve this, add the line:

umask 0077

to the end of ~/.bashrc file, which is the file located under the user's home directory.

Managing Permissions Using The Command Line Interface

Symbolic Method

The following table describes the symbols used to change permissions using the symbolic method. Familiarize yourself with this table before proceeding to the next section:

u the owner of the file or directory
g the group the file or directory belongs to
o everyone else
a everyone (u, g, and o)
add a permission
= assign a permission
r read permissions
w write permissions
x execute permissions
t directory sticky bit
s setuid or setgid

To add a permission to a user, group, or everyone else, use the + symbol. The following example adds execute permissions for the owner (u):

chmod u+x file1

To add execute permissions to the owner, and the group, use the following command:

chmod u+x,g+x file1

Please note there is no space between the u+x and g+x. Permissions do not have to be specified separately. The following has the same result as running the chmod u+x,g+x file1 command:

chmod ug+x file1

You must list all permissions needed when you assign permissions using the = symbol. For example, if the owner of the file1 file has read, write, and execute permissions, the follow command removes all but the owners read permissions:

chmod u=r file1

Note, if the group and everyone else had permissions, the previous command would not remove those permissions. You must only list all the permissions if you specify the owner, group, or everyone else when using the chmod command.

Use the - symbol to remove permissions. For example, if the owner of the file1 file had execute permissions, the following command would remove those permissions:

chmod u-x file1

Numeric Method

The following table describes the numbering scheme used when changing permissions using the numeric method:

Number Permissions ls -l Output
0 no permissions ---
1 execute --x
2 write -w-
3 write and execute -wx
4 read r--
5 read and execute r-x
6 read and write rw-
7 read, write, and execute rwx

Use the chmod command to change permissions regardless of whether you are using the symbolic or numeric method.

To set permissions using the numeric method, use the chmod xxx command, where xxx are values between 0 and 7. The table above describes the permissions each value (0-7) applies. The first value is the permission for the owner. The second value is for the group, and the third value is for everyone else.

Use the following command to assign the owner read, write, and execute permissions, and remove all permissions for the group and everyone else:

chmod 700 file1

View the permissions using the ls -l command:

ls -l
-rwx------ 1 user1 user1 0 Oct 27 16:02 file1

Use the following command to add read and write permissions for the file1 file for the owner, group, and everyone else:

chmod 666 file1

To change permissions on a folder, and all files and sub-directories within that folder, use the -R option:

chmod -R 700 folder1

This applies mode 700 permissions to the folder1 folder, and recursively changes the permissions of all files and sub-directories within the folder1 folder.

Permissions on Directories

Execute permission on a directory does not allow files within that directory to be executed. Rather, it allows users to change into that directory using the cd command. It also allows user to perform a long listing using ls -l command. However, files within a directory can be executed if said files have execute permissions.

Managing Permissions Using The Graphical User Interface

Follow these steps to access a graphical user interface (GUI) for managing permissions on files and folders:

  • Right click on the file or folder.
  • On the menu that appears, click the Properties menu item.
  • Click the Permissions tab.

Folder Permissions

The following table describes the Folder Access permissions. Changes to Folder Access permissions take immediate effect:

Create and delete files read, write, and execute
Access files read and execute
List files only read
None no permissions, all actions are denied

The following table describes File Access permissions. This allows finer-grained control of files within directories. Changes to File Access permissions take effect only after clicking the Apply permissions to enclosed files button.

Read and write read and write
Read-only read

When the File Access is set to ---, clicking Apply permissions to enclosed files keeps the current file permissions without changing them.

If the Execute: Allow executing file as program box is ticked, execute permissions are applied for everyone to files within that directory. If the Execute: Allow executing file as program box is not ticked, and you click the Apply permissions to enclosed files button, execute permissions are not removed from files within that directory.

If you are a member of a Secondary Group, change the group owner using the Groupdrop-down menu.

Idea.png
File Access Permissions
After closing and re-opening the properties window for a file or directory, the File Access permissions appear as ---. Your permissions are still set. Use the ls -l [foldername] command to view the file access permissions. If you are already in the [foldername] directory, use the ls -l command.

File Permissions

The following table describes the Access permissions for files. Changes to Access permissions take immediate effect:

Read-only read
Read and write read and write
None no permissions, all actions are denied

Ticking the Execute: Allow executing file as program box applies execute permissions for everyone to the file.

If you are a member of a Secondary Group you can change the group owner using the Group drop-down menu.

Special Permissions

There are two special permissions that can be set on executable files: Set User ID (setuid) and Set Group ID (sgid). These permissions allow the file being executed to be executed with the privileges of the owner or the group. For example, if a file was owned by the root user and has the setuid bit set, no matter who executed the file it would always run with root user privileges.

Set User ID (setuid)

You must be the owner of the file or the root user to set the setuid bit. Run the following command to set the setuid bit:

chmod u+s file1

View the permissions using the ls -l command:

ls -l file1
-rwSrw-r-- 1 user1 user1 0 2007-10-29 21:41 file1

Note the capital S. This means there are no execute permissions. Run the following command to add execute permissions to the file1 file, noting the lower case s:

chmod u+x file1
ls -l file1
-rwsrw-r-- 1 user1 user1 0 2007-10-29 21:41 file1

Note the lower case s. This means there are execute permissions.

Alternatively, you can set the setuid bit using the numeric method by prepending a 4 to the mode. For example, to set the setuid bit, read, write, and execute permissions for owner of the file1 file, run the following command:

chmod 4700 file1

Set Group ID (setgid)

When the Set Group ID bit is set, the executable is run with the authority of the group. For example, if a file was owned by the users group, no matter who executed that file it would always run with the authority of the users group. For example, run the following command as to set the setgid bit on the file1 file:

chmod g+s

Note that both the setuid and setgid bits are set using the s symbol. Alternatively, prepend a 2 to the mode. For example, run the following command as root to set the setgid bit, and read, write, and execute permissions for the owner of the file1 file:

chmod 2700 file1

The setgid is represented the same as the setuid bit, except in the group section of the permissions:

ls -l file1
-rwx--S--- 1 user1 user1 0 2007-10-30 21:40 file1

Use the chmod u+s command to set the setuid bit. Use the chmod g+s command to set the setgid bit.

Special Permissions for Directories

There are two special permissions for directories: the sticky bit and the setgid bit. When the sticky bit is set on a directory, only the root user, the owner of the directory, and the owner of a file can remove files within said directory.

Sticky Bit

An example of the sticky bit is the /tmp directory. Use the ls -ld /tmp command to view the permissions:

ls -ld /tmp
drwxrwxrwt  24 root root  4096 2007-10-30 22:00 tmp

The t at the end symbolizes that the sticky bit is set. A file created in the /tmp directory can only be removed by its owner, or the root user. For example, run the following command to set the sticky bit on the folder1 folder:

chmod a+t folder1

Alternatively, prepend a 1 to the mode of a directory to set the sticky bit:

chmod 1777 folder1

The permissions should be read, write, and execute for the owner, group, and everyone else, on directories that have the sticky bit set. This allows anyone to cd into the directory and create files.

Set Group ID

When the setgid bit is set on a directory, all files created within said directory inherit the group ownership of that directory. For example, the folder1 folder is owned by the user user1, and the group group1:

ls -ld folder1
drwxrwxr-x 2 user1 group1 4096 2007-10-30 22:25 folder1

Files created in the folder1 folder will inherit the group1 group membership:

touch folder1/file1
ls -l folder1/file1
-rw-rw-r-- 1 user1 group1 0 2007-10-30 22:29 folder1/file1

To set the setgid bit on a directory, use the chmod g+s command:

chmod g+s folder1

View the permissions using the ls -ld command, noting the s in the group permissions:

ls -ld folder1
drwxrwsr-x 2 user1 group1 4096 2007-10-30 22:32 folder1

Alternatively, prepend a 2 to the directories mode:

chmod 2770 folder1
Important.png
Old page
This page has been marked as "old", and likely contains content that is irrelevant or incorrect. If you can, please update this page. This page will be deleted if action is not taken.
Stop (medium size).png
Section is ready for conversion to XML

Access Control Lists

What Are ACLs And Their Purpose

Access control lists (ACLs) are a kernel-level feature of Fedora's default ext3 file system. ACLs provide an important level of flexibility for managing file permissions, that is, who or what has the rights to read, write, or execute a file.

Traditional Linux/UNIX file permissions (read, write, execute) are defined for three classes of users: the file owner, the file group, and others. This means that when a group is granted access to a particular shared resource (document, directory, printer, etc.), the same level of access is granted to all members of a group.

In practice, it is often required that some of the group members have limited or no access to the shared resource, or that the access is granted to other users who are not members of the particular group. In a non-ACL file permissions scheme this requires creation of numerous new groups, which quickly becomes difficult to manage, especially on large systems.

Fedora provides ACL support for ext3, NFS-exported ext3, and ext3 file systems accessed via Samba (which provides CIFS/Microsoft Windows file sharing.)

The most common file manipulation utilities, such as mv, cp, and ls also support ACLs. To preserve ACLs when archiving files, the star utility should be used instead of tar, which does not support ACLs.

There are two types of ACLs:

  • Access ACL - ACL that controls the level of access to the object (file or directory)
  • Default ACL - ACL associated with a directory. If set, all objects within a directory inherit the default ACL as their initial access ACL

Each ACL is composed of a set of ACL entries. Each ACL entry specifies access permissions to the object as a combination of read, write, and execute permissions for an individual user or a group.

Using Access Control Lists

There are a few prerequisites to using ACLs:

  • File system must support ACLs
  • File system must be mounted with acl option
  • RPM package acl must be installed

Enabling ACLs on a file system

On a default Fedora installation, file systems are mounted without ACL support. To enable ACLs for a local file system, edit the /etc/fstab file and add the acl option for the desired partition. The entry might look similar to:

LABEL=/data   /data   ext3   rw,acl   1 2

This entry ensures that ACL support is preserved after reboot but reboot is not required to enable ACLs. To accomplish this on an already mounted /data partition run:

su -c '/bin/mount -o remount /data'

Additional parameters are not required when mounting ACL enabled remote Samba shares. If the client accessing an NFS share can read ACLs and the NFS share is exported from an ACL enabled file system, ACLs are utilized by the client.

Setting ACLs and retrieving ACL information

ACLs are controlled by two utilities:

  • getfacl is used to retrieve ACL information
  • setfacl is used to set or modify ACL entry

To view ACL information on an object (directory docs) in the /data directory, run:

getfacl /data/docs

The output shows ACL information associated with the docs directory:

getfacl: Removing leading '/' from absolute path names
user::rwx
group::r-x
other::r-x

Since ACLs are not yet set, this information corresponds to common permissions on the /data/docs directory:

ls -dl /data/docs
drwxr-xr-x 5 jerry black 4096 Nov  1 19:57 /data/docs

To set an ACL for an object, run setfacl:

setfacl -m <rules> <object>

The command option -m is used to create or modify an ACL entry. For an object without previously set ACLs, a new ACL entry is created. If an object already has an ACL entry, option -m modifies the existing ACL entry by appending the new ACL entry to the object's ACL.

Idea.png
If using the --set option, all user, group, and others permissions must be defined.
The command option --set is used to create a new ACL or replace all existing ACLs on the object, so it needs a complete definition for the setting.

The <object> is a file or a directory on which an ACL is created

The <rules> are specified per user, per group, using an effective rights mask or for users who are not members of the user group for an object, using one of the following:

u:<uid>:<permissions>: sets the ACL for user; <uid> can be user name or numerical UID; <permissions> are any combination of rwx

g:<gid>:<permissions>: sets the ACL for group; <gid> can be group name or numerical GID; <permissions> are any combination of rwx

m:<permissions>: sets the effective rights mask on the object; <permissions> are any combination of rwx

o:<permissions>: sets the ACL for users who are not members of the object group; <permissions> are any combination of rwx

The effective rights mask is a sum of all permissions of the object group owner and all ACLs set on the object. It represents the actual rights granted to all ACL users and groups on the object and limits their access to the level it specifies. If a user has read and write permission through an ACL but the mask is set to read, the more restrictive permission (read) is in effect. The effective mask does not apply to file owner or file group.

Numerical UID or GID can be specified for a non-existing user or group, respectively. If the actual user or group name is specified, they must exist on the system, otherwise the setfacl command exits with an error.

To specify multiple ACLs on the same line, separate them by commas. Blank spaces are ignored:

setfacl -m u:<uid>:rw,g:<gid>:rx, u:<uid>:r /dir/file

To remove an ACL entry for user, use the -x command option and do not specify any permissions:

setfacl -x u:<uid> /dir/file

To set the default ACL, prefix the rule with a d:

setfacl -m d:g:<gid>:rx /dir

ACL examples

To grant the user carlos read, write, and execute rights on all files in the /data/docs directory, run:

setfacl -R -m u:carlos:rw /data/docs

(i) Use the -R command option to recursively set ACL on all files in /data/docs directory.

To check permissions for the /data/docs directory, run:

ls -dl /data/docs
drwxrwxr-x+ 5 jerry black 4096 Nov  1 19:57 /data/docs

To check modified ACL information for the /data/docs directory, run:

getfacl /data/docs
getfacl: Removing leading '/' from absolute path names
user::rwx
user:carlos:rwx
group::r-x
mask::rwx
other::r-x

Both of the above commands now produce a different output than previously.

The plus sign next to permission bits after the ls command shows that the ACL is now set on the object. Likewise, the getfacl output has two additional entries:

  • user:carlos:rwx indicates the additional user with the access rights on the object
  • mask::rwx denotes the effective rights on the object

The setfacl command also accepts input from text files. This is useful if identical long rules must be set for large number of objects. To accomplish this, create a plain text file (rules.txt in the next example) with a rule per line and use the -M command option to set ACL on all html files in a directory /dir:

setfacl -M rules.txt /dir/*.html

The format of the rules.txt file is the same as an output of the getfacl command with the --omit-header option:

getfacl --omit-header /data/etc/conf/script1.cfg

user::rw-
user:jerry:rw-
group::r--
group:black:r-x
mask::rwx
other::r--

This is very useful if the same ACL must be applied to some other files. You can create the rules.txt file by simply redirecting the output of the getfacl command:

getfacl --omit-header /data/etc/conf/script1.cfg > rules.txt

cat rules.txt
user::rw-
user:jerry:rw-
roup::r--
group:black:r-x
mask::rwx
other::r--

Copying And Archiving ACLs

Common file utilities mv and cp on Fedora support ACLs. Archiving tools such as tar and dump do not have support for ACLs and the star utility should be used to preserve ACLs while archiving files.

Copying And Moving ACLs

To copy the file or directory while preserving ACLs, use the -p or -a command option:

cp -p /dir1/file1 /dirx/file2
Idea.png
The /dirx directory must reside on a partition mounted with the acl option to copy the ACL of file1 to file2.
cp -a /dir1/dir2 /dirx/dir3
Idea.png
The /dirx directory must reside on a partition mounted with the acl option to copy the ACLs of dir2 to dir3.

The mv command always transfers ACLs, without any extra command options, if the destination file system is ACL enabled. If not, it transfers the files and issues a warning about the inability to preserve ACLs.

Archiving ACLs

To archive the files or directories while preserving ACLs, use the star command with the -acl option:

star -c -acl file=archive.star /data

This creates the backup.star archive of /data directory with preserved ACLs.

To restore the star archive and ACLs, run star with the -acl command option:

star -x -acl file=backup.star

This extracts the backup.star archive into current directory with preserved ACLs. The target filesystem being extracted to must support ACLs for this to work.

Additional Information

Related web sites

ACLs web site: [1]

Related manuals

For more information on ACLs and associated utilities, read the following manual pages:

  • man acl
  • man getfacl
  • man setfacl
  • man star
Warning.png
Section is ready for conversion to XML


Services and Daemons

Introduction

Services (daemons) are programs that perform useful functions on a system but are not normally started by the user. For example, MySQL runs normally as a service; it is not started every time another service needs to connect to the database. Instead, it is normally always running once configured, unless manually shut down.

Services can be started at other times than at system boot. They may be turned on,off, or restarted without restarting the machine as well as being set to run only at certain run levels.

Run levels are various states the machine can exist in. There are two main run levels most Linux users see. Run level 5 is usually the default for most systems, and presents a full graphical environment. The other is run level 3, which is typically used on servers that don't run a graphical environment, or for trouble shooting and low level system driver installation. Run level 0 is a system halt. Run level 6 is a system reboot. To change run levels, use the init command.

Services and Security

Turn off any service not being used. Leaving a service running that is not used leaves a potential system vulnerability for no benefit. For example, Bluetooth in Fedora is enabled by default. If the system isn't actively connecting to a Bluetooth device, there is no reason to keep the service running. Until recently an ISDN service ran by default. If the system does not use ISDN to connect to the Internet, there is no reason to have it installed and always running. There are several ways to find out what a running system's purpose is. [[The GUI service menus often ]have descriptions.?? On the command line, the command man <service name> produces documentation about most services. The general rule is to leave it running unless it is known what the services does.

Configuring Services

  1. In KDE (presumes the kde-admin tools are installed): Click on the Fedora icon in the toolbar on the default desktop, then navigate to Administration > Server Settings > Services.
  2. In Gnome, in the toolbar click on System > Server Settings > Services.
  3. Give the root password when prompted.

In the KDE services application, clicking on a service produces a description of that service and its status. Services without a check mark are not started at run (boot) time. To prevent a service from running on system start up, uncheck the box next to it.

  • To enable a service at start up, check the box.
  • To stop a service select it, then click on the Stop button.

In the GNOME services application, the On Demand Services tab is for services that are loaded when a client program calls them. For example, the backup system Amanda only runs when an Amanda client talks to the system.

To save the new configuration, click on the Save button. Failing to save changes means the services do not change start up behavior. Clicking on the Revert button erases all the changes.

Services can be configured to start/not start from the command line using chkconfig. The basic usage of chkconfig is to check the list of services and what run level they start in:

/sbin/chkconfig --list
NetworkManager  0:off   1:off   2:on    3:on    4:on    5:on    6:off
NetworkManagerDispatcher        0:off   1:off   2:off   3:off   4:off   5:off   6:off
acpid           0:off   1:off   2:off   3:off   4:off   5:off   6:off
anacron         0:off   1:off   2:on    3:on    4:on    5:on    6:off
apmd            0:off   1:off   2:on    3:on    4:on    5:on    6:off
atd             0:off   1:off   2:off   3:on    4:on    5:on    6:off
auditd          0:off   1:off   2:on    3:on    4:on    5:on    6:off
autofs          0:off   1:off   2:off   3:on    4:on    5:on    6:off
avahi-daemon    0:off   1:off   2:off   3:on    4:on    5:on    6:off
...
  1. Open a terminal window (Applications > Accessories > Terminal)
  2. To disable a service such as sendmail:
    su -c 'chkconfig --level 2345 sendmail off'
    This stops sendmail from being started in run levels 2,3,4, and 5.
  3. To turn sendmail on for run levels 3 and 5:
    su -c 'chkconfig --level 35 sendmail on'

A full list of chkconfig options is available on the manual page:

man chkconfig

To manually stop, restart, or start a service that wasn't already running, use the service command. This example starts the sendmail service:

su -c 'service sendmail restart'

In the screen capture you see an example of stopping a service that failed. In this case because the service was already stopped. You will also see an example of starting NFS. Notice that not just NFS started. 3 other services started automatically when NFS started. Many services are like this.

There is one final way to edit services.

Important.png
It is highly recommended to use chkconfig or the GUI tools to modify services, as well as using the service command.

To stop a service, use ps to acquire its PID, then stop the PID using the kill command. To modify the stop/start of a service in a particular run time level, edit the /etc/rc files:

ls -d /etc/rc*
rc          rc1.d/      rc3.d/      rc5.d/      rc.d/       rc.sysinit
rc0.d/      rc2.d/      rc4.d/      rc6.d/      rc.local

Each directory corresponds with the same numbered run time level. To start a service for run time level 5, add a link in the /etc/rc5.d/ directory to the corresponding start script in /etc/init.d. The S and K prefix with a number refers to the order in which that service is started or stopped when the system is starting up or shutting down.

These last methods are recommended only for experienced users. On rare occasions it is necessary to modify these files to change default behavior. Generally, an administrator never has to directly touch these files.

xinetd-Based Services

Many services run as sub-services managed by the xinetd service. FTP servers, backup servers, rsync, and a host of others. To enable or disable these services, use the chkconfig command as with init based services.

A default configuration of xinetd services is:

/sbin/chkconfig --list
...
xinetd based services:
amanda:         off
amandaidx:      off
amidxtape:      off
apgd:           off
chargen-dgram:  off
chargen-stream: off
csync2:         off
cups-lpd:       off
cvs:            off
daytime-dgram:  off
daytime-stream: off
discard-dgram:  off
discard-stream: off
echo-dgram:     off
echo-stream:    off
eklogin:        off
ekrb5-telnet:   off
gssftp:         off
klogin:         off
krb5-telnet:    off
kshell:         off
ktalk:          off
rsync:          off
tcpmux-server:  off
time-dgram:     off
time-stream:    off

For example, to turn on the xinetd service for rsync, use the following command:

/sbin/chkconfig rsync on

Then reload the service's configuration with the command su -c 'service xinetd reload'.

Re-issueing the /sbin/chkconfig --list command you now see

/sbin/chkconfig --list | grep rsync
rsync:          on

To customize the configuration of an xinetd service, edit the file for that service in the /etc/xinetd.d directory. For more information on the syntax of these configuration files, refer to the man page for xinetd.conf(5).

Common Services

Some services commonly found on Fedora installations.

Service Description
Amanda BackupPC Backup software
abrt Automatic Bug-Reporting Tool.
acpid Advanced Configuration and Power Interface daemon which controls and allows interfacing to power management and certain input devices..
amd Runs the automount daemon for remote filesystem mounting such as nfs.
anacron and crond Runs certain programs at specified times.
apmd Monitors laptop battery power and shuts down if power gets too low.
atd at scheduler. Automatically runs programs/scripts that meet certain criteria.
auditd System audit daemon
autofs Used to automatically mount filesystems listed in fstab.
avahi-daemon, avahi-dnsconfd Supports Apple's Zeroconf protocol.
bluetooth Provides Bluetooth functionality.
btseed, bttrack Bittorrent related utils.
cfenvd, cfexecd, cfservd Part of the cfengine services. cfengine is a system configuration an anomaly detection.
cman Cluster manager
cpuspeed System sensor and CPU speed adjustment.
cups Printing support
dbmail, Postfix, Sendmail, spamassassin, dovecot Email services and spam protection.
dc_client, dc_server Caching services
denyhosts Log watcher that bans hosts with too many failed login attempts.
dhcdbd Allow systems to use a DHCP server to obtain an IP address.
dund Bluetooth dial-up networking
firstboot Used after installation for post-installation configuration. You should turn this off after these configurations are complete.
gpm Mouse support on the console
haldaemon Hardware detection layer
hidd Bluetooth HID daemon
hplip HP Linux Imaging and Printing
httpd Apache web server
ip6tables and iptable Firewall
ipsec IPsec encryption/authentication
irda Provides infrared device services.
irqbalance Distributes hardware interrupts across processors on a multi-processor system.
isdn Provides ISDN functionality.
jexec This is provided as a helper to directly run java JAR applications. This is will be included if you installed Sun Java. It is not necessary and can be disabled.
kdump kexec based crash dumping mechanism for Linux.
kudzu Looks for new hardware at boot. Runs only at boot time.
ldap LDAP server
lirc Linux infrared support
lisa Network discovery and protocols
lm_sensors Support for hardware sensors such as CPU temp.
lpd local printer services
lvm2-monitor This is a monitoring application for your LVM (Logical Volume Management) system. This is recommended if you use LVM, however if you use manually partition your drives it can be disabled.
mcstran SELinux related
mdmonitor Software RAID support. Turn off if you are not using it.
mdmpd Multipath device support
messagebus App to app communications
multipathd failover and multipath support
microcode_ctl Support for IA32 (Intel PII and newer) microcode
mysqld, Postgresql, Oracle Database servers
named Bind DNS server
netfs Mounts NFS, SMB and other remote filesystems.
netplugd Linux networking related services
network Brings up the network.
nfs, nfslock Provides NFS services.
nscd Name service cache daemon
ntpd Syncs your computer clock with time servers.
openais Clustering, failover, checkpointing and related API.
pand BlueZ Bluetooth PAN daemon
pcmcia Provides pcmcia support. May be safely stopped if you are not using a laptop.
pcscd Smart card support
portmap Support for port mapping and RPC.
psacct Monitors system activity and provides audit trail of user actions.
pxe Provides pxe support. (Preboot execution environment)
raduisd Provides radius VPN support.
random Kernel random number generator.
rdisc Network discovery daemon
readahead_early, readahead_later Used in speeding up boot time.
restorecond Sets default SELinux context on new files.
rpcgssd, rpcidmap, rpcsvcgssd Network file-sharing support
rsync rsync run as a service. Synchronises files mostly between remote systems.
saslauthd SASL authentication server
sgi_fam File alteration monitor
smartd Watches hard-drives for problems.
smb Samba server
snmpd, snmtrapd Linux SNMP support
squid Proxy server
sshd SSH server
syslog System logging service
sysstat Starts special system logging services.
tux Tux web server
vncserver VNC server
vsftpd FTP server
winbind Maps Windows domain databases to UNIX
wpa_supplicant WPA (Wi-Fi Protected Access) supplicant for Linux
xend, xendomains, VMware, libvirtd Provides a virtual machine.
xfs X Font Server
ypbind YP/NIS support
yum-updatesd Automatic yum updates


Managing DHCP Server

DHCP (Dynamic Host Configuration Protocol) allows DHCP or BOOTP clients on the network to request the basic network configuration information. This information includes the IP address, subnet netmask, the address of the router, and the DNS domain name and the DNS server's IP address and in Fedora is provided by the dhcpd daemon.

Single DHCP server per subnet is the common setup. If installed, DHCP forwarding agents allow DHCP clients to receive the network information from servers that are located on a different network segments. DHCP server assigns leased addresses for the predetermined amount of time, configured in the dhcpd.conf file. DHCP server keeps track of leased addresses by placing them in the /var/lib/dhcp/dhcpd.leases file.

Installing DHCP Server

To install DHCP server, run:

su -c "/usr/bin/yum install dhcp"

Configuring DHCP Server

/etc/dhcpd.conf is the configuration file for the DHCP server. Once dhcp rpm package is installed, empty /etc/dhcpd.conf file is available. The file is empty in the sense that it doesn't provide any configuration but points to the location of the sample configuration file that can be used as a base. /etc/dhcpd.conf may look similar to the following:

# global options
ddns-update-style none;   # Dynamic DNS updates are turned off
option domain-name "example.com";   # DNS domain name assigned to client
option domain-name-servers 192.168.1.10;   # IP address of the DNS server
max-lease-time 172800;   # maximum lease time - 2 days
default-lease-time 86400;   # seconds till lease expire - 1 day
subnet 192.168.1.0 netmask 255.255.255.0

{
option routers 192.168.1.1;   # default gateway
option subnet-mask 255.255.255.0;   # netmask assigned to clients
range 192.168.1.150 192.168.1.249;   # pool of the addresses to lease
}

To assign the WINS server, or nmbd part of the Samba server to Windows DHCP clients, use the following options, either globally or per appropriate subnet:

option netbios-name-servers 192.168.1.11;   # IP address of the Samba or WINS server
option netbios-node-type 0x08;   # equivalent of the MS WINS type "hybrid"

In addition, /etc/dhcpd.conf may include the information about the NIS server, NTP (Network Time Protocol) server, etc.

DHCP server also allows for the permanent assignment of the particular IP address, based on the client's MAC address, which is commonly used for BOOTP clients:

host station3 {
hardware ethernet 00:0B:DB:14:C9:40;
fixed-address 192.168.1.103;
}

To start the DHCP server, run:

su -c "/sbin/service dhcpd start"

To enable DHCP server at boot time, run:

su -c "/sbin/chkconfig dhcpd on"

Additional Information

Related Manuals

  • man 8 dhcpd
  • man 5 dhcpd.conf

Apache web server

Installing Apache Web Server

The basic Apache functionality, serving static web sites, is provided by the httpd rpm package. To install Apache, run:

su -c "/usr/bin/yum install httpd"

Unless the requirement is to run a very basic web site, the more convenient way of installing the Apache web server is:

su -c "/usr/bin/yum groupinstall 'Web Server'"

In addition to the httpd package, the command above installs software needed to run Apache with the support for database driven web sites, support for common web scripting languages, such as PHP, perl, and python, Apache documentation provided by httpd-manual rpm package and support for serving secure, encrypted content through HTTPS protocol.

Idea.png
The Web Server package group can be installed during Fedora installation, using the option to customize software packages."

To start the Apache server, run:

 su -c "systemctl start httpd.service"

To test the correct operation of the Apache server, point the web browser to http://localhost. If the browser displays Fedora Test Page, the Apache is installed correctly.

To configure the Apache server to start at the boot time, run:

su -c "systemctl enable httpd.service"

Configuring Apache web server

There are a few characteristic directories that contain files needed for proper operation of the Apache web server:

/etc/httpd:: The location of Apache configuration files, referred to as ServerRoot.

/usr/lib/httpd/modules:: The location of various Apache modules, loaded on demand from the main configuration file.

/var/www/html:: Default location for storing web site content, referred to as DocumentRoot.

/var/log/httpd:: The location of the Apache log files.

The main Apache configuration file is /etc/httpd/conf/httpd.conf. At the minimum, there are only two directives in this file that need to be specified to enable Apache to serve the content over the Internet, The name to which server responds and the location of the web site content on the system. To serve the web content for www.example.com, these two entries are:

ServerName www.example.com:80
DocumentRoot "/var/www/html"

Reload the configuration file for these changes to take effect:

su -c "systemctl reload httpd.service"
Note.png
This configuration assumes that www.example.com resolves correctly in DNS and that the content for the web site is in the /var/www/html, the default DocumentRoot in Fedora."

/etc/httpd/conf/httpd.conf file includes instructions for almost all of the configuration options in the form of comments, ie. the lines beginning with # character. This feature makes the configuration file very long and does not allow quick changes to it. However, the Include directive within a file provides a way for splitting the configuration file into smaller, more manageable sections. The line:

Include conf.d/*.conf

causes the httpd daemon to read all *.conf files placed in the /etc/httpd/conf.d directory, in addition to to a main configuration file, during start up process. The common use of conf.d/*.conf files is to have separate configuration files for various Apache extensions or virtual hosts.

/etc/httpd/conf/httpd.conf includes numerous options for configuring the Apache web server. Other notable options are:

  • Performance tuning:
  • MaxClients limits the number of allowed simultaneous connections to the server and works together with the ServerLimit option.
  • KeepAlive allows for a number of concurrent HTTP requests over a single TCP connection.
  • TimeOut instructs the httpd daemon when to stop responding if it is under heavy load.
Warning.png
Apache performance tuning is the art of managing the trade-off against the benefit. It requires good understanding of the server's capabilities and seldom improves by including arbitrary parameters.
  • Log configuration:
  • ErrorLog points to the location where the server's errors are logged.
  • LogLevel sets the verbosity of the ErrorLog entries.
  • CustomLog points to the location where the requests are logged.
Idea.png
The Apache web server logs the requests and errors to /var/log/httpd/access_log and /var/log/httpd/error_log by default.
  • Other configuration options:
  • AddLanguage associates files with certain extension to certain languages. Useful when the web server serves pages in multiple languages.
  • LoadModule loads dynamically shared objects.
  • ScriptAlias specifies the location of CGI scripts.
  • ServerAdmin specifies who is the server administrator.
  • AddHandler maps scripts to script handlers, such as .cgi, .php, etc.
Note.png
Refer to the Apache documentation in the Additional Information section for the extensive list of the Apache configuration options and their usage.

Virtual Hosts

The Apache web server has the ability to serve the content for multiple sites from the single server through the concept of Virtual Hosts. Virtual hosts can be configured in two ways:

  • IP based Virtual Hosts:
  • Each virtual host has its own IP address and port combination.
  • Required for serving HTTPS requests, due to restrictions in the SSL protocol.
  • Name based Virtual Hosts:
  • All virtual hosts share the common IP address.
  • The Apache web server responds to the request by mapping the host header in the request to ServerName and ServerAlias directives in the particular virtual host's configuration file.

The example of the simple name based virtual hosts configuration:

# global configuration options
NameVirtualHost *:80
<VirtualHost *:80>
ServerName localhost
</VirtualHost>

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/virtual/example.com/html
</VirtualHost>

<VirtualHost *:80>
ServerName foobar.com
ServerAlias www.foobar.com
DocumentRoot /var/www/virtual/foobar.com/html
</VirtualHost>

The order in which the virtual hosts are listed is significant to the extent that the Apache will always serve the content from the first listed virtual host in case the request was made for the site that is resolvable in DNS but not defined as a ServerName or a ServerAlias.

Idea.png
Once the first VirtualHost is defined, all of the content served by Apache must also be moved into virtual hosts.

Security Considerations

Apache File Security

By default, the httpd daemon runs as the user and group apache. Therefore, all files that the httpd needs to access to operate properly must be accessible by user apache. The safe way to accomplish this is to set the ownership on all of the files to another user and allow read-only access to all other users. For example, to allow read-only access to www.foobar.com content, so it can be served over the Internet, run the following:

su -c "/bin/chown -R root:root /var/www/virtual/foobar.com"
su -c "/bin/chmod 755 /var/www/virtual/foobar.com /var/www/virtual/foobar.com/html"
su -c "/bin/chmod 644 /var/www/virtual/foobar.com/html/*"

In case the content should be readable by the Apache and nobody else, the good practice is to change the group ownership to group apache and deny access to others.

User-level ownership on files should be granted to the apache user only if the web server is expected to modify the files, for example, through the use of CGI scripts.

Apache Access Controls

To control the access to the content served by the Apache web server, use the Order, Deny, and Allow directives, within the Directory container directive. To allow access to the content of www.foobar.com:

<Directory /var/www/virtual/foobar.com/html>
Order deny,allow
</Directory>

The Order directive controls the behavior of how the access to the content is evaluated and sets the default precedence if Allow and Deny directives are not defined:

  • Order deny,allow defaults to "allow access"
  • Order allow,deny defaults to "deny access"

The latter value always overrides the former. For example, to allow access to all hosts on the 192.168.1 subnet and deny the host with the 192.168.1.66 IP address, add these options:

<Directory /var/www/virtual/foobar.com/html/priv>
Order allow,deny
Allow from 192.168.1.
Deny from 192.168.1.66
</Directory>

SELinux Notes

The best way to avoid SELinux errors while running Apache is to store the Apache related files in the default system locations. If this is not possible, the solution is to change the SELinux context on non-standard directories, using default ones as a reference:

su -c "/usr/bin/chcon -R --reference=/etc/httpd/conf /path/to/new/conf"

or

su -c "/usr/bin/chcon -R --reference=/var/www/html /path/to/site/content"

Additional Information

Related Web Sites

Installed Documentation

  • /var/www/manual - requires httpd-manual rpm package


Cog.png
This page needs some love
This page should be revised or reconstructed to be more helpful. Problems may include being out of step with current team or project status or process.

NFS

Summary

Purpose: This document covers many of the aspects of configuring and customizing NFS.

Audience: This document is designed for anyone wanting to setup NFS as a File server.

Assumptions: The Fedora OS is installed, TCP/IP and DNS is configured. User accounts have been added and the reader has access to the root password. Firewall rules are configured to allow for the proper port access, and the user has a basic understanding of vi and bash commands.

Related Documents: The InstallGuide documents the basic install of Fedora. The GettingStarted documents the basic use of Fedora and gaining access to the CLI. The DNS assists with configuring DNS for name resolution. UserAccounts documents the steps for creating users and groups. The ConfiguringServices covers configuring Services. There is a good guide to NFS, valid both for Fedora 14 and Fedora 15 in the official documentation, but it's not for total newbies.

Lead Writer: MikeDittmeier

Introduction

The Network File System, or NFS, is a daemon that allows other computers to 'mount' a disk partition on another remote computer, and access the files the same as local files and folders. Other services and daemons such as automount can be used to mount remote NFS shares without user intervention.

Package Requirements

The default NFS in Fedora versions 14 to 21 (at least) is NFSv4 (NFS, version 4). This article makes use of the following packages found in the Fedora Repository:

  • nfs-utils The nfs-utils package provides a daemon for the kernel NFS server and related tools, which provides a much higher level of performance than the traditional Linux NFS server used by most users.
  • nfs-utils-libs Support libraries that are needed by the commands and daemons the nfs-utils rpm
  • system-config-nfs system-config-nfs is a graphical user interface for creating, modifying, and deleting NFS shares.

Installation

By default NFS is already included in most fedora installations. To verify NFS is installed, type the following command:

rpm -q nfs-utils

this should output something like:

nfs-utils-1.2.6-3.fc17.x86_64

If not, then install the NFS packages by typing:

su -c 'yum install -y nfs-utils system-config-nfs'

For graphical installs, use Main Menu > Add/Remove Software. This requires the root user password to run. In the Browse tab, click on the Base System group on the left, then select the Base option on the right. Click Apply to have the software and all dependencies installed. You can customize what is installed in the Base grouping by clicking on Optional packages.

Configuring NFS

There are three main configuration files you will need to edit to set up an NFS server: /etc/exports, /etc/hosts.allow, and /etc/hosts.deny. The only file used in this section of the chapter is /etc/exports to get NFS up and running.

  • /etc/exports, Main configuration file
  • /etc/hosts.allow, Hosts to allow access
  • /etc/hosts.deny, Hosts to deny access

NFS is not enabled by default on all Fedora spins. To see if NFS is activated on your system, type

ps -ef | grep nfs

If you don't see any processes named "[nfsd]" and "[nfsd4]" you'll need to activate NFS with these commands:

sudo systemctl enable rpcbind
sudo systemctl enable nfs-server
sudo service rpcbind start
sudo service nfs-server start

Creating Shares

By default NFS does not share out any folders or drive volumes. To create the first share, open a shell prompt, and enter the following command to begin editing the /etc/exports file:

su -c 'vim /etc/exports'

The vi editor window will open to what looks like a new file. This is because the /etc/exports file has no existing configuration settings at install. The format that will be used to share folders and drive volumes is straightforward:

directory hosts(options)

Here is a break down of the 2 lines listed:

  • directory, This is the directory or volume to be shared
  • hosts, This is a client computer that will have access to the share. The preferred way to list the host is by IP Address, but DNS names can be used. A group of hosts can be configured by entering an IP range such as:
/var/ftp/pub  192.168.1.0/255.255.255.0(ro)
/home/public  192.168.1.0/255.255.255.0(rw)
  • options - The options specify the kind of access mentioned hosts will have to the shared directory. Here are some of the most common options:
  • ro, read only access is granted to the Directory
  • rw, read and write access is granted to the Directory
  • no_root_squash, by default, access by a remote root users is treated as the user 'nobody'. To allow the same access to a remote 'root' account as the local root user, add this option.
Stop (medium size).png
Allowing remote root access through NFS is a major security risk. Avoid using this option unless necessary!
  • no_subtree_check, subtree checking verifies the a file being accessed is in a sub folder on the same volume. When sharing an entire drive volume, this option will speed up access to the sub-folders and files.
  • sync, By default NFS uses 'sync' transfers, so the NFS server must send an acknowledgment that the file has been written. Using the async option will speed up file transfers by disabling the acknowledgment.

To share the /var/ftp/pub folder with read only access, and with sync/no_subtree_check allowed, edit the /etc/exports file as below:

/var/ftp/pub	192.168.54.0/255.255.255.0(ro,sync,no_subtree_check)


For graphical configurations, in Fedora 15 to 17, use Activities → Applications → Other → NFS (in older versions: System Menu > Administration > Server Settings > NFS). This requires the root user password to run. Click the [Add] button. on the Basic tab Enter the directory to share or click the [Browse...] button and select the directory you want to share. Enter the host or hosts you want to have access to the share, separated by spaces.

Note.png
Using the * in the Hosts field makes the share accessible to everyone

Select the Basic Permisions by clicking the [Read-only] or [Read/Write] radio buttons.

On the General Options tab, select the [Disable subtree checking] and the [Sync write operations on request] radio buttons.

Click the [OK] button to save your changes.

In a shell prompt, enter the following command to edit the /etc/exports file and verify the changes just made:

su -c 'vim /etc/exports'

The following example should be displayed in the vi editor window:

/var/ftp/pub                   192.168.54.0/255.255.255.0(ro,sync,no_wdelay,no_subtree_check,nohide)

Exit the vi editor, and restart the NFS service to apply the changes by typing (Fedora 17):

su -c 'systemctl restart nfs-server.service'

No error message should appear.

Beware: if, as superuser ("root") you overwrite by hand the "exports" file (for instance copying a file you had saved before), or if you delete the old one and create a new one by hand, then it's probable than the SEL (Security enhanced Linux) labels of the file get wrong. In such a case (or if you suspect it's the case), you have to restore them like this:

su -c 'restorecon /etc/exports'

The same way, you should restore the SEL labels of any configuration file you have created or restored by hand, for example /etc/hosts.allow .

In older versions of Fedora (for instance Fedora 14), instead of using systemctl, you should, in order to restart NFS, type

su -c 'service nfs restart'

And the following should be returned:

Shutting down NFS mountd:                                  [  OK  ] 
Shutting down NFS daemon:                                  [  OK  ] 
Shutting down NFS quotas:                                  [  OK  ] 
Shutting down NFS services:                                [  OK  ] 
Starting NFS services:                                     [  OK  ] 
Starting NFS quotas:                                       [  OK  ] 
Starting NFS daemon:                                       [  OK  ] 
Starting NFS mountd:                                       [  OK  ] 

To add additional shares, just add an additional line in the /etc/exports file for each directory or volume that needs to be shared.

NFS Clients

There is little to do to connect a linux system to a remote NFS share. Open a shell prompt, and create the folder on which you want to mount the remote NFS share:

su -c 'mkdir /media/nfs'

Now, enter the following command to mount the remote NFS share:

Note.png
In this example, server is the nfs host
su -c 'mount server:/var/ftp/pub /media/nfs'

To verify the remote NFS share is mounted enter the following command at a shell prompt:

mount

The following line should be included in the output:

server:/var/ftp/pub on /media/nfs type nfs (rw,addr=192.168.1.10)

Now enter the following to get a directory listing of the NFS mounted directory:

ls /media/nfs

There is a distribution folder in the /var/ftp/pub folder for Fedora that is displayed:

f8

Mounting NFS Shares at boot time

To mount a NFS share permanently during system start up, edit the /etc/fstab file the same way as you would for a local file system. The file system type should be set to nfs. Specify the dump and fsck order (the last two entries), in our case set to zero for demonstration purposes. Our example /etc/fstab should look like below:

...
server:/var/ftp/pub  /media/nfs    nfs         rw           0    0

Using Automount

Another way to access remote NFS shares is to use autofs. The difference between using the autofs daemon and the /etc/fstab file is autofs will only mount the NFS share when a file or directory is requested on the NFS mount point. This will also speed up boot time by not waiting for a response from the remote NFS server.

There is a good explanation of automount, valid both for Fedora 14 and 15, in the official documentation but they just forgot to say you have to install the autofs package. To do this, in Fedora 15, go to Activities → Applications → System tools → "Add/remove software"; in the "Filters" tab, choose only "Only newest packages" and check you've the following filters: "Installed → No filter", "Development → Only end user files", "Graphical → No filter", and "Free → Only free software" (or "No filter"). Then in the "Find" field", type "autofs", click on "Find", check the package whose name begins by "autofs" (for instance "autofs-1:5.0.5-38-fc15 (x86_64)"), and eventually on "Apply". After the download and installation are complete, you can close the "Add/Remove software window".

You may also use the following command to install the autofs package:

su -c 'yum install autofs'

The master configuration for autofs is the /etc/auto.master file. Here is an example file:

#
#
/misc   /etc/auto.misc
/net    -hosts
#
#
#
+auto.master

The /misc mount is defined in a seperate file /etc/auto.misc. The /misc directory is reserver for autofs mounts. New NFS mounts should be added to the /etc/auto.misc file. Here is an example of the /etc/auto.misc file:

#

cd              -fstype=iso9660,ro,nosuid,nodev :/dev/cdrom

To add the NFS share to the /etc/auto.misc, add the following line:

nfs		-ro,soft,intr		server:/var/ftp/pub

Save the changes made to the /etc/auto.misc file and start the autofs deamon: in Fedora 15, go to Activities → Applications → Other → Services, choose "autofs" in the list, then on the "start" button. Alternatively, you can use the following command at a shell prompt:

su -c 'service autofs start'

but this won't start the autofs daemon automatically at boot. Test the changes just made by entering the following command at a shell prompt:

ls /misc/nfs

the result should be:

f8

At this Point NFS should be up and running, and client systems should have access to the designated directories and volumes on the NFS server. To enable the NFS service during system startup, enter the following command at a shell prompt:

su -c 'chkconfig --levels 345 nfs on'

This starts the nfs service on run levels 3, 4 and 5 during start up.a

Samba

Introduction

Samba is an open source implementation of the SMB (Server Message Block) protocol. Samba provides the means for resource sharing between networked computers that run different operating systems. As a client, Samba allows Linux/UNIX machines to access resources on Windows or Samba servers. As a server, Samba provides shared resources for Windows or other Samba clients. Historically, Samba provided access to shared resources through the SMBFS - SMB File System. More recently, SMBFS has been replaced by the more advanced CIFS (Common Internet File System), SMB compliant virtual file system. CIFS utilizes advanced network file system features such as locking, Unicode, hardlinks support and others. With CIFS, all network functions, including authentication, are provided in the kernel.

Fedora includes version 3.x of Samba. This version is capable of the following:

  • Acts as a Windows NT-style PDC (Primary Domain Controller)
  • Provides authentication for Windows domain logins
  • Acts as a BDC (Backup Domain Controller) for Samba PDC
  • Joins Windows NT, Windows 2000/2003 and Samba domain as a member server
  • Provides WINS (Windows Internet Name Service) name resolution with the nmb component
  • Enhances network browsing services
  • Joins Windows AD (Active Directory) domain by utilizing LDAP and Kerberos services
  • Acts as a Windows Workgroup server, providing directory trees, files and printers to Windows and Linux/UNIX clients
  • Contains built-in Unicode support for internationalization

Current development version (4.x) will address existing limitations of Samba, the most important being the ability of Samba to act as a Windows Active Directory PDC.

How Samba Works

Idea.png
A detailed explanation of low-level Samba services is beyond the scope of this document. The simplified definition is that Samba utilizes the NetBIOS API to deliver or respond to SMB/CIFS calls over the network, thus providing access to the network-shared directory tree, file and print resources. In addition, Samba extends NetBIOS and SMB/CIFS to provide authentication services and LDAP-type directory information.

Samba is composed of multiple applications each of which provide a part of Sambas functionality. Three daemons - smbd, nmbd, and winbindd are the main components of Samba. Some of the most commonly used command line Samba tools are smbstatus, smbpasswd, findsmb, nmblookup, net, smbclient, smbtar, and testparm.

Samba Daemons

smbd:: The smbd daemon is responsible for the management of all shared resources on the Samba server. It provides file, print and browse services for SMB/CIFS clients including authentication and resource locking.

nmbd:: The nmbd daemon is the naming service component. nmbd provides WINS functionality to Windows clients, browse lists in the Network Neighborhood and participates in browser elections on the network.

winbindd:: Together with nsswitch, the winbindd service provides access to user and group information stored on the Windows server and is capable of passing a Samba client's authentication requests to the Windows server.

Commonly Used Command Line Utilities

smbstatus:: Reports current connections to shares on a Samba server.

smbpasswd:: Used to set or modify passwords for Samba users.

findsmb:: Used to provide information about SMB/CIFS enabled computers on the network.

nmblookup:: Uses NetBIOS over TCP/IP to translate computer names to IP addresses.

net:: Used for remote administration of Samba servers.

smbclient:: Used by UNIX/Linux client computers to connect to Samba or Windows shared resources.

smbtar:: Utility used to backup data that resides on Samba shares.

testparm:: Utility used to check the syntax of the Samba configuration file (smb.conf).

Instaling Samba Server

The default Fedora installation does not include Samba server. To install Samba, run:

su -c "yum install samba"

and enter the root password when prompted. This command will install the two packages needed to run a Samba server:

  • samba-common
  • samba

The samba package installs the actual Samba server, while the samba-common package includes additional files needed by the Samba server and Samba client. There are two additional optional packages that can also be installed:

  • samba-client
  • system-config-samba

The samba-client package provides client-side Samba functionality to a Fedora machine. The package allows connectivity to remote Samba or Windows shares with the smbclient command line utility. The system-config-samba package provides a graphical interface to aid with Samba server configuration. This utility is capable of configuring a very limited set of Samba server options and is not covered in this document.

smb.conf

The main configuration file is /etc/samba/smb.conf. It includes a sensible set of configuration options which should be able to cover most, if not all, scenarios. The smb.conf file accepts two types of comments:

  • hash symbol (#) is usually used to denote actual comments
  • semicolon (;) is usually used to denote unused configuration options

Configuration options are in the format:

name = value

Lines that contain only whitespace are ignored.

smb.conf file is divided into sections. Each section begins with the section name in brackets and continues until the beginning of the next section. There are three special sections:

[global] section:: Contains configuration parameters for the entire Samba server. [homes] section:: When defined in the configuration file, this section allows clients to quickly access their home directories. [printers] section:: When defined allows users to connect to printers specified in the Samba server's local printcap file.

Samba Configuration

Samba configuration can be customized based on network requirements. This section provides some sample configurations for various Samba implementations, including:

  • Standalone workgroup server
  • Domain member server (Windows NT-style)
  • Primary Domain Controller (Windows NT-style)
  • Domain member server in the Windows AD domain

Samba Security Modes

A good understanding of how Samba implements security is essential for proper deployment of a Samba server. Windows NT/2000/2003 SMB (CIFS) only implements two security levels, user-level and share-level security, Samba provides more flexibility by extending Windows-based SMB/CIFS security through its Security Modes. Samba security modes are configured through the smb.conf parameter:

security = <mode>

The available modes are:

share:: In this mode, client must authenticate against each share. In a Windows world, the share password is set on the share itself. This means that client does not have to pass the username along with the connection request. Samba always uses the username/password combination, provided through the underlying Linux authentication method - /etc/passwd or /etc/nsswitch.conf. For this mode the smb.conf entry is:

security = share

user:: This is Samba's default security mode. In this mode, authentication is based on the username/password combination. When a client makes a request for a shared resource, the Samba server doesn't "know" which share an authenticating client is allowed to access. For this mode the smb.conf entry is:

security = user

server:: Although still valid, the server security mode is a "legacy" mode, a leftover from times when the Samba software was not able to become a domain member server. This mode allows a Samba server to authenticate connecting clients against the Windows NT-style PDC. There are many shortcomings, the possibility of "account lockout" on the Windows PDC, no assurance that the PDC is the actual machine specified, no support for winbindd/remote user profiles, etc. In this mode, Samba appears to be in a user security mode to the clients, while actually passing all the authentication to the PDC. For server security mode to work, two additional parameters must be specified in an smb.conf file:

encrypt passwords = yes
security = server
password server = PDC-NetBIOS-name

domain:: Domain security mode is the mechanism that provides a central database for all user, group and machine account information. This database is stored on the machines that participate in a domain as Domain Controllers. The PDC is responsible for maintaining the integrity of the database and sending regular updates to servers that act as Backup Domain Controllers. The BDC is used for performing account authentication, thus offloading a significant amount of work from the Primary Domain Controller. This is very important for redundancy of large environments, particularly those where a single domain spreads across different physical locations. Having a BDC allows for uninterrupted logins even if the network link to PDC is "down". Samba participates in a domain security mode by virtue of a machine trust account stored in a domain accounts database. This allows a Samba server configured as a BDC to authenticate clients or pass the authentication to the Domain Controller if it is configured as a Domain Member Server. Samba servers must join a Windows based domain before it can be configured for domain security mode. To configure Samba for Domain security mode:

To /etc/samba/smb.conf add:

security = domain
workgroup = <Domain-Name>

On a Windows PDC, use Server Manager to add the Samba server's machine account to the domain database. On the Samba server run:

net rpc join -U administrator%password

It is not necessary to specify the actual domain name using the previous command - this information is retrieved from a smb.conf file. ADS:: ADS security mode dictates that Samba server must join Windows Active Directory domain. To join ADS domain, create Samba server's account in a ADS:

net ads join -U Administrator

Samba is able to join AD domain as an either NT-style AD domain member using NT style security (if AD is running in a native mode) or as a native AD domain member, which requires Kerberos based authentication services. The latter may be required for domains where security policy prohibits RPC based authentication (NT-style). smb.conf entry is:

security = ADS
realm = <some.kerberos.realm>
encrypt passwords = yes

Samba is sometimes not able to identify the authentication server from its Kerberos realm name. This often happens on networks with Linux/UNIX style DNS servers if they are not configured to handle the non-standard DNS requirements of the Windows AD DNS implementation. In this case, add the following parameter to the smb.conf:

password server = <kerberos.server.name>

Important Notes For Systems With SELinux Enabled

To achieve proper operation of Samba on SELinux enabled systems follow these few rules:

  • If you create a directory that you want to share, label it with the samba_share_t context:
chcon -R -t samba_share_t /home/newdir
Warning.png
Do not change the SELinux context of system directories!
System directories will have different SELinux labels and relabeling them with samba context can severely damage system security and possibly render the system unusable.

To check what context a system directory has, use:

ls -lZd /path-to-systemdir
  • To share a system directory, use one of the following:
setsebool -P samba_export_all_ro on

... to provide read-only shares or ...

setsebool -P samba_export_all_rw on

... to provide read-write access to shares.

  • SELinux disables by default sharing home directories. To enable sharing of home directories, run:
setsebool -P samba_enable_home_dirs on
  • To enable the correct operation of Fedora user account command line utilities such as useradd, which allows Samba to run as a domain controller, run:
setsebool -P samba_domain_controller on

Security Considerations

There are several ways to address the security of a Samba server:

  • Interface protection
  • Host based protection
  • User based protection
  • Firewall protection
Interface Protection

Add the following parameters to the smb.conf to define which interfaces the Samba services listen on:

interfaces = eth0 lo
bind interfaces only = yes

In the example above, Samba will only listen on the loopback interface and the first Ethernet NIC and ignores all other network interfaces that might be present on the system.

Host Based Protection

Samba by default, accepts connections from all hosts. To restrict access to a Samba server from only the desired hosts or subnets, configure the following paarmeters:

hosts allow = 127.0.0.1 192.168.1.0/24
hosts deny = 0.0.0.0/0

This will allow access to the Samba server only to localhost and hosts on the 192.168.1. subnet.

User Based Protection

To restrict user access to Samba shares globally, use the following parameter in the [global] section of the smb.conf file:

valid users = user1, otheruser, @smballowed

The above configuration allows access to a Samba server to users user1, otheruser, and users who are members of the smballowed user group.

Firewall Protection

A good practice for securing a Samba server is to use firewall protection combined with Samba-specific protection as described in the previous section. To configure iptables firewall access to a Samba server from the 192.168.1.0/24 subnet, add the following rules:

iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 137 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 138 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 139 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 445 -j ACCEPT

Samba communicates through:

  • 137/UDP port - used by nmbd for NetBIOS name resolution
  • 138/UDP port - used by nmbd for NetBIOS network browsing
  • 139/TCP port - used by smbd for NetBIOS session service
  • 445/TCP port - used by smbd for Microsoft Active Directory services

Inbound traffic on high-order ports [1024:65535] should be denied except for established connections.

Samba And CUPS (Common Unix Printing System)

For detailed CUPS printing instructions, see Using the Common UNIX Printing System . This section covers some capabilities of the CUPS printing system related to Samba.

Basic Features

Samba is pre-compiled with support for CUPS printing. This integration simplifies print serving to SMB/CIFS clients. In a simple scenario, Samba presents CUPS printer queues to the SMB/CIFS clients and passes received print jobs directly to the CUPS for printing. This scenario assumes the SMB/CIFS clients have the appropriate printer drivers installed and are capable of producing print jobs in a format that the printer device understands. In this scenario, the [global] section of the smb.conf file requires only two parameters:

printing = cups
printcap = cups

Printer devices are configured in the [printers] section. For small environments with few printer devices that do not have any specific printing requirements the default [printers] section be sufficients. Samba and CUPS provide a lot of flexibility and each individual printer can be configured through its own [printer] which overrides settings in the [global] . One common example is the need to allow only a set of users or user groups in the organization to print to a device:

[global] 
printing = cups
printcap = cups

[printers] 
comment = all printers
path = /var/spool/samba
printable = yes
guest ok = yes
use client driver = yes

[restricted_printer] 
comment = color laser
path = /var/spool/samba
browseable = no
printable = yes
guest ok = no
valid users = @marketing, boss
use client driver = yes

In the above example, only the user boss and members of the marketing group are allowed to print to the color laser printer.

Advanced Features

Integration of Samba and CUPS printing allows for advanced configurations that provide robust printing solutions, suitable for enterprise environments. For detailed guides and tutorials about the advanced features, refer to the Additional Information section at the bottom of the page.

Samba Linux Client Utilities

To view the list of SMB/CIFS shares on a particular host, run:

smbclient -L <hostname>

To connect to the Samba share on a particular host, run:

smbclient //<hostname>/<sharename>

...and enter the Samba password when prompted. To connect to the Samba share as a different user, specify the user name as an argument to the -U command option:

smbclient -U <userX> //<hostname>/<sharename>

...and enter userX's samba password when prompted. To mount the Samba share on the local directory, as root run:

mount -t cifs //<hostname>/<sharename> /<localdir> -o user=userX

...and enter userX's samba password when prompted. If mounting Samba share in this fashion, userX will likely encounter various issues with file permissions on the mounted /<localdir>. To avoid these issues, pass the additional options to the mount command:

mount -t cifs //<hostname>/<sharename> /<localdir> -o user=userX,uid=<UID>,file_mode=0644

...where <UID> is a numerical user ID of the userX's local account on the client machine. It is also possible to pass the userX's Samba password as an option to the mount command:

mount -t cifs //<hostname>/<sharename> /<localdir> -o user=userX,password=<password>,uid=<UID>,file_mode=0644

...and avoid the password prompt on every mount attempt. However, this is not recommended, since the actual password might be visible to the others. The recommended way is to use the credentials option:

mount -t cifs //<hostname>/<sharename> /<localdir> -o credentials=<path_to_the_credentials_file>,uid=<UID>,file_mode=0644

The credentials file is an ASCII text file of the format:

username=<samba-user>
password=<samba-password>
Idea.png
The good practice is to create the credentials file with file permissions set to read-only for user root and not accessible to anybody else.

The root is the only user with a permission to run the mount utility. To enable non-privileged users to mount and unmount Samba shares, set SUID on /sbin/mount.cifs and /sbin/umount.cifs. As root, run:

chmod u+s /sbin/mount.cifs /sbin/umount.cifs

Once set, user can use mount.cifs to mount Samba shares:

/sbin/mount.cifs //<hostname>/<sharename> /<localdir> -o credentials=<path_to_the_credentials_file>,uid=<UID>,file_mode=0644

...or umount.cifs to unmount the share:

/sbin/umount.cifs /<localdir>

To mount Samba shares at boot time, edit the /etc/fstab file and add the line:

//<hostname>/<sharename> /<localdir> cifs <option1>,<option2>,...,<optionX> 0 0
Idea.png
The entry in the /etc/fstab file accepts the same set of options as the mount command.

Common Scenarios - Sample Configuration Files

Idea.png
Computer, workgroup, and share names, specified directory paths, user and group names and IP network addresses in the following configuration files are entirely arbitrary.

Read-only shared directory

Requirement: Allow all users to view company's policies on Internet and Email usage, without the ability to alter files.

Solution:

  1. Create directory /home/common/policies
  2. Copy all related documents to /home/common/policies
  3. Create [policies] section in smb.conf that allows anonymous access

Use the following smb.conf to achieve this:

[global] 
workgroup = BIGBROTHER
security = share

[policies] 
path = /home/common/policies
read only = yes
guest ok = yes

Small Office Network

Environment: Translation services office with three client PCs (Windows XP) networked in an OFFICESPACE workgroup. MS Word documents and MS Excel spreadsheets are shared from each PC. Network-capable laser printer that accepts direct printing from workstations.

Requirements: Provide central storage for documents, writable for all users and centrally managed raw print queue, with print drivers locally installed on each workstation.

Solution:

1. Install Fedora and Samba server on a new server 1. Create group officespace on the server:

groupadd officespace

1.#3 Create user milton on the server:

useradd milton
passwd milton
Changing password for user milton.
New UNIX password: ********
Retype new UNIX password: ********
passwd: all authentication tokens updated successfully.

1.#4 Create directory structure that will contain documentation and be shared via Samba:

mkdir -p /data/documents/{translations,spreadsheets}
chown -R milton.officespace /data/documents
chmod -R ug+rwxs,o+rx,o-w /datadocuments

1.#5 Create accounts for three users in the office and add all of them to officespace group.

Idea.png
Steps 2-5 above ensure that directory structure /data/documents has SUID and SGID set on it and that all new files created under it will inherit the set ownership and permissions. This allows all users in the office to alter the content of the files, thus not interfering with the file access permissions.

1.#6 Create CUPS print queue on the server:

lpadmin -p prn1 -v socket://192.168.1.11:9100 -E

...and enable CUPS queue for raw printing by uncommenting the line:

#application/octet-stream     application/vnd.cups-raw      0     -

...in a /etc/cups/mime.convs file and uncommenting the line:

#application/octet-stream

...in a /etc/cups/mime.types file.

Idea.png
CUPS print queue may not be fully enabled when created.
It is sometimes necessary to force this by issuing the following commands: cupsenable <print_queue> and cupsaccept <print_queue>

1.#7 Create the following /etc/smb.conf file:

[global] 
workgroup = OFFICESPACE
netbios name = Stapler
server string = Office Samba Server
security = share
load printers = yes
printing = CUPS
printcap name = CUPS

[documents] 
comment = Office Documentation
path = /data/documents
read only = no
force user = milton
force group = officespace

[printers] 
comment = Laser Print Spool
path = /var/spool/samba
printable = yes
guest ok = yes
use client driver = yes

1.#8 Enable Samba and print daemons at boot time:

chkconfig smb on
chkconfig cups on

...and start both services:

service smb start
service cups start
Idea.png
Always use the testparm utility to test syntax/validity of the Samba configuration file, before starting the service!

1.#9 Reconfigure workstations to become members of the OFFICESPACE workgroup and to use Samba-shared printer.

NT-style Domain

Environment: Corporate headquarters, with 50 users, 60 Windows XP and Fedora client computers, used in Sales and Marketing, Finance, Information Services and Management departments. Several HP Laser Jet printers and a color laser printer. Subnet address is 192.168.1.0/24. IP addresses 192.168.1.2 - 192.168.1.10 are reserved for various servers, .10 for Samba server. IP addresses 192.168.1.11-192.168.1.20 are reserved for network printers. DHCP server assigns host address from the address pool 192.168.1.101 - 192.168.1.200 to client computers.

Requirements:

  • NT Domain-like logon services, using encrypted passwords
  • Each department has own file storage area, writable only by users from that department and accessible read-only by Management
  • Each user has own home drive, accessible only by user and not visible by anybody else
  • Common file storage area, writable for all users
  • Server-based user profiles for Windows users, providing the ability to use any Windows PC on the network, while retaining access to their own settings and data
  • Dedicated printers for Management and Finance, not accessible to other departments
  • Dedicated color printer for Marketing

Solution: 1. Install Fedora and Samba server on a dedicated server computer 1. Configure network interface eth0 with the IP address 192.168.1.10/24 1. Configure iptables firewall to deny access to all services, except for ports 137, 138 (UDP) and 139, 445 (TCP) 1. Create the following directories for Samba shares:

mkdir /home/{management,finance,technical,sales,general}

...and the directory for storing user profiles:

mkdir -p /home/samba/profiles

1.#5 Create user groups: management, sales, finance, technical, general:

for i in management sales finance technical general
do groupadd $i
done

...and corresponding user accounts, needed for simplified management of file permissions on shared directories:

for i in management sales finance technical general
do useradd -g $i $i
done

1.#6 Create Linux accounts for users, so that a user's primary group is the user's department group and a secondary group is general. Windows users do not need a shell environment on a Samba server while IS team members all use Fedora clients and often require access to the Samba server through terminal based SSH sessions, thus need full a shell environment on the server. Examples:

useradd -g finance -G general -d /home/users/payroll_guy -s /bin/false payroll_guy
useradd -g technical -G general -d /home/users/stickster -s /bin/bash stickster

1.#7 Set Linux passwords for each user:

passwd <username>
Idea.png
Having a Linux password is a prerequisite to creating Samba passwords for users, using the smbpasswd utility.
If a user's Linux password does not exist, the smbpasswd -a <username> command is ignored and the Samba password is not set.

1.#8 Set the appropriate file and directory permissions on shared directories:

chown -R finance.finance /home/finance
chmod -R ug+rwxs,o+rx,o-w /home/finance
chown -R management.management /home/management
chmod -R ug+rwxs,o-rwx /home/management
chown -R sales.sales /home/sales
chmod -R ug+rwxs,o+rx,o-w /home/sales
chown -R technical.technical /home/technical
chmod -R ug+rwxs,o+rx,o-w /home/technical
chown -R general.general /home/general
chmod -R ug+rwxs,o+rx,o-w /home/general
chmod o+rwt /home/samba/profiles
Idea.png
/home/samba/profiles directory must be world-writable for "on-the-fly" creation of the individual profile directories.
The "Sticky bit" t on this directory prevents users with write permission on the directory to rename or delete files or directories contained within this directory if the user is not the file or directory owner.

1.#8 Create appropriate CUPS print queues:

lpadmin -p prn1 -v socket://192.168.1.11:9100 -E
lpadmin -p prn2 -v socket://192.168.1.12:9100 -E
lpadmin -p prn3 -v socket://192.168.1.13:9100 -E
lpadmin -p prn4 -v socket://192.168.1.14:9100 -E

for i in prn{1,2,3,4}
do cupsenable $i
done

for i in prn{1,2,3,4}
do cupsaccept $i
done

1.#9 Configure SELinux to allow Samba shares. Allow sharing of previously created directories:

for dir in management finance technical sales general; do chcon -R -t samba_share_t /home/$dir; done

Enable sharing of home directories:

setsebool -P samba_enable_home_dirs on

Enable Samba Domain operations:

setsebool -P samba_domain_controller on

1.#10 Move default smb.conf file and use it as a help reference:

mv /etc/samba/smb.conf /etc/samba/smb.conf.orig

1.#11 Create new /etc/samba/smb.conf file:

[global] 

workgroup = CORPHQ
netbios name = WEREWOLF
server string = Corporate Samba Domain Controller

admin users = root, stickster

hosts allow = 127.0.0.1 192.168.1.0/24

printing = cups
printcap name = cups
load printers = yes


log file = /var/log/samba/%m.log


max log size = 50


socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192


security = user
passdb backend = tdbsam
domain logons = yes
domain master = yes



logon path = \\%L\Profiles\%U


logon drive = H:

add user script = /usr/sbin/useradd -d /dev/null -g 100 -s /bin/false -M %u

name resolve order = wins lmhosts bcast

wins support = yes

wins proxy = no

hide dot files = yes

[homes] 
comment = Home Directories
browseable = no
writable = yes

[Profiles] 
path = /home/samba/profiles
read only = No
create mask = 0700
directory mask = 0700

[printers] 
comment = All Printers
path = /var/spool/samba
browseable = no
guest ok = no
printable = yes
use client driver = yes

[management] 
comment = Managment Share
browseable = yes
writable = yes
path = /home/management
valid users = @management
force user = management
force group = management
create mask = 0770
directory mask = 0770

[finance] 
comment = Finance Share
browseable = yes
writable = yes
path = /home/finance
valid users = @finance
read list = @management
force user = finance
force group = finance
create mask = 0770
directory mask = 0770

[general] 
comment = General Share
browseable = yes
writable = yes
path = /home/groups/general
valid users = @general
read list = @management
force user = general
force group = general
create mask = 0770
directory mask = 0770

[technical] 
comment = Technical Share
browseable = yes
writable = yes
path = /home/groups/technical
valid users = @technical
read list = @management
write list = @technical
force user = technical
force group = technical
create mask = 0775
directory mask = 0775

[Sales] 
comment = Sales And Marketing Share
browseable = yes
writable = yes
path = /home/groups/sales
valid users = @sales
read list = @management
force user = sales
force group = sales
create mask = 0770
directory mask = 0770

[prn1] 
comment = Management Department Printer
path = /var/spool/samba
browseable = no
printable = yes
guest ok = no
valid users = @management
use client driver = yes

[prn2] 
comment = Finance Department Printer
path = /var/spool/samba
browseable = no
printable = yes
guest ok = no
valid users = @finance
use client driver = yes

[prn3] 
comment = Sales Department Printer
path = /var/spool/samba
browseable = no
printable = yes
guest ok = no
valid users = @sales
use client driver = yes

1.#12 Create Samba accounts for all users:

smbpasswd -a <username>

Enter the user's password when prompted.

1.#13 Enable the Samba and print daemons at boot time:

chkconfig smb on
chkconfig cups on

...and start both services:

service smb start
service cups start

Additional Information

Detailed Samba documentation, tutorials and FAQs are located at:

Related Web Sites

Related Manuals

Find more about specific Samba daemons and client-side utilities from the man pages included with Samba installation:

  • smbd(8)
  • nmbd(8)
  • winbindd(8)
  • samba_selinux(8)
  • smb.conf(5)
  • smbclient(1)
  • smbstatus(1)
  • smbpasswd(8)
  • findsmb(1)
  • nmblookup(1)
  • net(8)
  • smbtar(1)
  • testparm(1)

Further Reading

For aspiring and accomplished Samba administrators, some essential reading is: Using Samba 2nd edition . It covers Samba releases 2.2.x and 3.0.x.

Warning.png
Administering Samba in a large environment would most likely include fair amount of Windows administration, too!


Managing Network Time Server

What is NTP

The Network Time Protocol (NTP) allows the computer to synchronize the clock to that of an external authoritative time source and provide the accurate time to clients on the local network. Fedora provides this functionality through the ntpd server. The ntpd daemon and associated utilities are provided by the ntp rpm package.

Installing NTP server

To install the Network Time Protocol Server, run:

su -c '/usr/bin/yum install ntp'

Configuring the NTP server

The configuration of the NTP server is managed through:

/etc/sysconfig/ntp:: Configuration file for the ntpd daemon start-up options. /etc/ntp.conf:: The main configuration file for the server and client. /etc/ntp/:: Contains the remaining files necessary to set the server up.

Before configuring the NTP server and starting the ntpd daemon, it is important to perform initial time synchronization of the system clock. The reason is that the ntpd daemon will not perform the initial synchronization at start up time if the system clock deviates from the real, accurate time too much.

To synchronize the system time to that of the public ntp server pool, run:

su -c '/usr/sbin/ntpdate -b pool.ntp.org'

Admonition("Note","pool.ntp.org is the project that manages a cluster of publicly available time servers across the world. Its clever DNS round-robin setup greatly reduces the load on individual time servers and aids in reducing the bandwidth cost for the operators and users by utilizing pgeodns data. It is likely that the response to the ntpdate command above will come from the geographically close time server.")

Access Controls

The NTP server provides a resource to the remote systems and clients, which implies enforcing of certain security measures. Access control parameters are adjustable and defined in the /etc/ntp.conf file using the following format:

restrict <ipaddress or FQDN> <netmask> parameter

The most commonly used parameters are:

ignore:: Deny all packets and queries kod:: Send Kiss-Of-Death packet on access violation nomodify:: Deny ntpq / ntpdc queries that attempt to modify the server notrap:: Deny control message trap service noquery:: Deny all ntpq / ntpdc queries noserve:: Deny all queries - except ntpq / ntpdc notrust:: Deny access unless cryptographically authenticated nopeer:: Deny all packets that attempt to establish a peer association

Admonition("Tip","Omit all parameters to grant the full access to NTP server.")

/etc/ntp.conf

To allow full control to the localhost, add the following entry:

restrict 127.0.0.1

The default configuration file has the pool of time servers listed:

server 0.fedora.pool.ntp.org dynamic
server 1.fedora.pool.ntp.org dynamic
server 2.fedora.pool.ntp.org dynamic

Admonition("Note","The listed servers are used in this guide. Consider changing the default entries to public servers that are available in your country or region to ensure faster response and help better network load handling.")

Restrict the listed servers from querying or modifying the local NTP server:

restrict 0.fedora.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery
restrict 1.fedora.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery
restrict 2.fedora.pool.ntp.org mask 255.255.255.255 nomodify notrap noquery

Allow clients from the internal subnet to query the server (adjust the subnet address, if needed):

restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

Complete the configuration file with the following entries:

server          127.127.1.0     # local clock
fudge           127.127.1.0 stratum 10
driftfile       /var/lib/ntp/drift
broadcastdelay  0.008
keys            /etc/ntp/keys

The entries above provide the following:

server:: Specifies that a server is running on the host (own local clock) fudge:: Passes additional information to the clock driver stratum 10:: Manually sets the Stratum the server should operate at (1-15) driftfile:: Specifies the location of the file that holds calculated clock frequency offset broadcastdelay:: Sets the propagation delay from the server when broadcasting keys:: Store a list of keys needed for any cryptographic links

Admonition("Note","Stratum levels define the distance from the reference clock in the NTP hierarchy. Stratum 0 are reference clocks assumed to operate with very little or "zero-delay" and synchronize their clock to UTC over GPS, long wave radio, or similar links. They cannot be used on the network and are attached to Stratum 1 servers directly, for example through RS-232 serial port. Stratum 1 servers provide time synchronization over network links to Stratum 2 servers and so on, to Stratum 15. The higher the Stratum level is, the less accurate is the time source, estimated to be in a range of 10 - 100 ms per Startum level.")

Admonition("Tip","When determining the stratum of your server, firstly consider who you are providing time to? If you are only using the system for yourself and passing it on to a few workstations, then your stratum can be safely left at 10. If you are using the system for a large scale network, then plan your time servers and strata effectively.")

To start the NTP server, run:

su -c '/sbin/service ntpd start'

To enable the NTP server at boot time, run:

su -c '/sbin/chkconfig ntpd on'

By default, the ntpd daemon logs messages to the system log - /var/log/messages. The alternate log file may be specified in the /etc/ntp.conf:

logfile /var/log/ntpd.log

...and must be writable by ntp user.

To test the proper operation of the NTP server, run:

/usr/sbin/ntpq -pn

The initial output of the command is similar to:

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
66.118.163.120  .INIT.          16 u    -   64    0    0.000    0.000   0.000
202.135.38.18   .INIT.          16 u    -   64    0    0.000    0.000   0.000
208.113.193.10  .INIT.          16 u    -   64    0    0.000    0.000   0.000
127.127.1.0     .LOCL.          10 l    -   64    1    0.000    0.000   0.001

Running the same command again after a few seconds should produce the output similar to:

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
66.118.163.120  198.82.1.202     3 u   20   64    1  208.157   14.189   0.001
202.135.38.18   131.203.16.6     2 u   20   64    1   22.891   13.406   0.001
208.113.193.10  132.239.1.6      2 u   20   64    1  145.721    8.078   0.001
127.127.1.0     .LOCL.          10 l   20   64    1    0.000    0.000   0.001

The above output shows a properly synchronised time server drawing from NTP pool allocated sources. Notice that the local server is running at a stratum of 10.

Admonition("Tip","The clients on the local network will not be able to use the service until the .LOCL. time is stable. This may take up to 15 minutes upon the start of the ntpd daemon.")

Additional Information

Related Website

Installed Documentation

  • /usr/share/doc/ntp-*/index.html Installed Documentation

Related Manuals

  • man 8 ntpd
  • man 5 ntp.conf
  • man 5 ntp_acc
  • man 5 ntp_auth
  • man 5 ntp_mon
  • man 5 ntp_clock
  • man 5 ntp_misc

Managing Netfilter (IP Tables) Firewall

A firewall is a networking device which is used to separate private networks from external access by providing a level of security rules and controls.

A simple firewall can be configured to block all access to networks, workstations and communication ports. A more complex firewall is capable of inspecting each individual packet that attempts to pass through it and ensures that they are correctly formatted and appropriate to the services provided for (or by) the internal network. This type of firewall is called a packet filtering firewall.

This chapter explains some of the concepts for Netfilter or iptables, firewall implementation provided by Fedora and packet forwarding which can be used to secure a private network. The example configurations provided in each section are only designed to provide an introduction into each of those specific sections, while the included example firewall script provides a simple but effective security for a networked system.

iptables is not a daemon. Upon the service start, all the firewall rules are loaded into memory and there is no "listening daemon". By default, rules are not persistent across reboot. However, iptables start-up can be managed as any other SysV init script, using /sbin/ckconfig and /sbin/service commands.

iptables rules are created using /sbin/iptables command. Once the rules are entered, use:

su -c '/sbin/service iptables save'

This creates the /etc/sysconfig/iptables file, which preserves the rules across reboot. Any additional rules are created and added to the file in a same way.

[Admonition("Tip","Effective firewall configuration can also be created using graphical interface system-config-firewall. This application is quite capable of creating simple firewall in a very convenient way. However, to configure more advanced options using this utility, familiarity with the iptables rules syntax is necessary.")]

Packet Forwarding

Packet forwarding is a simple concept where the server allows data packets to pass from one network to another. As per diagram below, packets from the private network are allowed to be forwarded through the server and out to the ISP and vice versa.

/-----------------------\
/-----------------\      |   Server (Routing)    |      /-----------------\
| Private Network |------|  eth1 : 192.168.1.1   |      | ISP Connection  |
| 192.168.1.0/24  |      |-----------------------|      | REMOTE IP ADDR  |
\-----------------/      | eth0 : 123.123.123.2  |------| 123.123.123.1   |
\-----------------------/      \-----------------/

There are a few initial considerations. First, the server must have networks or gateways defined in its routing table so it can make an informed decision where the packet needs to be passed to. Second, the server must have packet forwarding enabled. Thirdly, if the routed packets came from a private, non-routable subnet, they must be translated into globally routed IP addresses, before they will be accepted on the Internet.

To enable packet forwarding manually, run:

su -c '/bin/echo 1 > /proc/sys/net/ipv4/ip_forward'

This change takes the effect immediately but is not preserved on reboot. However, reboot is not required to disable IP forwrding - it can be done in a similar way:

su -c '/bin/echo 0 > /proc/sys/net/ipv4/ip_forward'

To enable IP forwarding permantly, change the parameter in /etc/sysctl.conf file to:

net.ipv4.ip_forward = 1

Packet Filtering

Packet filtering is usually confusing concept for users new to system administration.

In packet forwarding the kernel is either allowed to move packets between different subnets or is not, and if it is, the decisions are made from the kernel's routing table.

In packet filtering, the application iptables stores a list of pre-programmed rules which are individually tested against every packet that either tries to enter, pass through, or exit any of the system's network devices. Each rule is used to test the packet in a sequential order and if the packet matches any of the rules it is either accepted or rejected depending on the global policy and rule definitions.

The iptables firewall stores the rulesets in a group of three tables. Each provide different capabilities depending on the rules and the order they are applied. We will only examine the filter and nat tables here, the mangle table is used for specialised packet alteration which is beyond our scope. The following table displays the filter table and the three built-in chains.

Table Name Chain Name Chane Description
3> filter INPUT Any packet coming into the system
FORWARD Any packet that is being routed through the system
OUTPUT Any packet that is leaving the system

To list the filter table and its rules, first stop the iptables service:

su -c '/sbin/service iptables stop'

and then use the following command:

su -c '/sbin/iptables -t filter -nvL'

Admonition("Tip","The filter table is the default table when working with iptables, so the command option -t filter is not necessary but is a good practice.")

The output will look similar to:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

The listing shows the three built in chains, and their default policies are all set to ACCEPT, which means the firewall is inactive.

To populate the table with the set of rules, enter the following commands at the terminal line by line and press Enter after each line:

01- su -c '/sbin/iptables -P INPUT DROP'
02- su -c '/sbin/iptables -P FORWARD DROP'
03- su -c '/sbin/iptables -P OUTPUT DROP'
04- su -c '/sbin/iptables -A INPUT  -i lo -j ACCEPT'
05- su -c '/sbin/iptables -A OUTPUT -o lo -j ACCEPT'
06- su -c '/sbin/iptables -A INPUT  -i ppp0 -p tcp --sport 80 -j ACCEPT'
07- su -c '/sbin/iptables -A OUTPUT -o ppp0 -p tcp --dport 80 -j ACCEPT'
08- su -c '/sbin/iptables -A INPUT  -i eth1 -s 192.168.1.0/24 -p tcp --dport 3128 -j ACCEPT'
09- su -c '/sbin/iptables -A OUTPUT -o eth1 -d 192.168.1.0/24 -p tcp --sport 3128 -j ACCEPT'

Admonition("Note","Do not type the numbers at the beginning of each line. Start the actual command with su - numbers are shown here to explain the process more clearly.")

List the rules again:

su -c '/sbin/iptables -t filter -nvL'

The output is now:

01-	Chain INPUT (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
04-    0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
06-    0     0 ACCEPT     tcp  --  ppp0   *       0.0.0.0/0            0.0.0.0/0           tcp spt:80
08-    0     0 ACCEPT     tcp  --  eth1   *       192.168.1.0/24       0.0.0.0/0           tcp dpt:3128

02- Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

03- Chain OUTPUT (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
05-    0     0 ACCEPT     all  --  *      lo      0.0.0.0/0            0.0.0.0/0
07-    0     0 ACCEPT     tcp  --  *      ppp0    0.0.0.0/0            0.0.0.0/0           tcp dpt:80
09-    0     0 ACCEPT     tcp  --  *      eth1    0.0.0.0/0            192.168.1.0/24      tcp spt:3128

Each command above corresponds to the line in the output preceded with the same number and the rules are set according to the following:

Lines 01-03:: The first three commands set the default (-P) policy on all the chains to DROP everything, unless suitable rules inside the chain will ACCEPT them. This is the most secure method of filtering, because every packet now must have a specific rule written for it to be accepted by firewall and passed on.

Lines 04-05:: These two commands have (-A) appended to two ACCEPT rules. The OUTPUT rule (05) allows any packet to (-o) leave via the loopback device and the INPUT rule (04) allows packets to re-enter (-i) via the loopback interface.

Because the chains are using a default DROP policy, they restrict the server from accessing any of its own services running on the local host, such as DNS. A basic rule like this allows the server to access all services on the loopback interface without restriction.

Lines 06-07:: The next two (-A) appended rules are more specific. The OUTPUT rule (07) specifies that any packet going out (-o) through ppp0 interface using (-p) protocol TCP is accepted if the destination port is 80. The INPUT rule (06) specifies that any packet coming through the (-i) interface ppp0 using (-p) protocol TCP is accepted if the source port is 80.

In other words, local server is allowed to access external web servers through ppp0 connection.

Lines 08-09:: The last INPUT rule (08) which has been (-A) appended to the chain allows any TCP packets from the (-s) source network of 192.168.1.0/24, coming through the (-i) interface eth1 and are going to the (--dport) destination port 3128. The matching OUTPUT rule (09) has been (-A) appended to the chain allows any packets that are going out (-o) through the eth1 interface to (-d) destination network 192.168.1.0/24 using the TCP (-p) protocol, if the (--sport) source port is 3128.

These two are fairly detailed rules, they say that anyone on the internal network (192.168.1.0/24) is allowed to send packets to the squid proxy server (3128) through the internal eth1 interface and the results can be returned to the workstation.

Admonition("Tip","If using a strict DROP policy as above, it is important to note that you may need two rules that complement each other in order for packets to flow out and back in again.")

Source Network Address Translation

Source Network Address Translation (SNAT) provides the ability to change the source or destination IP address of data packets on-the-fly, so that the packet appears as coming from or going to a different address than the original. This feature also works with port numbers.

There are many reasons to use SNAT:

  • It allows packets from a private (RFC1918) network to be globally routed on the Internet and vice versa.
  • It allows inbound traffic to be sent to different internal hosts (bastions) depending on the resources requested.
  • It does not disclose any security details of the internal private network.

The iptables firewall provides support for SNAT and has a built-in nat table for that purpose. The following table displays the nat tables and the three built-in chains associated with it:

Table Name Chain Name Chane Description
3> nat PREROUTING Altering incoming packets before they are passed to INPUT filter
POSTROUTING Altering outgoing packets after they are passed by OUTPUT filter
OUTPUT Altering outgoing packets before they are passed to routing table

As the naming suggests, the PREROUTING and POSTROUTING chains are applied before or after any kernel routing decisions are made, so the packets can then be routed to match any new changes which have been made to the destination or source addresses.

The following example explains how nat and filter tables work together. To populate the table with the set of rules, enter the following commands at the terminal line by line and press Enter after each line:

01- su -c '/sbin/iptables -P INPUT ACCEPT'
02- su -c '/sbin/iptables -P FORWARD DROP'
03- su -c '/sbin/iptables -P OUTPUT ACCEPT'
04- su -c '/sbin/iptables -A FORWARD -i eth1 -o ppp0 -s 192.168.1.0/24 -p tcp --dport 80 -j ACCEPT'
05- su -c '/sbin/iptables -A FORWARD -i ppp0 -o eth1 -d 192.168.1.0/24 -p tcp --sport 80 -j ACCEPT'
06- su -c '/sbin/iptables -t nat -A POSTROUTING -o ppp0 -s 192.168.1.0/24 -j SNAT --to-source 123.123.123.2'
07- su -c '/bin/echo 1 > /proc/sys/net/ipv4/ip_forward'

Admonition("Note","Do not type the numbers at the beginning of each line. Start the actual command with su - numbers are shown here to explain the process more clearly.")

To list the rules in both tables, run:

su -c '/sbin/iptables -t filter -nvL' ; su -c '/sbin/iptables -t nat -nvL'

The output is:

01- Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

02- Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
04-     0     0 ACCEPT     tcp  --  eth1   ppp0    192.168.1.0/24       0.0.0.0/0           tcp dpt:80
05-     0     0 ACCEPT     tcp  --  ppp0   eth1    0.0.0.0/0            192.168.1.0/24      tcp spt:80

03- Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination



Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
06-     0     0 SNAT       all  --  *      ppp0    192.168.1.0/24       0.0.0.0/0           to:123.123.123.2

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Each command above corresponds to the line in the output preceded with the same number and the rules are set according to the following:

Lines 01-03:: The first three commands have now defined the global policies for the three built-in chains for the filter table. Firewall accepts everything that is classed as INPUT or OUTPUT, and for security it drops anything trying to pass through (FORWARD) the SNAT unless it is explicitly allowed.

Lines 04-05:: The two forward rules are quite specific. Rule 04 says that any incoming packet on the eth1 interface from the source network of 192.168.1.0/24, that goes out through the ppp0 device is accepteded if its destination port is 80. Rule 05 is the matching rule allowing the packet to return back through the NAT.

Line 06:: This rule is responsible for re-writing of the source IP address. It is applied after the routing decisions have been made and the packet is on its way to the Internet. According to the rule, any outgoing packet through the ppp0 interface from the 192.168.1.0/24 network is re-written, so that the source IP address becomes 123.123.123.2. When the packet reaches the Internet web server, it can be processed normally and returned to 123.123.123.2 (the NAT device), where it will automatically be re-written again and sent back to the workstation on the private network, where the packet originated.

Line 07:: This command enables packet forwarding between local network interfaces.

IP Masquerading

IP masquerading is a form of NAT most commonly used for all interfaces with dynamically assigned IP address. Without the masquerading ability, firewall rules will have to be re-written every time the IP address changes. SNAT (static NAT) from the previous section, remembers, to a degree, the connection state information when the connection becomes inactive. Using masquerading, the connection state information is reset each time the interface is deactivated and subsequently reactivated. Masquerading automates SNAT for dynamic IP connections.

The following example explains masquerading. To populate the tables with the set of rules, enter the following commands at the terminal line by line and press Enter after each line:

01- su -c '/sbin/iptables -P INPUT ACCEPT'
02- su -c '/sbin/iptables -P FORWARD DROP'
03- su -c '/sbin/iptables -P OUTPUT ACCEPT'
04- su -c '/sbin/iptables -A FORWARD -i ppp0 -m state --state ESTABLISHED,RELATED -j ACCEPT'
05- su -c '/sbin/iptables -A FORWARD -i eth1 -o ppp0 -s 192.168.1.0/24 -j ACCEPT'
06- su -c '/sbin/iptables -t nat -A POSTROUTING -o ppp0 -s 192.168.1.0/24 -j MASQUERADE'
07- su -c '/bin/echo 1 > /proc/sys/net/ipv4/ip_forward'

Admonition("Note","Do not type the numbers at the beginning of each line. Start the actual command with su - numbers are shown here to explain the process more clearly.")

To list the rules in both tables, run:

su -c '/sbin/iptables -t filter -nvL' ; su -c '/sbin/iptables -t nat -nvL'

The output is:

01- Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

02- Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
04-     0     0 ACCEPT     all  --  ppp0   *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
05-     0     0 ACCEPT     tcp  --  eth1   ppp0    192.168.1.0/24       0.0.0.0/0

03- Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination



Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
06-     0     0 MASQUERADE all  --  *      ppp0    192.168.1.0/24       0.0.0.0/0

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Each command above corresponds to the line in the output preceded with the same number and the rules are set according to the following:


Lines 01-03:: The first three commands define the global policies for the three built-in chains for the filter table. Firewall accepts everything that is classed as INPUT or OUTPUT, and it drops anything trying to pass through (FORWARD) the NAT unless explicitly allowed.

Line 04:: This rule handles connection state. According to the rule, any incoming packet through ppp0 interface must (-m) match a state, ie. must be in response to an already RELATED or ESTABLISHED connection. This rule denies any NEW connections to be initiated from the external network.

Line 05:: This rule allows packet forwarding of any incoming packets through the eth1 interface from the source network 192.168.1.0/24 to the ppp0 device. This rule allows internal workstations to create new connections, and matches rule 4 which allows the response packets to return.

Line 06:: This rule does the exact same as if it were a SNAT rule, however it will use the IP address that is currently assigned to the ppp0 interface when the packet passes through the NAT device. Any packets that now pass from the internal private network to the Internet will have their source address re-written as the external IP address of the NAT device.

Line 07:: This command enables packet forwarding between local network interfaces.

Admonition("Tip","Always use masquerading for dynamically assigned Internet interfaces.")

Admonition("Warning","Always specify an (-o) out interface parameter to make sure the masquerading rule works in one direction only!")

Destination NAT

Destination NAT deals with changing the destination address of any packets before they are subjected to any routing decisions. This allows specific packets to be re-written so they conform to a particular rule and can then be redirected, depending on the global policies and destinations required.

In its most typical application, DNAT is used to change the incoming packets that are destined for a particular service or host, and it rewrites the destination addresses, so the packets can pass to a different host located inside the private network, normally a DMZ.

When DNAT occurs, the original external host is not aware that the packets have been redirected and that the returning data is from a different host. This process is transparent to the originator.

The following example explains masquerading. To populate the tables with the set of rules, enter the following commands at the terminal line by line and press Enter after each line:

01- su -c '/sbin/iptables -P INPUT ACCEPT'
02- su -c '/sbin/iptables -P FORWARD DROP'
03- su -c '/sbin/iptables -P OUTPUT ACCEPT'
04- su -c '/sbin/iptables -A FORWARD -i eth1 -o ppp0 -s 192.168.1.0/24 -j ACCEPT'
05- su -c '/sbin/iptables -A FORWARD -i ppp0 -o eth1 -p tcp --dport 80 -j ACCEPT'
06- su -c '/sbin/iptables -t nat -A PREROUTING -i ppp0 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.2:80'
07- su -c '/bin/echo 1 > /proc/sys/net/ipv4/ip_forward'

Admonition("Note","Do not type the numbers at the beginning of each line. Start the actual command with su - numbers are shown here to explain the process more clearly.")

To list the rules in both tables, run:

su -c '/sbin/iptables -t filter -nvL' ; su -c '/sbin/iptables -t nat -nvL'

The output is:

01- 	Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

02- Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
04-     0     0 ACCEPT     all  --  eth1   ppp0    192.168.1.0/24       0.0.0.0/0
05-     0     0 ACCEPT     tcp  --  ppp0   eth1    0.0.0.0/0            192.168.1.0/24      tcp dpt:80

03- Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination



Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination
06-     0     0 DNAT       tcp  --  ppp0   *       0.0.0.0/0            0.0.0.0/0           tcp dpt:80 to:192.168.1.2:80

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Each command above corresponds to the line in the output preceded with the same number and the rules are set according to the following:


Lines 01-03:: The first three commands define the global policies for the three built-in chains for the filter table. Firewall accepts everything that is classed as INPUT or OUTPUT, and it drops anything trying to pass through the NAT unless explicitly allowed.

Line 04-05:: The first FORWARD rule (04) allows any incoming packets through the eth1 interface, from the source network 192.168.1.0/24, going out through the ppp0 interface. The second FORWARD rule (05) allows any incoming TCP packets through the ppp0 interface if their destination port is 80.

Line 06:: This is a PREROUTING rule that forces any incoming TCP packets through the ppp0 interface with the destination port 80, to be re-written and routed to the host 192.168.1.2.

Line 07:: This command enables packet forwarding between local network interfaces.

DNAT declarations are reasonably easy because the destination header can be rewritten before the routing table is queried. Some important points to remember are:

  • DNAT can re write packets as they enter the Firewall (before routing).
  • If the new destination host is compromised, the Firewall host is not affected.
  • Do not DNAT a packet to another system that will DNAT it back (routing loops).
  • The "--to-destination" address does not have to be on the internal network.

Example Firewall Script

The following is an example firewall script which uses all of the concepts covered already in this chapter. It should therefore be relatively easy to understand, implement and maintain.

The firewall script firewall.sh is designed to separate and secure the private network (eth1) from the Internet traffic (ppp0), while providing some flexibility for the internal network which is being masqueraded.

#!/bin/sh
#

<!--#############################################################
-->
<!--# Define interfaces here
-->
EXT_DEV=ppp0
INT_DEV=eth1
INT_NET=192.168.1.0/24

<!--# Loading firewall modules
-->
modprobe ip_conntrack
modprobe ip_conntrack_ftp

<!--#############################################################
-->
<!--# Enable Packet Forwarding
-->
echo 1 > /proc/sys/net/ipv4/ip_forward

<!--# Remove all previous rules, and delete any user defined chains
-->
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X

<!--# Set the default policies to drop
-->
iptables -P INPUT   DROP
iptables -P OUTPUT  DROP
iptables -P FORWARD DROP

<!--# Loopback device OK
-->
iptables -A INPUT  -i lo -s 127.0.0.0/8 -d 127.0.0.0/8 -j ACCEPT
iptables -A OUTPUT -o lo -s 127.0.0.0/8 -d 127.0.0.0/8 -j ACCEPT

<!--# Allow all ICMP Traffic (optional) - IN, OUT and THROUGH.
-->
iptables -A INPUT   -p icmp --icmp-type any -j ACCEPT
iptables -A OUTPUT  -p icmp --icmp-type any -j ACCEPT
iptables -A FORWARD -p icmp --icmp-type any -j ACCEPT

<!--# Allow all Internal traffic to Server
-->
iptables -A INPUT  -i $INT_DEV -s $INT_NET -d $INT_NET -j ACCEPT
iptables -A OUTPUT -o $INT_DEV -s $INT_NET -d $INT_NET -j ACCEPT

<!--#############################################################
-->
<!--# OUTBOUND Rule: Allow ALL packets out the external device
-->
iptables -A OUTPUT  -o $EXT_DEV -j ACCEPT
iptables -A FORWARD -i $INT_DEV -o $EXT_DEV -j ACCEPT

<!--#############################################################
-->
<!--# MASQUERADING: All packets from the internal network will
-->
<!--# appear as if they had originated from the firewall.
-->
iptables -t nat -A POSTROUTING -o $EXT_DEV -s $INT_NET -j MASQUERADE

<!--#############################################################
-->
<!--# INBOUND Rule: Allow ALL EXT packets if a connection already exists (See "NEW" Inbound Rules)
-->
iptables -A INPUT   -i $EXT_DEV -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i $EXT_DEV -m state --state RELATED,ESTABLISHED -j ACCEPT


#
<!--# INBOUND Rules: Allow ONLY NEW packets on these ports.
-->
#

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 20  -j ACCEPT
iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 21  -j ACCEPT

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 22  -j ACCEPT

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 25  -j ACCEPT
iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 465 -j ACCEPT

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 80  -j ACCEPT
iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 443 -j ACCEPT

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 636 -j ACCEPT

iptables -A INPUT -i $EXT_DEV -m state --state NEW -m tcp -p tcp --syn --dport 993 -j ACCEPT

<!--#
-->


#
<!--# INBOUND DNAT (redirection) Rules: Allow ONLY NEW packets on these ports and redirect to internal services.
-->
#

<!--# INBOUND Rule: Redirect ALL packets to the INTERNAL workstation - HTTP
-->

<!--# INBOUND Rule: Redirect ALL packets to the INTERNAL workstation - HTTPS
-->

To run the script, save the text above as a file firewall.sh and run:

su -c '/bin/sh /path/to/firewall.sh'

and apply changes to the firewall:

su -c '/sbin/service iptables save'

Restart the iptables service...:

su -c '/sbin/service iptables restart'

...and check the output:

su -c '/sbin/iptables -t filter -nvL' ; su -c '/sbin/iptables -t nat -nvL'

To automatically start the iptables service at boot time, firewall kernel modules that are needed must also be loaded at startup. To configure this, add the following to the /etc/sysconfig/iptables-config file:

IPTABLES_MODULES="ip_conntrack ip_conntrack_ftp"

To check whether all the necessary modules have loaded automatically, run:

su -c '/sbin/lsmod'

Additional Information

Related Websites

Related Manuals

  • man 8 iptables

Scheduling Tasks

Introduction

Fedora provides a cron facility for tasks scheduling. The cron facility is most commonly used for routine system maintenance and other recurring tasks, such as execution of backup scripts at pre-determined intervals. The cron utility runs as a crond daemon and executes tasks specified in the system or master crontab file - /etc/crontab or users' crontab files which, once created, are installed in the /var/spool/cron directory.

System crontab File

The master crontab file consists of seven fields, in the following order:

Field Meaning Valid value
1 Minute 0-59
2 Hour 0-23
3 Day of Month 1-31
4 Month 1-12 or jan,feb,mar,etc.
5 Day of Week 0-7 or sun,mon,tue,etc; where 0 and 7 = Sunday, 1 = Monday...
6 username to run the task as Any valid userID on the system
7 Task to run Any program found in the PATH which user in the Field 6 has the right to execute
Idea.png
If used, the * symbol in the first five fields represents all valid values for the field.

As specified in the Fedora's default /etc/crontab file:

cat /etc/crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

...cron executes run-parts utility which processes all jobs found in /etc/cron.weekly directory, on every Sunday at 04:22.

The top section of the /etc/crontab file is optional and contains the lines which will set the environment variables for the jobs specified in the bottom section of the file. If these variables are not specified, the environment of the user in field 6 is used.

To add additional jobs to the system cron, place them in the /etc/cron.d directory.

User crontab Files

Use the crontab utility to edit, install, remove or view individual user's task schedules.

crontab Usage

Usage:

crontab <filename>

In the example above, the content of the file <filename> must conform to the crontab syntax. The only difference from the system crontab file is that the user crontab files do not contain user field. If the <filename> conforms to the crontab syntax, the crontab file of the user who runs the command will be installed in /var/spool/cron directory, with the user's name as a file name, i.e., if user root runs the command, the crontab file is created as /var/spool/cron/root.

User crontab files are not directly accessible to users, since the /var/spool/cron directory has 700 permissions set. To edit one's own crontab file the user must run the crontab command with an -e option:

crontab -e

The crontab -e may also be used to create the new crontab file. When executed, crontab -e opens the existing or new crontab file in the vim text editor. The altered crontab file is installed once it is written using :w option in vim.

To read the content of the crontab file, run:

crontab -l

To remove the crontab file, run:

crontab -r

To read or manipulate the other user's crontab file, as root run:

crontab -u <username> [options] 

To control which users can run crontab, use the /etc/cron.allow and /etc/cron.deny files. The rules are:

  • If the file /etc/cron.allow exists, add to it the username of the user to grant the access
  • If the file /etc/cron.deny exists, it must not contain the username of the user who needs access to the cron
  • If neither the /etc/cron.allow nor /etc/cron.deny exists, only the root user has access to the cron

Anacron

The anacron utility can be used to periodically schedule jobs on the machines which do not run 24 hours per day. The anacron is controlled by the /etc/anacrontab file. The /etc/anacrontab file has a syntax similar to the /etc/crontab. It consists of two sections:

  • Environment assignments section - where environment variables such as SHELL, PATH or MAILTO for the scheduled jobs are set
  • Job description section - where the actual jobs are scheduled

The job description section contains one or more lines, each consisting of four fields, separated by one or more blank space. The four fields are:

Field Meaning Valid value
1 Period n number of days
2 Delay n number of minutes
3 Job Identifier Any non-blank character, except /
4 Command to run Any shell command

The default /etc/anacrontab file on Fedora:

cat /etc/anacrontab


SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

1        65     cron.daily              nice run-parts /etc/cron.daily
7        70     cron.weekly             nice run-parts /etc/cron.weekly
@monthly 75     cron.monthly            nice run-parts /etc/cron.monthly

...executes the run-parts on all jobs from /etc/cron.weekly directory if it has not run in the last 7 days. run-parts will run with the delay of 70 minutes upon the start of the anacron daemon and use cron.weekly as an identifier for this job in anacron messages.

Additional Information

Related Manuals

Find more information about cron and anacron from the following man pages:

  • cron(8)
  • crontab(1)
  • crontab(5)
  • anacron(8)
  • anacrontab(5)