diff --git a/en_US.ISO8859-1/books/handbook/basics/chapter.xml b/en_US.ISO8859-1/books/handbook/basics/chapter.xml index bb43780cae..0b4bf61865 100644 --- a/en_US.ISO8859-1/books/handbook/basics/chapter.xml +++ b/en_US.ISO8859-1/books/handbook/basics/chapter.xml @@ -1,3751 +1,3440 @@ UNIX Basics Synopsis This chapter covers the basic commands and functionality of the &os; operating system. Much of this material is relevant for any &unix;-like operating system. New &os; users are encouraged to read through this chapter carefully. After reading this chapter, you will know: How to use and configure virtual consoles. How to create and manage users and groups on &os;. How &unix; file permissions and &os; file flags work. The default &os; file system layout. The &os; disk organization. How to mount and unmount file systems. What processes, daemons, and signals are. What a shell is, and how to change the default login environment. How to use basic text editors. What devices and device nodes are. How to read manual pages for more information. Virtual Consoles and Terminals virtual consoles terminals console Unless &os; has been configured to automatically start a graphical environment during startup, the system will boot into a command line login prompt, as seen in this example: FreeBSD/amd64 (pc3.example.org) (ttyv0) login: The first line contains some information about the system. The amd64 indicates that the system in this example is running a 64-bit version of &os;. The hostname is pc3.example.org, and ttyv0 indicates that this is the system console. The second line is the login prompt. Since &os; is a multiuser system, it needs some way to distinguish between different users. This is accomplished by requiring every user to log into the system before gaining access to the programs on the system. Every user has a unique name username and a personal password. To log into the system console, type the username that was configured during system installation, as described in , and press Enter. Then enter the password associated with the username and press Enter. The password is not echoed for security reasons. Once the correct password is input, the message of the day (MOTD) will be displayed followed by a command prompt. Depending upon the shell that was selected when the user was created, this prompt will be a #, $, or % character. The prompt indicates that the user is now logged into the &os; system console and ready to try the available commands. Virtual Consoles While the system console can be used to interact with the system, a user working from the command line at the keyboard of a &os; system will typically instead log into a virtual console. This is because system messages are configured by default to display on the system console. These messages will appear over the command or file that the user is working on, making it difficult to concentrate on the work at hand. By default, &os; is configured to provide several virtual consoles for inputting commands. Each virtual console has its own login prompt and shell and it is easy to switch between virtual consoles. This essentially provides the command line equivalent of having several windows open at the same time in a graphical environment. The key combinations AltF1 through AltF8 have been reserved by &os; for switching between virtual consoles. Use AltF1 to switch to the system console (ttyv0), AltF2 to access the first virtual console (ttyv1), AltF3 to access the second virtual console (ttyv2), and so on. When switching from one console to the next, &os; takes manages the screen output. The result is an illusion of having multiple virtual screens and keyboards that can be used to type commands for &os; to run. The programs that are launched in one virtual console do not stop running when the user switches to a different virtual console. Refer to &man.syscons.4;, &man.atkbd.4;, &man.vidcontrol.1; and &man.kbdcontrol.1; for a more technical description of the &os; console and its keyboard drivers. In &os;, the number of available virtual consoles is configured in this section of /etc/ttys: # name getty type status comments # ttyv0 "/usr/libexec/getty Pc" cons25 on secure # Virtual terminals ttyv1 "/usr/libexec/getty Pc" cons25 on secure ttyv2 "/usr/libexec/getty Pc" cons25 on secure ttyv3 "/usr/libexec/getty Pc" cons25 on secure ttyv4 "/usr/libexec/getty Pc" cons25 on secure ttyv5 "/usr/libexec/getty Pc" cons25 on secure ttyv6 "/usr/libexec/getty Pc" cons25 on secure ttyv7 "/usr/libexec/getty Pc" cons25 on secure ttyv8 "/usr/X11R6/bin/xdm -nodaemon" xterm off secure To disable a virtual console, put a comment symbol (#) at the beginning of the line representing that virtual console. For example, to reduce the number of available virtual consoles from eight to four, put a # in front of the last four lines representing virtual consoles ttyv5 through ttyv8. Do not comment out the line for the system console ttyv0. Note that the last virtual console (ttyv8) is used to access the graphical environment if &xorg; has been installed and configured as described in . For a detailed description of every column in this file and the available options for the virtual consoles, refer to &man.ttys.5;. Single User Mode The &os; boot menu provides an option labelled as Boot Single User. If this option is selected, the system will boot into a special mode known as single user mode. This mode is typically used to repair a system that will not boot or to reset the root password when it is not known. While in single user mode, networking and other virtual consoles are not available. However, full root access to the system is available, and by default, the root password is not needed. For these reasons, physical access to the keyboard is needed to boot into this mode and determining who has physical access to the keyboard is something to consider when securing a &os; system. The settings which control single user mode are found in this section of /etc/ttys: # name getty type status comments # # If console is marked "insecure", then init will ask for the root password # when going to single-user mode. console none unknown off secure By default, the status is set to secure. This assumes that who has physical access to the keyboard is either not important or it is controlled by a physical security policy. If this setting is changed to insecure, the assumption is that the environment itself is insecure because anyone can access the keyboard. When this line is changed to insecure, &os; will prompt for the root password when a user selects to boot into single user mode. Be careful when changing this setting to insecure! If the root password is forgotten, booting into single user mode is still possible, but may be difficult for someone who is not familiar with the &os; booting process. Changing Console Video Modes The &os; console default video mode may be adjusted to 1024x768, 1280x1024, or any other size supported by the graphics chip and monitor. To use a different video mode load the VESA module: &prompt.root; kldload vesa To determine which video modes are supported by the hardware, use &man.vidcontrol.1;. To get a list of supported video modes issue the following: &prompt.root; vidcontrol -i mode The output of this command lists the video modes that are supported by the hardware. To select a new video mode, specify the mode using &man.vidcontrol.1; as the root user: &prompt.root; vidcontrol MODE_279 If the new video mode is acceptable, it can be permanently set on boot by adding it to /etc/rc.conf: allscreens_flags="MODE_279" Users and Basic Account Management &os; allows multiple users to use the computer at the same time. While only one user can sit in front of the screen and use the keyboard at any one time, any number of users can log in to the system through the network. To use the system, each user should have their own user account. This chapter describes: The different types of user accounts on a &os; system. How to add, remove, and modify user accounts. How to set limits to control the resources that users and groups are allowed to access. How to create groups and add users as members of a group. Account Types Since all access to the &os; system is achieved using accounts and all processes are run by users, user and account management is important. There are three main types of accounts: system accounts, user accounts, and the superuser account. System Accounts accounts system System accounts are used to run services such as DNS, mail, and web servers. The reason for this is security; if all services ran as the superuser, they could act without restriction. accounts daemon accounts operator Examples of system accounts are daemon, operator, bind, news, and www. accounts nobody nobody is the generic unprivileged system account. However, the more services that use nobody, the more files and processes that user will become associated with, and hence the more privileged that user becomes. User Accounts accounts user User accounts are assigned to real people and are used to log in and use the system. Every person accessing the system should have a unique user account. This allows the administrator to find out who is doing what and prevents users from clobbering the settings of other users. Each user can set up their own environment to accommodate their use of the system, by configuring their default shell, editor, key bindings, and language settings. Every user account on a &os; system has certain information associated with it: User name The user name is typed at the login: prompt. Each user must have a unique user name. There are a number of rules for creating valid user names which are documented in &man.passwd.5;. It is recommended to use user names that consist of eight or fewer, all lower case characters in order to maintain backwards compatibility with applications. Password Each account has an associated password. User ID (UID) The User ID (UID) is a number used to uniquely identify the user to the &os; system. Commands that allow a user name to be specified will first convert it to the UID. It is recommended to use a UID less than 65535, since higher values may cause compatibility issues with some software. Group ID (GID) The Group ID (GID) is a number used to uniquely identify the primary group that the user belongs to. Groups are a mechanism for controlling access to resources based on a user's GID rather than their UID. This can significantly reduce the size of some configuration files and allows users to be members of more than one group. It is recommended to use a GID of 65535 or lower as higher GIDs may break some software. Login class Login classes are an extension to the group mechanism that provide additional flexibility when tailoring the system to different users. Login classes are discussed further in . Password change time By default, passwords do not expire. However, password expiration can be enabled on a per-user basis, forcing some or all users to change their passwords after a certain amount of time has elapsed. Account expiry time By default, &os; does not expire accounts. When creating accounts that need a limited lifespan, such as student accounts in a school, specify the account expiry date using &man.pw.8;. After the expiry time has elapsed, the account cannot be used to log in to the system, although the account's directories and files will remain. User's full name The user name uniquely identifies the account to &os;, but does not necessarily reflect the user's real name. Similar to a comment, this information can contain spaces, uppercase characters, and be more than 8 characters long. Home directory The home directory is the full path to a directory on the system. This is the user's starting directory when the user logs in. A common convention is to put all user home directories under /home/username or /usr/home/username. Each user stores their personal files and subdirectories in their own home directory. User shell The shell provides the user's default environment for interacting with the system. There are many different kinds of shells and experienced users will have their own preferences, which can be reflected in their account settings. The Superuser Account accounts superuser (root) The superuser account, usually called root, is used to manage the system with no limitations on privileges. For this reason, it should not be used for day-to-day tasks like sending and receiving mail, general exploration of the system, or programming. The superuser, unlike other user accounts, can operate without limits, and misuse of the superuser account may result in spectacular disasters. User accounts are unable to destroy the operating system by mistake, so it is recommended to login as a user account and to only become the superuser when a command requires extra privilege. Always double and triple-check any commands issued as the superuser, since an extra space or missing character can mean irreparable data loss. There are several ways to gain superuser privilege. While one can log in as root, this is highly discouraged. Instead, use &man.su.1; to become the superuser. If - is specified when running this command, the user will also inherit the root user's environment. The user running this command must be in the wheel group or else the command will fail. The user must also know the password for the root user account. In this example, the user only becomes superuser in order to run make install as this step requires superuser privilege. Once the command completes, the user types exit to leave the superuser account and return to the privilege of their user account. Install a Program As the Superuser &prompt.user; configure &prompt.user; make &prompt.user; su - Password: &prompt.root; make install &prompt.root; exit &prompt.user; The built-in &man.su.1; framework works well for single systems or small networks with just one system administrator. An alternative is to install the security/sudo package or port. This software provides activity logging and allows the administrator to configure which users can run which commands as the superuser. Managing Accounts accounts modifying &os; provides a variety of different commands to manage user accounts. The most common commands are summarized in , followed by some examples of their usage. See the manual page for each utility for more details and usage examples. Utilities for Managing User Accounts Command Summary &man.adduser.8; The recommended command-line application for adding new users. &man.rmuser.8; The recommended command-line application for removing users. &man.chpass.1; A flexible tool for changing user database information. &man.passwd.1; The command-line tool to change user passwords. &man.pw.8; A powerful and flexible tool for modifying all aspects of user accounts.
<command>adduser</command> accounts adding adduser /usr/share/skel skeleton directory The recommended program for adding new users is &man.adduser.8;. When a new user is added, this program automatically updates /etc/passwd and /etc/group. It also creates a home directory for the new user, copies in the default configuration files from /usr/share/skel, and can optionally mail the new user a welcome message. This utility must be run as the superuser. The &man.adduser.8; utility is interactive and walks through the steps for creating a new user account. As seen in , either input the required information or press Return to accept the default value shown in square brackets. In this example, the user has been invited into the wheel group, allowing them to become the superuser with &man.su.1;. When finished, the utility will prompt to either create another user or to exit. Adding a User on &os; &prompt.root; adduser Username: jru Full name: J. Random User Uid (Leave empty for default): Login group [jru]: Login group is jru. Invite jru into other groups? []: wheel Login class [default]: Shell (sh csh tcsh zsh nologin) [sh]: zsh Home directory [/home/jru]: Home directory permissions (Leave empty for default): Use password-based authentication? [yes]: Use an empty password? (yes/no) [no]: Use a random password? (yes/no) [no]: Enter password: Enter password again: Lock out the account after creation? [no]: Username : jru Password : **** Full Name : J. Random User Uid : 1001 Class : Groups : jru wheel Home : /home/jru Shell : /usr/local/bin/zsh Locked : no OK? (yes/no): yes adduser: INFO: Successfully added (jru) to the user database. Add another user? (yes/no): no Goodbye! &prompt.root; Since the password is not echoed when typed, be careful to not mistype the password when creating the user account. <command>rmuser</command> rmuser accounts removing To completely remove a user from the system, run &man.rmuser.8; as the superuser. This command performs the following steps: Removes the user's &man.crontab.1; entry, if one exists. Removes any &man.at.1; jobs belonging to the user. Kills all processes owned by the user. Removes the user from the system's local password file. Optionally removes the user's home directory, if it is owned by the user. Removes the incoming mail files belonging to the user from /var/mail. Removes all files owned by the user from temporary file storage areas such as /tmp. Finally, removes the username from all groups to which it belongs in /etc/group. If a group becomes empty and the group name is the same as the username, the group is removed. This complements the per-user unique groups created by &man.adduser.8;. &man.rmuser.8; cannot be used to remove superuser accounts since that is almost always an indication of massive destruction. By default, an interactive mode is used, as shown in the following example. <command>rmuser</command> Interactive Account Removal &prompt.root; rmuser jru Matching password entry: jru:*:1001:1001::0:0:J. Random User:/home/jru:/usr/local/bin/zsh Is this the entry you wish to remove? y Remove user's home directory (/home/jru)? y Removing user (jru): mailspool home passwd. &prompt.root; <command>chpass</command> chpass Any user can use &man.chpass.1; to change their default shell and personal information associated with their user account. The superuser can use this utility to change additional account information for any user. When passed no options, aside from an optional username, &man.chpass.1; displays an editor containing user information. When the user exits from the editor, the user database is updated with the new information. This utility will prompt for the user's password when exiting the editor, unless the utility is run as the superuser. In , the superuser has typed chpass jru and is now viewing the fields that can be changed for this user. If jru runs this command instead, only the last six fields will be displayed and available for editing. This is shown in . Using <command>chpass</command> as Superuser #Changing user database information for jru. Login: jru Password: * Uid [#]: 1001 Gid [# or name]: 1001 Change [month day year]: Expire [month day year]: Class: Home directory: /home/jru Shell: /usr/local/bin/zsh Full Name: J. Random User Office Location: Office Phone: Home Phone: Other information: Using <command>chpass</command> as Regular User #Changing user database information for jru. Shell: /usr/local/bin/zsh Full Name: J. Random User Office Location: Office Phone: Home Phone: Other information: The commands &man.chfn.1; and &man.chsh.1; are links to &man.chpass.1;, as are &man.ypchpass.1;, &man.ypchfn.1;, and &man.ypchsh.1;. Since NIS support is automatic, specifying the yp before the command is not necessary. How to configure NIS is covered in . <command>passwd</command> passwd accounts changing password Any user can easily change their password using &man.passwd.1;. To prevent accidental or unauthorized changes, this command will prompt for the user's original password before a new password can be set: Changing Your Password &prompt.user; passwd Changing local password for jru. Old password: New password: Retype new password: passwd: updating the database... passwd: done The superuser can change any user's password by specifying the username when running &man.passwd.1;. When this utility is run as the superuser, it will not prompt for the user's current password. This allows the password to be changed when a user cannot remember the original password. Changing Another User's Password as the Superuser &prompt.root; passwd jru Changing local password for jru. New password: Retype new password: passwd: updating the database... passwd: done As with &man.chpass.1;, &man.yppasswd.1; is a link to &man.passwd.1;, so NIS works with either command. <command>pw</command> pw The &man.pw.8; utility can create, remove, modify, and display users and groups. It functions as a front end to the system user and group files. &man.pw.8; has a very powerful set of command line options that make it suitable for use in shell scripts, but new users may find it more complicated than the other commands presented in this section.
- - Limiting Users - - - limiting users - - - accounts - limiting - - - &os; provides several methods for an administrator to - limit the amount of system resources an individual may use. - These limits are discussed in two sections: disk quotas and - other resource limits. - - - quotas - - - limiting users - quotas - - - disk quotas - - - Disk quotas limit the amount of disk space available to - users and provide a way to quickly check that usage without - calculating it every time. Quotas are discussed in - . - - The other resource limits include ways to limit the amount - of CPU, memory, and other resources a user may consume. These - are defined using login classes and are discussed here. - - - /etc/login.conf - - - Login classes are defined in - /etc/login.conf and are described in - detail in &man.login.conf.5;. Each user account is assigned - to a login class, default by default, and - each login class has a set of login capabilities associated - with it. A login capability is a - name=value - pair, where name is a well-known - identifier and value is an - arbitrary string which is processed accordingly depending on - the name. Setting up login classes - and capabilities is rather straightforward and is also - described in &man.login.conf.5;. - - - &os; does not normally read the configuration in - /etc/login.conf directly, but instead - reads the /etc/login.conf.db database - which provides faster lookups. Whenever - /etc/login.conf is edited, the - /etc/login.conf.db must be updated by - executing the following command: - - &prompt.root; cap_mkdb /etc/login.conf - - - Resource limits differ from the default login capabilities - in two ways. First, for every limit, there is a soft - (current) and hard limit. A soft limit may be adjusted by the - user or application, but may not be set higher than the hard - limit. The hard limit may be lowered by the user, but can - only be raised by the superuser. Second, most resource limits - apply per process to a specific user, not to the user as a - whole. These differences are mandated by the specific - handling of the limits, not by the implementation of the login - capability framework. - - Below are the most commonly used resource limits. The - rest of the limits, along with all the other login - capabilities, can be found in &man.login.conf.5;. - - - - coredumpsize - - - The limit on the size of a core file - - coredumpsize - - generated by a program is subordinate to other limits - - limiting users - coredumpsize - - on disk usage, such as filesize, or - disk quotas. This limit is often used as a less-severe - method of controlling disk space consumption. Since - users do not generate core files themselves, and often - do not delete them, setting this may save them from - running out of disk space should a large program - crash. - - - - - cputime - - - The maximum amount of CPU - - cputime - - - limiting users - cputime - - time a user's process may consume. Offending processes - will be killed by the kernel. - - - This is a limit on CPU time - consumed, not percentage of the CPU as displayed in - some fields by &man.top.1; and &man.ps.1;. - - - - - - filesize - - - The maximum size of a file - - filesize - - - limiting users - filesize - - the user may own. Unlike - disk quotas, this limit is - enforced on individual files, not the set of all files a - user owns. - - - - - maxproc - - - The maximum number of processes - - maxproc - - - limiting users - maxproc - - a user can run. This includes foreground and background - processes. This limit may not be larger than the system - limit specified by the kern.maxproc - &man.sysctl.8;. Setting this limit too small may hinder - a user's productivity as it is often useful to be logged - in multiple times or to execute pipelines. Some tasks, - such as compiling a large program, start lots of - processes. - - - - - memorylocked - - - The maximum amount of memory - - memorylocked - - - limiting users - memorylocked - - a process may request to be locked into main memory - using &man.mlock.2;. Some system-critical programs, - such as &man.amd.8;, lock into main memory so that if - the system begins to swap, they do not contribute to - disk thrashing. - - - - - memoryuse - - - The maximum amount of memory - - memoryuse - - - limiting users - memoryuse - - a process may consume at any given time. It includes - both core memory and swap usage. This is not a - catch-all limit for restricting memory consumption, but - is a good start. - - - - - openfiles - - - The maximum number of files a process may have open - - openfiles - - - limiting users - openfiles - . - In &os;, files are used to represent sockets and IPC - channels, so be careful not to set this too low. The - system-wide limit for this is defined by the - kern.maxfiles &man.sysctl.8;. - - - - - sbsize - - - The limit on the amount of network memory, and - thus mbufs - - sbsize - - - limiting users - sbsize - , - a user may consume. This can be generally used to limit - network communications. - - - - - stacksize - - - The maximum size of a process stack - - stacksize - - - limiting users - stacksize - . - This alone is not sufficient to limit the amount of - memory a program may use so it should be used in - conjunction with other limits. - - - - - There are a few other things to remember when setting - resource limits. Following are some general tips, - suggestions, and miscellaneous comments. - - - - Processes started at system startup by - /etc/rc are assigned to the - daemon login class. - - - - Although the /etc/login.conf that - comes with the system is a good source of reasonable - values for most limits, they may not be appropriate for - every system. Setting a limit too high may open the - system up to abuse, while setting it too low may put a - strain on productivity. - - - - Users of &xorg; should - probably be granted more resources than other users. - &xorg; by itself takes a lot of - resources, but it also encourages users to run more - programs simultaneously. - - - - Many limits apply to individual processes, not the - user as a whole. For example, setting - openfiles to 50 means that each process - the user runs may open up to 50 files. The total amount - of files a user may open is the value of - openfiles multiplied by the value of - maxproc. This also applies to memory - consumption. - - - - For further information on resource limits and login - classes and capabilities in general, refer to - &man.cap.mkdb.1;, &man.getrlimit.2;, and - &man.login.conf.5;. - - Managing Groups groups /etc/groups accounts groups A group is a list of users. A group is identified by its group name and GID. In &os;, the kernel uses the UID of a process, and the list of groups it belongs to, to determine what the process is allowed to do. Most of the time, the GID of a user or process usually means the first group in the list. The group name to GID mapping is listed in /etc/group. This is a plain text file with four colon-delimited fields. The first field is the group name, the second is the encrypted password, the third the GID, and the fourth the comma-delimited list of members. For a more complete description of the syntax, refer to &man.group.5;. The superuser can modify /etc/group using a text editor. Alternatively, &man.pw.8; can be used to add and edit groups. For example, to add a group called teamtwo and then confirm that it exists: Adding a Group Using &man.pw.8; &prompt.root; pw groupadd teamtwo &prompt.root; pw groupshow teamtwo teamtwo:*:1100: In this example, 1100 is the GID of teamtwo. Right now, teamtwo has no members. This command will add jru as a member of teamtwo. Adding User Accounts to a New Group Using &man.pw.8; &prompt.root; pw groupmod teamtwo -M jru &prompt.root; pw groupshow teamtwo teamtwo:*:1100:jru The argument to is a comma-delimited list of users to be added to a new (empty) group or to replace the members of an existing group. To the user, this group membership is different from (and in addition to) the user's primary group listed in the password file. This means that the user will not show up as a member when using with &man.pw.8;, but will show up when the information is queried via &man.id.1; or a similar tool. When &man.pw.8; is used to add a user to a group, it only manipulates /etc/group and does not attempt to read additional data from /etc/passwd. Adding a New Member to a Group Using &man.pw.8; &prompt.root; pw groupmod teamtwo -m db &prompt.root; pw groupshow teamtwo teamtwo:*:1100:jru,db In this example, the argument to is a comma-delimited list of users who are to be added to the group. Unlike the previous example, these users are appended to the group and do not replace existing users in the group. Using &man.id.1; to Determine Group Membership &prompt.user; id jru uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo) In this example, jru is a member of the groups jru and teamtwo. For more information about this command and the format of /etc/group, refer to &man.pw.8; and &man.group.5;.
Permissions UNIX In &os;, every file and directory has an associated set of permissions and several utilities are available for viewing and modifying these permissions. Understanding how permissions work is necessary to make sure that users are able to access the files that they need and are unable to improperly access the files used by the operating system or owned by other users. This section discusses the traditional &unix; permissions used in &os;. For finer grained file system access control, refer to . In &unix;, basic permissions are assigned using three types of access: read, write, and execute. These access types are used to determine file access to the file's owner, group, and others (everyone else). The read, write, and execute permissions can be represented as the letters r, w, and x. They can also be represented as binary numbers as each permission is either on or off (0). When represented as a number, the order is always read as rwx, where r has an on value of 4, w has an on value of 2 and x has an on value of 1. Table 4.1 summarizes the possible numeric and alphabetic possibilities. When reading the Directory Listing column, a - is used to represent a permission that is set to off. permissions file permissions &unix; Permissions Value Permission Directory Listing 0 No read, no write, no execute --- 1 No read, no write, execute --x 2 No read, write, no execute -w- 3 No read, write, execute -wx 4 Read, no write, no execute r-- 5 Read, no write, execute r-x 6 Read, write, no execute rw- 7 Read, write, execute rwx
&man.ls.1; directories Use the argument to &man.ls.1; to view a long directory listing that includes a column of information about a file's permissions for the owner, group, and everyone else. For example, a ls -l in an arbitrary directory may show: &prompt.user; ls -l total 530 -rw-r--r-- 1 root wheel 512 Sep 5 12:31 myfile -rw-r--r-- 1 root wheel 512 Sep 5 12:31 otherfile -rw-r--r-- 1 root wheel 7680 Sep 5 12:31 email.txt The first (leftmost) character in the first column indicates whether this file is a regular file, a directory, a special character device, a socket, or any other special pseudo-file device. In this example, the - indicates a regular file. The next three characters, rw- in this example, give the permissions for the owner of the file. The next three characters, r--, give the permissions for the group that the file belongs to. The final three characters, r--, give the permissions for the rest of the world. A dash means that the permission is turned off. In this example, the permissions are set so the owner can read and write to the file, the group can read the file, and the rest of the world can only read the file. According to the table above, the permissions for this file would be 644, where each digit represents the three parts of the file's permission. How does the system control permissions on devices? &os; treats most hardware devices as a file that programs can open, read, and write data to. These special device files are stored in /dev/. Directories are also treated as files. They have read, write, and execute permissions. The executable bit for a directory has a slightly different meaning than that of files. When a directory is marked executable, it means it is possible to change into that directory using &man.cd.1;. This also means that it is possible to access the files within that directory, subject to the permissions on the files themselves. In order to perform a directory listing, the read permission must be set on the directory. In order to delete a file that one knows the name of, it is necessary to have write and execute permissions to the directory containing the file. There are more permission bits, but they are primarily used in special circumstances such as setuid binaries and sticky directories. For more information on file permissions and how to set them, refer to &man.chmod.1;. Symbolic Permissions Tom Rhodes Contributed by permissions symbolic Symbolic permissions use characters instead of octal values to assign permissions to files or directories. Symbolic permissions use the syntax of (who) (action) (permissions), where the following values are available: Option Letter Represents (who) u User (who) g Group owner (who) o Other (who) a All (world) (action) + Adding permissions (action) - Removing permissions (action) = Explicitly set permissions (permissions) r Read (permissions) w Write (permissions) x Execute (permissions) t Sticky bit (permissions) s Set UID or GID These values are used with &man.chmod.1;, but with letters instead of numbers. For example, the following command would block other users from accessing FILE: &prompt.user; chmod go= FILE A comma separated list can be provided when more than one set of changes to a file must be made. For example, the following command removes the group and world write permission on FILE, and adds the execute permissions for everyone: &prompt.user; chmod go-w,a+x FILE &os; File Flags Tom Rhodes Contributed by In addition to file permissions, &os; supports the use of file flags. These flags add an additional level of security and control over files, but not directories. With file flags, even root can be prevented from removing or altering files. File flags are modified using &man.chflags.1;. For example, to enable the system undeletable flag on the file file1, issue the following command: &prompt.root; chflags sunlink file1 To disable the system undeletable flag, put a no in front of the : &prompt.root; chflags nosunlink file1 To view the flags of a file, use with &man.ls.1;: &prompt.root; ls -lo file1 -rw-r--r-- 1 trhodes trhodes sunlnk 0 Mar 1 05:54 file1 Several file flags may only be added or removed by the root user. In other cases, the file owner may set its file flags. Refer to &man.chflags.1; and &man.chflags.2; for more information. The <literal>setuid</literal>, <literal>setgid</literal>, and <literal>sticky</literal> Permissions Tom Rhodes Contributed by Other than the permissions already discussed, there are three other specific settings that all administrators should know about. They are the setuid, setgid, and sticky permissions. These settings are important for some &unix; operations as they provide functionality not normally granted to normal users. To understand them, the difference between the real user ID and effective user ID must be noted. The real user ID is the UID who owns or starts the process. The effective UID is the user ID the process runs as. As an example, &man.passwd.1; runs with the real user ID when a user changes their password. However, in order to update the password database, the command runs as the effective ID of the root user. This allows users to change their passwords without seeing a Permission Denied error. The setuid permission may be set by prefixing a permission set with the number four (4) as shown in the following example: &prompt.root; chmod 4755 suidexample.sh The permissions on suidexample.sh now look like the following: -rwsr-xr-x 1 trhodes trhodes 63 Aug 29 06:36 suidexample.sh Note that a s is now part of the permission set designated for the file owner, replacing the executable bit. This allows utilities which need elevated permissions, such as &man.passwd.1;. The nosuid &man.mount.8; option will cause such binaries to silently fail without alerting the user. That option is not completely reliable as a nosuid wrapper may be able to circumvent it. To view this in real time, open two terminals. On one, type passwd as a normal user. While it waits for a new password, check the process table and look at the user information for &man.passwd.1;: In terminal A: Changing local password for trhodes Old Password: In terminal B: &prompt.root; ps aux | grep passwd trhodes 5232 0.0 0.2 3420 1608 0 R+ 2:10AM 0:00.00 grep passwd root 5211 0.0 0.2 3620 1724 2 I+ 2:09AM 0:00.01 passwd Although &man.passwd.1; is run as a normal user, it is using the effective UID of root. The setgid permission performs the same function as the setuid permission; except that it alters the group settings. When an application or utility executes with this setting, it will be granted the permissions based on the group that owns the file, not the user who started the process. To set the setgid permission on a file, provide &man.chmod.1; with a leading two (2): &prompt.root; chmod 2755 sgidexample.sh In the following listing, notice that the s is now in the field designated for the group permission settings: -rwxr-sr-x 1 trhodes trhodes 44 Aug 31 01:49 sgidexample.sh In these examples, even though the shell script in question is an executable file, it will not run with a different EUID or effective user ID. This is because shell scripts may not access the &man.setuid.2; system calls. The setuid and setgid permission bits may lower system security, by allowing for elevated permissions. The third special permission, the sticky bit, can strengthen the security of a system. When the sticky bit is set on a directory, it allows file deletion only by the file owner. This is useful to prevent file deletion in public directories, such as /tmp, by users who do not own the file. To utilize this permission, prefix the permission set with a one (1): &prompt.root; chmod 1777 /tmp The sticky bit permission will display as a t at the very end of the permission set: &prompt.root; ls -al / | grep tmp drwxrwxrwt 10 root wheel 512 Aug 31 01:49 tmp
Directory Structure directory hierarchy The &os; directory hierarchy is fundamental to obtaining an overall understanding of the system. The most important directory is root or, /. This directory is the first one mounted at boot time and it contains the base system necessary to prepare the operating system for multi-user operation. The root directory also contains mount points for other file systems that are mounted during the transition to multi-user operation. A mount point is a directory where additional file systems can be grafted onto a parent file system (usually the root file system). This is further described in . Standard mount points include /usr/, /var/, /tmp/, /mnt/, and /cdrom/. These directories are usually referenced to entries in /etc/fstab. This file is a table of various file systems and mount points and is read by the system. Most of the file systems in /etc/fstab are mounted automatically at boot time from the script &man.rc.8; unless their entry includes . Details can be found in . A complete description of the file system hierarchy is available in &man.hier.7;. The following table provides a brief overview of the most common directories. Directory Description / Root directory of the file system. /bin/ User utilities fundamental to both single-user and multi-user environments. /boot/ Programs and configuration files used during operating system bootstrap. /boot/defaults/ Default boot configuration files. Refer to &man.loader.conf.5; for details. /dev/ Device nodes. Refer to &man.intro.4; for details. /etc/ System configuration files and scripts. /etc/defaults/ Default system configuration files. Refer to &man.rc.8; for details. /etc/mail/ Configuration files for mail transport agents such as &man.sendmail.8;. /etc/namedb/ &man.named.8; configuration files. /etc/periodic/ Scripts that run daily, weekly, and monthly, via &man.cron.8;. Refer to &man.periodic.8; for details. /etc/ppp/ &man.ppp.8; configuration files. /mnt/ Empty directory commonly used by system administrators as a temporary mount point. /proc/ Process file system. Refer to &man.procfs.5;, &man.mount.procfs.8; for details. /rescue/ Statically linked programs for emergency recovery as described in &man.rescue.8;. /root/ Home directory for the root account. /sbin/ System programs and administration utilities fundamental to both single-user and multi-user environments. /tmp/ Temporary files which are usually not preserved across a system reboot. A memory-based file system is often mounted at /tmp. This can be automated using the tmpmfs-related variables of &man.rc.conf.5; or with an entry in /etc/fstab; refer to &man.mdmfs.8; for details. /usr/ The majority of user utilities and applications. /usr/bin/ Common utilities, programming tools, and applications. /usr/include/ Standard C include files. /usr/lib/ Archive libraries. /usr/libdata/ Miscellaneous utility data files. /usr/libexec/ System daemons and system utilities executed by other programs. /usr/local/ Local executables and libraries. Also used as the default destination for the &os; ports framework. Within /usr/local, the general layout sketched out by &man.hier.7; for /usr should be used. Exceptions are the man directory, which is directly under /usr/local rather than under /usr/local/share, and the ports documentation is in share/doc/port. /usr/obj/ Architecture-specific target tree produced by building the /usr/src tree. /usr/ports/ The &os; Ports Collection (optional). /usr/sbin/ System daemons and system utilities executed by users. /usr/share/ Architecture-independent files. /usr/src/ BSD and/or local source files. /var/ Multi-purpose log, temporary, transient, and spool files. A memory-based file system is sometimes mounted at /var. This can be automated using the varmfs-related variables in &man.rc.conf.5; or with an entry in /etc/fstab; refer to &man.mdmfs.8; for details. /var/log/ Miscellaneous system log files. /var/mail/ User mailbox files. /var/spool/ Miscellaneous printer and mail system spooling directories. /var/tmp/ Temporary files which are usually preserved across a system reboot, unless /var is a memory-based file system. /var/yp/ NIS maps. Disk Organization The smallest unit of organization that &os; uses to find files is the filename. Filenames are case-sensitive, which means that readme.txt and README.TXT are two separate files. &os; does not use the extension of a file to determine whether the file is a program, document, or some other form of data. Files are stored in directories. A directory may contain no files, or it may contain many hundreds of files. A directory can also contain other directories, allowing a hierarchy of directories within one another in order to organize data. Files and directories are referenced by giving the file or directory name, followed by a forward slash, /, followed by any other directory names that are necessary. For example, if the directory foo contains a directory bar which contains the file readme.txt, the full name, or path, to the file is foo/bar/readme.txt. Note that this is different from &windows; which uses \ to separate file and directory names. &os; does not use drive letters, or other drive names in the path. For example, one would not type c:\foo\bar\readme.txt on &os;. Directories and files are stored in a file system. Each file system contains exactly one directory at the very top level, called the root directory for that file system. This root directory can contain other directories. One file system is designated the root file system or /. Every other file system is mounted under the root file system. No matter how many disks are on the &os; system, every directory appears to be part of the same disk. Consider three file systems, called A, B, and C. Each file system has one root directory, which contains two other directories, called A1, A2 (and likewise B1, B2 and C1, C2). Call A the root file system. If &man.ls.1; is used to view the contents of this directory, it will show two subdirectories, A1 and A2. The directory tree looks like this: / | +--- A1 | `--- A2 A file system must be mounted on to a directory in another file system. When mounting file system B on to the directory A1, the root directory of B replaces A1, and the directories in B appear accordingly: / | +--- A1 | | | +--- B1 | | | `--- B2 | `--- A2 Any files that are in the B1 or B2 directories can be reached with the path /A1/B1 or /A1/B2 as necessary. Any files that were in /A1 have been temporarily hidden. They will reappear if B is unmounted from A. If B had been mounted on A2 then the diagram would look like this: / | +--- A1 | `--- A2 | +--- B1 | `--- B2 and the paths would be /A2/B1 and /A2/B2 respectively. File systems can be mounted on top of one another. Continuing the last example, the C file system could be mounted on top of the B1 directory in the B file system, leading to this arrangement: / | +--- A1 | `--- A2 | +--- B1 | | | +--- C1 | | | `--- C2 | `--- B2 Or C could be mounted directly on to the A file system, under the A1 directory: / | +--- A1 | | | +--- C1 | | | `--- C2 | `--- A2 | +--- B1 | `--- B2 It is entirely possible to have one large root file system, and not need to create any others. There are some drawbacks to this approach, and one advantage. Benefits of Multiple File Systems Different file systems can have different mount options. For example, the root file system can be mounted read-only, making it impossible for users to inadvertently delete or edit a critical file. Separating user-writable file systems, such as /home, from other file systems allows them to be mounted nosuid. This option prevents the suid/guid bits on executables stored on the file system from taking effect, possibly improving security. &os; automatically optimizes the layout of files on a file system, depending on how the file system is being used. So a file system that contains many small files that are written frequently will have a different optimization to one that contains fewer, larger files. By having one big file system this optimization breaks down. &os;'s file systems are robust if power is lost. However, a power loss at a critical point could still damage the structure of the file system. By splitting data over multiple file systems it is more likely that the system will still come up, making it easier to restore from backup as necessary. Benefit of a Single File System File systems are a fixed size. If you create a file system when you install &os; and give it a specific size, you may later discover that you need to make the partition bigger. This is not easily accomplished without backing up, recreating the file system with the new size, and then restoring the backed up data. &os; features the &man.growfs.8; command, which makes it possible to increase the size of file system on the fly, removing this limitation. File systems are contained in partitions. This does not have the same meaning as the common usage of the term partition (for example, &ms-dos; partition), because of &os;'s &unix; heritage. Each partition is identified by a letter from a through to h. Each partition can contain only one file system, which means that file systems are often described by either their typical mount point in the file system hierarchy, or the letter of the partition they are contained in. &os; also uses disk space for swap space to provide virtual memory. This allows your computer to behave as though it has much more memory than it actually does. When &os; runs out of memory, it moves some of the data that is not currently being used to the swap space, and moves it back in (moving something else out) when it needs it. Some partitions have certain conventions associated with them. Partition Convention a Normally contains the root file system. b Normally contains swap space. c Normally the same size as the enclosing slice. This allows utilities that need to work on the entire slice, such as a bad block scanner, to work on the c partition. A file system would not normally be created on this partition. d Partition d used to have a special meaning associated with it, although that is now gone and d may work as any normal partition. Disks in &os; are divided into slices, referred to in &windows; as partitions, which are numbered from 1 to 4. These are then divided into partitions, which contain file systems, and are labeled using letters. slices partitions dangerously dedicated Slice numbers follow the device name, prefixed with an s, starting at 1. So da0s1 is the first slice on the first SCSI drive. There can only be four physical slices on a disk, but there can be logical slices inside physical slices of the appropriate type. These extended slices are numbered starting at 5, so ad0s5 is the first extended slice on the first IDE disk. These devices are used by file systems that expect to occupy a slice. Slices, dangerously dedicated physical drives, and other drives contain partitions, which are represented as letters from a to h. This letter is appended to the device name, so da0a is the a partition on the first da drive, which is dangerously dedicated. ad1s3e is the fifth partition in the third slice of the second IDE disk drive. Finally, each disk on the system is identified. A disk name starts with a code that indicates the type of disk, and then a number, indicating which disk it is. Unlike slices, disk numbering starts at 0. Common codes are listed in . When referring to a partition, include the disk name, s, the slice number, and then the partition letter. Examples are shown in . shows a conceptual model of a disk layout. When installing &os;, configure the disk slices, create partitions within the slice to be used for &os;, create a file system or swap space in each partition, and decide where each file system will be mounted. Disk Device Names Drive Type Drive Device Name IDE and SATA hard drives ad or ada SCSI hard drives and USB storage devices da IDE and SATA CD-ROM drives acd or cd SCSI CD-ROM drives cd Floppy drives fd Assorted non-standard CD-ROM drives mcd for Mitsumi CD-ROM and scd for Sony CD-ROM devices SCSI tape drives sa IDE tape drives ast RAID drives Examples include aacd for &adaptec; AdvancedRAID, mlxd and mlyd for &mylex;, amrd for AMI &megaraid;, idad for Compaq Smart RAID, twed for &tm.3ware; RAID.
Sample Disk, Slice, and Partition Names Name Meaning ad0s1a The first partition (a) on the first slice (s1) on the first IDE disk (ad0). da1s2e The fifth partition (e) on the second slice (s2) on the second SCSI disk (da1). Conceptual Model of a Disk This diagram shows &os;'s view of the first IDE disk attached to the system. Assume that the disk is 4 GB in size, and contains two 2 GB slices (&ms-dos; partitions). The first slice contains a &ms-dos; disk, C:, and the second slice contains a &os; installation. This example &os; installation has three data partitions, and a swap partition. The three partitions will each hold a file system. Partition a will be used for the root file system, e for the /var/ directory hierarchy, and f for the /usr/ directory hierarchy. .-----------------. --. | | | | DOS / Windows | | : : > First slice, ad0s1 : : | | | | :=================: ==: --. | | | Partition a, mounted as / | | | > referred to as ad0s2a | | | | | :-----------------: ==: | | | | Partition b, used as swap | | | > referred to as ad0s2b | | | | | :-----------------: ==: | Partition c, no | | | Partition e, used as /var > file system, all | | > referred to as ad0s2e | of FreeBSD slice, | | | | ad0s2c :-----------------: ==: | | | | | : : | Partition f, used as /usr | : : > referred to as ad0s2f | : : | | | | | | | | --' | `-----------------' --'
Mounting and Unmounting File Systems The file system is best visualized as a tree, rooted, as it were, at /. /dev, /usr, and the other directories in the root directory are branches, which may have their own branches, such as /usr/local, and so on. root file system There are various reasons to house some of these directories on separate file systems. /var contains the directories log/, spool/, and various types of temporary files, and as such, may get filled up. Filling up the root file system is not a good idea, so splitting /var from / is often favorable. Another common reason to contain certain directory trees on other file systems is if they are to be housed on separate physical disks, or are separate virtual disks, such as Network File System mounts, described in , or CDROM drives. The <filename>fstab</filename> File file systems mounted with fstab During the boot process (), file systems listed in /etc/fstab are automatically mounted except for the entries containing . This file contains entries in the following format: device /mount-point fstype options dumpfreq passno device An existing device name as explained in . mount-point An existing directory on which to mount the file system. fstype The file system type to pass to &man.mount.8;. The default &os; file system is ufs. options Either for read-write file systems, or for read-only file systems, followed by any other options that may be needed. A common option is for file systems not normally mounted during the boot sequence. Other options are listed in &man.mount.8;. dumpfreq Used by &man.dump.8; to determine which file systems require dumping. If the field is missing, a value of zero is assumed. passno Determines the order in which file systems should be checked. File systems that should be skipped should have their passno set to zero. The root file system needs to be checked before everything else and should have its passno set to one. The other file systems should be set to values greater than one. If more than one file system has the same passno, &man.fsck.8; will attempt to check file systems in parallel if possible. Refer to &man.fstab.5; for more information on the format of /etc/fstab and its options. Using &man.mount.8; file systems mounting File systems are mounted using &man.mount.8;. The most basic syntax is as follows: &prompt.root; mount device mountpoint This command provides many options which are described in &man.mount.8;, The most commonly used options include: Mount Options Mount all the file systems listed in /etc/fstab, except those marked as noauto, excluded by the flag, or those that are already mounted. Do everything except for the actual mount system call. This option is useful in conjunction with the flag to determine what &man.mount.8; is actually trying to do. Force the mount of an unclean file system (dangerous), or the revocation of write access when downgrading a file system's mount status from read-write to read-only. Mount the file system read-only. This is identical to using . fstype Mount the specified file system type or mount only file systems of the given type, if is included. ufs is the default file system type. Update mount options on the file system. Be verbose. Mount the file system read-write. The following options can be passed to as a comma-separated list: nosuid Do not interpret setuid or setgid flags on the file system. This is also a useful security option. Using &man.umount.8; file systems unmounting To unmount a file system use &man.umount.8;. This command takes one parameter which can be a mountpoint, device name, or . All forms take to force unmounting, and for verbosity. Be warned that is not generally a good idea as it might crash the computer or damage data on the file system. To unmount all mounted file systems, or just the file system types listed after , use or . Note that does not attempt to unmount the root file system. Processes and Daemons &os; is a multi-tasking operating system. Each program running at any one time is called a process. Every running command starts at least one new process and there are a number of system processes that are run by &os;. Each process is uniquely identified by a number called a process ID (PID). Similar to files, each process has one owner and group, and the owner and group permissions are used to determine which files and devices the process can open. Most processes also have a parent process that started them. For example, the shell is a process, and any command started in the shell is a process which has the shell as its parent process. The exception is a special process called &man.init.8; which is always the first process to start at boot time and which always has a PID of 1. Some programs are not designed to be run with continuous user input and disconnect from the terminal at the first opportunity. For example, a web server responds to web requests, rather than user input. Mail servers are another example of this type of application. These types of programs are known as daemons. The term daemon comes from Greek mythology and represents an entity that is neither good nor evil, and which invisibly performs useful tasks. This is why the BSD mascot is the cheerful-looking daemon with sneakers and a pitchfork. There is a convention to name programs that normally run as daemons with a trailing d. For example, BIND is the Berkeley Internet Name Domain, but the actual program that executes is named. The Apache web server program is httpd and the line printer spooling daemon is lpd. This is only a naming convention. For example, the main mail daemon for the Sendmail application is sendmail, and not maild. Viewing Processes To see the processes running on the system, use &man.ps.1; or &man.top.1;. To display a static list of the currently running processes, their PIDs, how much memory they are using, and the command they were started with, use &man.ps.1;. To display all the running processes and update the display every few seconds in order to interactively see what the computer is doing, use &man.top.1;. By default, &man.ps.1; only shows the commands that are running and owned by the user. For example: &prompt.user; ps PID TT STAT TIME COMMAND 8203 0 Ss 0:00.59 /bin/csh 8895 0 R+ 0:00.00 ps The output from &man.ps.1; is organized into a number of columns. The PID column displays the process ID. PIDs are assigned starting at 1, go up to 99999, then wrap around back to the beginning. However, a PID is not reassigned if it is already in use. The TT column shows the tty the program is running on and STAT shows the program's state. TIME is the amount of time the program has been running on the CPU. This is usually not the elapsed time since the program was started, as most programs spend a lot of time waiting for things to happen before they need to spend time on the CPU. Finally, COMMAND is the command that was used to start the program. A number of different options are available to change the information that is displayed. One of the most useful sets is auxww, where displays information about all the running processes of all users, displays the username and memory usage of the process' owner, displays information about daemon processes, and causes &man.ps.1; to display the full command line for each process, rather than truncating it once it gets too long to fit on the screen. The output from &man.top.1; is similar: &prompt.user; top last pid: 9609; load averages: 0.56, 0.45, 0.36 up 0+00:20:03 10:21:46 107 processes: 2 running, 104 sleeping, 1 zombie CPU: 6.2% user, 0.1% nice, 8.2% system, 0.4% interrupt, 85.1% idle Mem: 541M Active, 450M Inact, 1333M Wired, 4064K Cache, 1498M Free ARC: 992M Total, 377M MFU, 589M MRU, 250K Anon, 5280K Header, 21M Other Swap: 2048M Total, 2048M Free PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAND 557 root 1 -21 r31 136M 42296K select 0 2:20 9.96% Xorg 8198 dru 2 52 0 449M 82736K select 3 0:08 5.96% kdeinit4 8311 dru 27 30 0 1150M 187M uwait 1 1:37 0.98% firefox 431 root 1 20 0 14268K 1728K select 0 0:06 0.98% moused 9551 dru 1 21 0 16600K 2660K CPU3 3 0:01 0.98% top 2357 dru 4 37 0 718M 141M select 0 0:21 0.00% kdeinit4 8705 dru 4 35 0 480M 98M select 2 0:20 0.00% kdeinit4 8076 dru 6 20 0 552M 113M uwait 0 0:12 0.00% soffice.bin 2623 root 1 30 10 12088K 1636K select 3 0:09 0.00% powerd 2338 dru 1 20 0 440M 84532K select 1 0:06 0.00% kwin 1427 dru 5 22 0 605M 86412K select 1 0:05 0.00% kdeinit4 The output is split into two sections. The header (the first five or six lines) shows the PID of the last process to run, the system load averages (which are a measure of how busy the system is), the system uptime (time since the last reboot) and the current time. The other figures in the header relate to how many processes are running, how much memory and swap space has been used, and how much time the system is spending in different CPU states. If the ZFS file system module has been loaded, an ARC line indicates how much data was read from the memory cache instead of from disk. Below the header is a series of columns containing similar information to the output from &man.ps.1;, such as the PID, username, amount of CPU time, and the command that started the process. By default, &man.top.1; also displays the amount of memory space taken by the process. This is split into two columns: one for total size and one for resident size. Total size is how much memory the application has needed and the resident size is how much it is actually using now. &man.top.1; automatically updates the display every two seconds. A different interval can be specified with . Killing Processes One way to communicate with any running process or daemon is to send a signal using &man.kill.1;. There are a number of different signals; some have a specific meaning while others are described in the application's documentation. A user can only send a signal to a process they own and sending a signal to someone else's process will result in a permission denied error. The exception is the root user, who can send signals to anyone's processes. The operating system can also send a signal to a process. If an application is badly written and tries to access memory that it is not supposed to, &os; will send the process the Segmentation Violation signal (SIGSEGV). If an application has been written to use the &man.alarm.3; system call to be alerted after a period of time has elapsed, it will be sent the Alarm signal (SIGALRM). Two signals can be used to stop a process: SIGTERM and SIGKILL. SIGTERM is the polite way to kill a process as the process can read the signal, close any log files it may have open, and attempt to finish what it is doing before shutting down. In some cases, a process may ignore SIGTERM if it is in the middle of some task that can not be interrupted. SIGKILL can not be ignored by a process. Sending a SIGKILL to a process will usually stop that process there and then. There are a few tasks that can not be interrupted. For example, if the process is trying to read from a file that is on another computer on the network, and the other computer is unavailable, the process is said to be uninterruptible. Eventually the process will time out, typically after two minutes. As soon as this time out occurs the process will be killed.. Other commonly used signals are SIGHUP, SIGUSR1, and SIGUSR2. Since these are general purpose signals, different applications will respond differently. For example, after changing a web server's configuration file, the web server needs to be told to re-read its configuration. Restarting httpd would result in a brief outage period on the web server. Instead, send the daemon the SIGHUP signal. Be aware that different daemons will have different behavior, so refer to the documentation for the daemon to determine if SIGHUP will achieve the desired results. Sending a Signal to a Process This example shows how to send a signal to &man.inetd.8;. The &man.inetd.8; configuration file is /etc/inetd.conf, and &man.inetd.8; will re-read this configuration file when it is sent a SIGHUP. Find the PID of the process to send the signal to using &man.pgrep.1;. In this example, the PID for &man.inetd.8; is 198: &prompt.user; pgrep -l inetd 198 inetd -wW Use &man.kill.1; to send the signal. Because &man.inetd.8; is owned by root, use &man.su.1; to become root first. &prompt.user; su Password: &prompt.root; /bin/kill -s HUP 198 Like most &unix; commands, &man.kill.1; will not print any output if it is successful. If a signal is sent to a process not owned by that user, the message kill: PID: Operation not permitted will be displayed. Mistyping the PID will either send the signal to the wrong process, which could have negative results, or will send the signal to a PID that is not currently in use, resulting in the error kill: PID: No such process. Why Use <command>/bin/kill</command>? Many shells provide kill as a built in command, meaning that the shell will send the signal directly, rather than running /bin/kill. Be aware that different shells have a different syntax for specifying the name of the signal to send. Rather than try to learn all of them, it can be simpler to specify /bin/kill. When sending other signals, substitute TERM or KILL with the name of the signal. Killing a random process on the system is a bad idea. In particular, &man.init.8;, PID 1, is special. Running /bin/kill -s KILL 1 is a quick, and unrecommended, way to shutdown the system. Always double check the arguments to &man.kill.1; before pressing Return. Shells shells command line A shell provides a command line interface for interacting with the operating system. A shell receives commands from the input channel and executes them. Many shells provide built in functions to help with everyday tasks such as file management, file globbing, command line editing, command macros, and environment variables. &os; comes with several shells, including the Bourne shell (&man.sh.1;) and the extended C shell (&man.tcsh.1;). Other shells are available from the &os; Ports Collection, such as zsh and bash. The shell that is used is really a matter of taste. A C programmer might feel more comfortable with a C-like shell such as &man.tcsh.1;. A &linux; user might prefer bash. Each shell has unique properties that may or may not work with a user's preferred working environment, which is why there is a choice of which shell to use. One common shell feature is filename completion. After a user types the first few letters of a command or filename and presses Tab, the shell completes the rest of the command or filename. Consider two files called foobar and football. To delete foobar, the user might type rm foo and press Tab to complete the filename. But the shell only shows rm foo. It was unable to complete the filename because both foobar and football start with foo. Some shells sound a beep or show all the choices if more than one name matches. The user must then type more characters to identify the desired filename. Typing a t and pressing Tab again is enough to let the shell determine which filename is desired and fill in the rest. environment variables Another feature of the shell is the use of environment variables. Environment variables are a variable/key pair stored in the shell's environment. This environment can be read by any program invoked by the shell, and thus contains a lot of program configuration. provides a list of common environment variables and their meanings. Note that the names of environment variables are always in uppercase. Common Environment Variables Variable Description USER Current logged in user's name. PATH Colon-separated list of directories to search for binaries. DISPLAY Network name of the &xorg; display to connect to, if available. SHELL The current shell. TERM The name of the user's type of terminal. Used to determine the capabilities of the terminal. TERMCAP Database entry of the terminal escape codes to perform various terminal functions. OSTYPE Type of operating system. MACHTYPE The system's CPU architecture. EDITOR The user's preferred text editor. PAGER The user's preferred utility for viewing text one page at a time. MANPATH Colon-separated list of directories to search for manual pages.
Bourne shells How to set an environment variable differs between shells. In &man.tcsh.1; and &man.csh.1;, use setenv to set environment variables. In &man.sh.1; and bash, use export to set the current environment variables. This example sets the default EDITOR to /usr/local/bin/emacs for the &man.tcsh.1; shell: &prompt.user; setenv EDITOR /usr/local/bin/emacs The equivalent command for bash would be: &prompt.user; export EDITOR="/usr/local/bin/emacs" To expand an environment variable in order to see its current setting, type a $ character in front of its name on the command line. For example, echo $TERM displays the current $TERM setting. Shells treat special characters, known as meta-characters, as special representations of data. The most common meta-character is *, which represents any number of characters in a filename. Meta-characters can be used to perform filename globbing. For example, echo * is equivalent to ls because the shell takes all the files that match * and echo lists them on the command line. To prevent the shell from interpreting a special character, escape it from the shell by starting it with a backslash (\). For example, echo $TERM prints the terminal setting whereas echo \$TERM literally prints the string $TERM. Changing the Shell The easiest way to permanently change the default shell is to use chsh. Running this command will open the editor that is configured in the EDITOR environment variable, which by default is set to &man.vi.1;. Change the Shell: line to the full path of the new shell. Alternately, use chsh -s which will set the specified shell without opening an editor. For example, to change the shell to bash: &prompt.user; chsh -s /usr/local/bin/bash The new shell must be present in /etc/shells. If the shell was installed from the &os; Ports Collection as described in , it should be automatically added to this file. If it is missing, add it using this command, replacing the path with the path of the shell: &prompt.root; echo /usr/local/bin/bash >> /etc/shells Then, rerun &man.chsh.1;. Advanced Shell Techniques Tom Rhodes Written by The &unix; shell is not just a command interpreter, it acts as a powerful tool which allows users to execute commands, redirect their output, redirect their input and chain commands together to improve the final command output. When this functionality is mixed with built in commands, the user is provided with an environment that can maximize efficiency. Shell redirection is the action of sending the output or the input of a command into another command or into a file. To capture the output of the &man.ls.1; command, for example, into a file, simply redirect the output: &prompt.user; ls > directory_listing.txt The directory_listing.txt file will now contain the directory contents. Some commands allow you to read input in a similar one, such as &man.sort.1;. To sort this listing, redirect the input: &prompt.user; sort < directory_listing.txt The input will be sorted and placed on the screen. To redirect that input into another file, one could redirect the output of &man.sort.1; by mixing the direction: &prompt.user; sort < directory_listing.txt > sorted.txt In all of the previous examples, the commands are performing redirection using file descriptors. Every unix system has file descriptors; however, here we will focus on three, so named as Standard Input, Standard Output, and Standard Error. Each one has a purpose, where input could be a keyboard or a mouse, something that provides input. Output could be a screen or paper in a printer for example. And error would be anything that is used for diagnostic or error messages. All three are considered I/O based file descriptors and sometimes considered streams. Through the use of these descriptors, short named stdin, stdout, and stderr, the shell allows output and input to be passed around through various commands and redirected to or from a file. Another method of redirection is the pipe operator. The &unix; pipe operator, | allows the output of one command to be directly passed, or directed to another program. Basically a pipe will allow the standard output of a command to be passed as standard input to another command, for example: &prompt.user; cat directory_listing.txt | sort | less In that example, the contents of directory_listing.txt will be sorted and the output passed to &man.less.1;. This allows the user to scroll through the output at their own pace and prevent it from scrolling off the screen.
Text Editors text editors editors Most &os; configuration is done by editing text files. Because of this, it is a good idea to become familiar with a text editor. &os; comes with a few as part of the base system, and many more are available in the Ports Collection. ee editors &man.ee.1; A simple editor to learn is &man.ee.1;, which stands for easy editor. To start this editor, type ee filename where filename is the name of the file to be edited. Once inside the editor, all of the commands for manipulating the editor's functions are listed at the top of the display. The caret (^) represents Ctrl, so ^e expands to Ctrl e . To leave &man.ee.1;, press Esc, then choose the leave editor option from the main menu. The editor will prompt to save any changes if the file has been modified. vi editors emacs &os; also comes with more powerful text editors, such as &man.vi.1;, as part of the base system. Other editors, like editors/emacs and editors/vim, are part of the &os; Ports Collection. These editors offer more functionality at the expense of being more complicated to learn. Learning a more powerful editor such as vim or Emacs can save more time in the long run. Many applications which modify files or require typed input will automatically open a text editor. To change the default editor, set the EDITOR environment variable as described in . Devices and Device Nodes A device is a term used mostly for hardware-related activities in a system, including disks, printers, graphics cards, and keyboards. When &os; boots, the majority of the boot messages refer to devices being detected. A copy of the boot messages are saved to /var/run/dmesg.boot. Each device has a device name and number. For example, acd0 is the first IDE CD-ROM drive, while kbd0 represents the keyboard. Most devices in a &os; must be accessed through special files called device nodes, which are located in /dev. Manual Pages manual pages The most comprehensive documentation on &os; is in the form of manual pages. Nearly every program on the system comes with a short reference manual explaining the basic operation and available arguments. These manuals can be viewed using man: &prompt.user; man command where command is the name of the command to learn about. For example, to learn more about &man.ls.1;, type: &prompt.user; man ls Manual pages are divided into sections which represent the type of topic. In &os;, the following sections are available: User commands. System calls and error numbers. Functions in the C libraries. Device drivers. File formats. Games and other diversions. Miscellaneous information. System maintenance and operation commands. System kernel interfaces. In some cases, the same topic may appear in more than one section of the online manual. For example, there is a chmod user command and a chmod() system call. To tell &man.man.1; which section to display, specify the section number: &prompt.user; man 1 chmod This will display the manual page for the user command &man.chmod.1;. References to a particular section of the online manual are traditionally placed in parenthesis in written documentation, so &man.chmod.1; refers to the user command and &man.chmod.2; refers to the system call. If the name of the manual page is unknown, use man -k to search for keywords in the manual page descriptions: &prompt.user; man -k mail This command displays a list of commands that have the keyword mail in their descriptions. This is equivalent to using &man.apropos.1;. To read the descriptions for the commands in /usr/bin, type: &prompt.user; cd /usr/bin &prompt.user; man -f * | more or &prompt.user; cd /usr/bin &prompt.user; whatis * |more GNU Info Files Free Software Foundation &os; includes many applications and utilities produced by the Free Software Foundation (FSF). In addition to manual pages, these programs may include hypertext documents called info files. These can be viewed using &man.info.1; or, if editors/emacs is installed, the info mode of emacs. To use &man.info.1;, type: &prompt.user; info For a brief introduction, type h. For a quick command reference, type ?.
diff --git a/en_US.ISO8859-1/books/handbook/security/chapter.xml b/en_US.ISO8859-1/books/handbook/security/chapter.xml index b3f6e2a99d..809dbcd3c5 100644 --- a/en_US.ISO8859-1/books/handbook/security/chapter.xml +++ b/en_US.ISO8859-1/books/handbook/security/chapter.xml @@ -1,3616 +1,3930 @@ Security Tom Rhodes Rewritten by security Synopsis Security, whether physical or virtual, is a topic so broad that an entire industry has grown up around it. Hundreds of standard practices have been authored about how to secure systems and networks, and as a user of &os;, understanding how to protect against attacks and intruders is a must. In this chapter, several fundamentals and techniques will be discussed. The &os; system comes with multiple layers of security, and many more third party utilities may be added to enhance security. After reading this chapter, you will know: Basic &os; system security concepts. The various crypt mechanisms available in &os;. How to set up one-time password authentication. How to configure TCP Wrapper for use with &man.inetd.8;. How to set up Kerberos on &os;. How to configure IPsec and create a VPN. How to configure and use OpenSSH on &os;. How to use file system ACLs. How to use portaudit to audit third party software packages installed from the Ports Collection. How to utilize &os; security advisories. What Process Accounting is and how to enable it on &os;. - Understand the resource limits database and how to - utilize it to control user resources. + How to control user resources using login classes or the + resource limits database. Before reading this chapter, you should: Understand basic &os; and Internet concepts. Additional security topics are covered elsewhere in this Handbook. For example, Mandatory Access Control is discussed in and Internet firewalls are discussed in . Introduction Security is everyone's responsibility. A weak entry point in any system could allow intruders to gain access to critical information and cause havoc on an entire network. In most security training, they discuss the security triad CIA which stands for the confidentiality, integrity, and availability of information systems. The CIA triad is a bedrock concept of computer security, customers and end users expect privacy of their data. They expect orders they place to not be changed or their information altered behind the scenes. They also expect access to information at all times. Together they make up the confidentiality, integrity, and availability of the system. To protect CIA, security professionals apply a defense in depth strategy. The idea of defense in depth is to add several layers of security to prevent one single layer failing and the entire security system collapsing. A systems administrator cannot simply turn on a firewall and consider the network or system secure, they must audit accounts, check the integrity of binaries, and ensure malicious tools are not installed. To do this, they must understand what the threats are. Threats What is a threat as pertaining to computer security? For years it was assumed that threats are remote attackers, people whom will attempt to access the system without permission, from a remote location. In today's world, this definition has been expanded to include employees, malicious software, rogue network devices, natural disasters, security vulnerabilities, and even competing corporations. Every day thousands of systems and networks are attacked and several hundred are accessed without permission. Sometimes by simple accident, others by remote attackers, and in some cases, corporate espionage or former employees. As a system user, it is important to prepare for and admit when a mistake has lead to a security breach and report possible issues to the security team. As an administrator, it is important to know of the threats and be prepared to mitigate them. A Ground Up Approach In security, it is sometimes best to take a ground up approach, whereas the administrator begins with the basic accounts, system configuration, and then begins to work with third party utilities and work up to the network layer. It is in these latter configuration aspects that system policy and procedures should take place. Many places of business already have a security policy that covers the configuration technology devices in use. They should contain, at minimal, the security configuration of end user workstations and desktops, mobile devices such as phones and laptops, and both production and development servers. In many cases, when applying computer security, standard operating procedures (SOPs) already exist. When in doubt, ask the security team. System and User Accounts In securing a system, the best starting point is auditing accounts. Ensure that the root account has a strong password, disable accounts that do not need shell access, for users who need to augment their privileges, install the security/sudo and only allow them access to applications they need. The root user password should never be shared. To deny access to accounts, two methods exist. The first one is to lock an account, for example, to lock the toor account: &prompt.root; pw lock toor This command will change the account from this toor:*:0:0::0:0:Bourne-again Superuser:/root: to toor:*LOCKED**:0:0::0:0:Bourne-again Superuser:/root: In some cases, this is not possible, perhaps because of an additional service. In those cases, login access could be prevented by changing the shell to /sbin/nologin like in this example: &prompt.root; chsh -s /usr/sbin/nologin toor Only super users are able to change the shell for other users. Attempting to perform this as a regular user will fail. The account structure will now look like this, with the nologin shell as the last entry: toor:*:0:0::0:0:Bourne-again Superuser:/root:/usr/sbin/nologin The /usr/sbin/nologin shell will block the &man.login.1; command from assigning a shell to this user. Permitted Account Escalation In some cases, system administration access needs to be shared with other users. &os; has two methods to handle this. The first one, which is not recommended, is a shared root password and adding users to the wheel group. To achieve this, edit the /etc/group and add the user to the end of the first group. This user must be separated by a comma character. The correct way to permit this privilege escalation is using the security/sudo port which will provide additional auditing, more fine grained user control, and even lock users into running only single, privileged commands such as &man.service.8; After installation, edit /usr/local/etc/sudoers using the visudo interface. In this example, a new webadmin group will be added, the user trhodes to that group, and then give the user access to restart apache24, the following procedure may be followed: &prompt.root; pw groupadd webadmin -M trhodes -g 6000 &prompt.root; visudo %webadmin ALL=(ALL) /usr/sbin/service apache24 * The security/sudo provides an invaluable resource when it comes to local user management. It is also possible to not require passwords and just default to the &man.ssh.1; key method. To disable password login via &man.sshd.8; and only use local passwords for sudo, see . Passwords Passwords are a necessary evil of technology. In the cases they must be used, not only should the password be extremely complex, but also use a powerful hash mechanism to protect it. At the time of this writing, &os; supports DES, MD5, Blowfish, SHA256, and SHA512 in the crypt() library. The default is SHA512 and should not be changed backwards; however, some users like to use the Blowfish option. Each mechanism, aside from DES, has a unique beginning to designate the hash mechanism assigned. For the MD5 mechanism, the symbol is a $ sign. For the SHA256 or SHA512, the symbol is $6$ and Blowfish uses $2a$. Any weaker passwords should be re-hashed by asking the user to run &man.passwd.1; during their next login. At the time of this writing, Blowfish is not part of AES nor is it considered compliant with any FIPS (Federal Information Processing Standards) standard and its use may not be permitted in some environments. For any system connected to the network, two factor authentication should be used. This is normally considered something you have and something you know. With OpenSSH being part of the &os; base system and the use of ssh-keys being available for some time, all network logins should avoid the use of passwords in exchange for this two factor authentication method. For more information see the section of the handbook. Kerberos users may need to make additional changes to implement OpenSSH in their network. Password Policy and Enforcement Enforcing a strong password policy for local accounts is a fundamental aspect of local system security and policy. During password enforcement, things like password length, password strength, and the likelihood the password could be guessed or cracked can be implemented through the system &man.pam.8; modules. The PAM system, or Pluggable Authentication Modules, will enforce the password policy by setting a minimum and maximum password length. They will also enforce mixed characters. In particular the &man.pam.passwdqc.8; will be discussed. To proceed, add the following line to /etc/pam.d/passwd: password requisite pam_passwdqc.so min=disabled,disabled,disabled,12,10 similar=deny retry=3 enforce=users There is already a commented out line for this module and it may be altered to the version above. This statement basically sets several requirements. First, a minimal password length is disabled, allowing for a password of any length. Using only two character classes are disabled, which means that all classes, including special, will be considered valid. The next entry requires that passwords be twelve characters in length with characters from three classes or ten byte (or more) passwords with characters from four character classes. This also denies passwords that are similar to the previously used password. A user is provided three opportunities to enter a new password and finally only enforce this requirement on users. That is, exempt super users. This statement is probably confusing so reading the manual page is highly recommended, in particular to understand what character classes are. After this change is made and the file saved, any user changing their password will see a message similar to the following. This message might also clear up some confusion about the configuration. &prompt.user; passwd Changing local password for trhodes Old Password: You can now choose the new password. A valid password should be a mix of upper and lower case letters, digits and other characters. You can use a 12 character long password with characters from at least 3 of these 4 classes, or a 10 character long password containing characters from all the classes. Characters that form a common pattern are discarded by the check. Alternatively, if noone else can see your terminal now, you can pick this as your password: "trait-useful&knob". Enter new password: If a weak password is entered, it will be rejected with a warning and the user will have an opportunity to try again In most password policies, a password aging requirement is normally set. This means that a every password must expire after so many days after it has been set. To set a password age time in &os;, set the in /etc/login.conf. Most users when added to the system just fall into the default group which is where this variable could be added and the database rebuilt using: &prompt.root; cap_mkdb /etc/login.conf To set the expiration on individual users, provide a day count to &man.pw.8; and a username like: &prompt.root; pw usermod -p 30-apr-2014 -n trhodes As seen here, an expiration date is set in the form of day, month, year. For more information, see &man.pw.8; Backdoors and Rootkits Backdoors and rootkits are only a threat after they have been installed. Once installed, this malicious software will normally open up another avenue of entry for an attacker. Realistically, once a system has been compromised, and an investigation has been performed, it should be erased. There is tremendous risk that even the most prudent security or systems engineer will miss something an attacker left behind. A backdoor or rootkit software does do one thing useful for administrators - once detected, it is a sign that a compromise happened at some point. But normally these types of applications are hidden very well. Tools do exist to detect backdoors and rootkits, one of them is security/rkhunter. After installation, the system may be checked using the following command. It will produce a lot of information and will require some manual pressing of the ENTER key: &prompt.root; rkhunter -c After the process completes, a status message will be printed to the screen. This message will include the amount of files checked, suspect files, possible rootkits, and more. During the check, some generic security warnings may be produced about hidden files, the OpenSSH protocol selection, and occasionally known vulnerable versions of installed software. These can be handled now or later after a more detailed analysis has been performed. Every administrator should know what is running on the systems they are responsible for. Using tools like rkhunter, lsof and native commands such as &man.netstat.1; and &man.ps.1; can show a great deal of information on the system. Take notes on what is normal, ask questions when something seems out of place and be paranoid. And remember, preventing a compromise is ideal but detecting a compromise is a must. Binary Verification Verification of system files and binaries is important because it provides the system administration and security team with information about system changes. In any system, no internal command or application should change without the system admin team knowing. A software application that monitors the system for changes is called an Intrusion Detection System or IDS. &os; provides native support for a basic IDS system. In fact, as part of the nightly &man.periodic.8; security emails will notify an administrator of changes. Since the information is stored locally, there is a chance a malicious user could modify and spoof the information. As such, it is recommended to create a separate set of binary signatures and store them on a read only, root owned directory or, preferably, off system such as a USB disk or rsync server. To being, a seed needs to be generated. This is a numeric constant that will be used as to help generate the hash values and to check the hash values. Lacking this seed value will make faking or checking the checksum values of files difficult it not impossible. In the following example, the key will be passed with the flag. First, generate a set of hashes and checksums for /bin using the following command: &prompt.root; mtree -s 3483151339707503 -c -K cksum,sha256digest -p /bin > bin_chksum_mtree This should have produced something similar to: &prompt.root; mtree: /bin checksum: 3427012225 Viewing bin_cksum_mtree should yield output similar to the following: # user: root # machine: dreadnaught # tree: /bin # date: Mon Feb 3 10:19:53 2014 # . /set type=file uid=0 gid=0 mode=0555 nlink=1 flags=none . type=dir mode=0755 nlink=2 size=1024 \ time=1380277977.000000000 \133 nlink=2 size=11704 time=1380277977.000000000 \ cksum=484492447 \ sha256digest=6207490fbdb5ed1904441fbfa941279055c3e24d3a4049aeb45094596400662a cat size=12096 time=1380277975.000000000 cksum=3909216944 \ sha256digest=65ea347b9418760b247ab10244f47a7ca2a569c9836d77f074e7a306900c1e69 chflags size=8168 time=1380277975.000000000 cksum=3949425175 \ sha256digest=c99eb6fc1c92cac335c08be004a0a5b4c24a0c0ef3712017b12c89a978b2dac3 chio size=18520 time=1380277975.000000000 cksum=2208263309 \ sha256digest=ddf7c8cb92a58750a675328345560d8cc7fe14fb3ccd3690c34954cbe69fc964 chmod size=8640 time=1380277975.000000000 cksum=2214429708 \ sha256digest=a435972263bf814ad8df082c0752aa2a7bdd8b74ff01431ccbd52ed1e490bbe7 Notice the machine's hostname, the current date and time, and the user who executed &man.mtree.8; are all included in this report. There is also a checksum, size, time and SHA256 digest for each binary that was found. To verify binary signatures, the following command will read in the current list of signatures and provide an output: &prompt.root; mtree -s 3483151339707503 -p /bin < bin_chksum_mtree >> bin_chksum_output This should produce the same checksum for /bin that was produced when the command was originally ran. Since no changes occurred in the time these commands were ran, the bin_chksum_output output will be empty. To simulate a change, change the date on /bin/cat using &man.touch.1; and run the verification command again: &prompt.root; touch /bin/cat &prompt.root; mtree -s 3483151339707503 -p /bin < bin_chksum_mtree >> bin_chksum_output &prompt.root; cat bin_chksum_output cat changed modification time expected Fri Sep 27 06:32:55 2013 found Mon Feb 3 10:28:43 2014 More advanced IDS systems exist, such as security/aide but in most cases, &man.mtree.8; provides the functionality administrators need. It is important to keep the seed value and the checksum output hidden from malicious users. System Tuning for Security Many of the systems features may be tuned through the use of &man.sysctl.8;. This is also true for a few security features which could be used to prevent denial of service (DOS) style attacks. Some of the more important will be covered here. Any time a setting is changed with &man.sysctl.8;, the chance to cause undesired harm is increased affecting the availability of the system. Considering the CIA of the system should be done during any system-wide configuration change. The following is a list of &man.sysctl.8;'s and a short description of what effects the changes will have on the system. By default, the &os; kernel boots with a security level of -1. This is called insecure mode because immutable file flags may be turned off and all devices may be read from or written to. The security level will remain at -1 unless it is altered, either by the administrator or by &man.init.8;, because of a setting in the startup scripts. The security level may be raised during system startup by setting kern_securelevel_enable to YES in /etc/rc.conf, and the value of kern_securelevel to the desired security level. See &man.security.7; and &man.init.8; for more information on these settings. Increasing the securelevel can break Xorg and cause other issues. Be prepared to do some debugging. Next &man.sysctl.8;s to change is the net.inet.tcp.blackhole and net.inet.udp.blackhole. When these are set, incoming SYN packets on closed ports will be dropped with no return RST response. The normal behavior is to return an RST to show a port is closed. These will provide some level of protection against stealth scans against a system. Set the net.inet.tcp.blackhole to 2 and the net.inet.udp.blackhole to 1 and review the information in &man.blackhole.4; for more information. Additionally the net.inet.icmp.drop_redirect and net.inet.ip.redirect should be set as well. These two &man.sysctl.8;s will help prevent against what are called redirect attacks. Redirect attacks are the purposeful mass issuing of ICMP type 5 packets which should not be required in a normal network. As such, set net.inet.icmp.drop_redirect to 1 and set net.inet.ip.redirect to 0. Source routing is method of detecting and accessing non-routable addresses on the internal network. This should probably be disabled as non-routable addresses are normally not routable on purpose. To disable this feature, set net.inet.ip.sourceroute and net.inet.ip.accept_sourceroute to 0. Drop all ICMP echo requests to the broadcast address. When machine on the network need to send messages to all hosts on a subnet, the message is sent to the broadcast address. There is no reason an external host should need to perform such an action so set net.inet.icmp.bmcastecho to 0 to reject all external broadcast requests. Some additional &man.sysctl.8;s are documented in &man.security.7; and it is recommended it be consulted for additional information. One-time Passwords one-time passwords security one-time passwords By default, &os; includes support for One-time Passwords In Everything (OPIE). OPIE is designed to prevent replay attacks, in which an attacker discovers a user's password and uses it to access a system. Since a password is only used once in OPIE, a discovered password is of little use to an attacker. OPIE uses a secure hash and a challenge/response system to manage passwords. The &os; implementation uses the MD5 hash by default. OPIE uses three different types of passwords. The first is the usual &unix; or Kerberos password. The second is the one-time password which is generated by opiekey. The third type of password is the secret password which is used to generate one-time passwords. The secret password has nothing to do with, and should be different from, the &unix; password. There are two other pieces of data that are important to OPIE. One is the seed or key, consisting of two letters and five digits. The other is the iteration count, a number between 1 and 100. OPIE creates the one-time password by concatenating the seed and the secret password, applying the MD5 hash as many times as specified by the iteration count, and turning the result into six short English words which represent the one-time password. The authentication system keeps track of the last one-time password used, and the user is authenticated if the hash of the user-provided password is equal to the previous password. Because a one-way hash is used, it is impossible to generate future one-time passwords if a successfully used password is captured. The iteration count is decremented after each successful login to keep the user and the login program in sync. When the iteration count gets down to 1, OPIE must be reinitialized. There are a few programs involved in this process. A one-time password, or a consecutive list of one-time passwords, is generated by passing an iteration count, a seed, and a secret password to &man.opiekey.1;. In addition to initializing OPIE, &man.opiepasswd.1; is used to change passwords, iteration counts, or seeds. The relevant credential files in /etc/opiekeys are examined by &man.opieinfo.1; which prints out the invoking user's current iteration count and seed. This section describes four different sorts of operations. The first is how to set up one-time-passwords for the first time over a secure connection. The second is how to use opiepasswd over an insecure connection. The third is how to log in over an insecure connection. The fourth is how to generate a number of keys which can be written down or printed out to use at insecure locations. Initializing <acronym>OPIE</acronym> To initialize OPIE for the first time, run this command from a secure location: &prompt.user; opiepasswd -c [grimreaper] ~ $ opiepasswd -f -c Adding unfurl: Only use this method from the console; NEVER from remote. If you are using telnet, xterm, or a dial-in, type ^C now or exit with no password. Then run opiepasswd without the -c parameter. Using MD5 to compute responses. Enter new secret pass phrase: Again new secret pass phrase: ID unfurl OTP key is 499 to4268 MOS MALL GOAT ARM AVID COED The sets console mode which assumes that the command is being run from a secure location, such as a computer under the user's control or a SSH session to a computer under the user's control. When prompted, enter the secret password which will be used to generate the one-time login keys. This password should be difficult to guess and should be different than the password which is associated with the user's login account. It must be between 10 and 127 characters long. Remember this password. The ID line lists the login name (unfurl), default iteration count (499), and default seed (to4268). When logging in, the system will remember these parameters and display them, meaning that they do not have to be memorized. The last line lists the generated one-time password which corresponds to those parameters and the secret password. At the next login, use this one-time password. Insecure Connection Initialization To initialize or change the secret password on an insecure system, a secure connection is needed to some place where opiekey can be run. This might be a shell prompt on a trusted machine. An iteration count is needed, where 100 is probably a good value, and the seed can either be specified or the randomly-generated one used. On the insecure connection, the machine being initialized, use &man.opiepasswd.1;: &prompt.user; opiepasswd Updating unfurl: You need the response from an OTP generator. Old secret pass phrase: otp-md5 498 to4268 ext Response: GAME GAG WELT OUT DOWN CHAT New secret pass phrase: otp-md5 499 to4269 Response: LINE PAP MILK NELL BUOY TROY ID mark OTP key is 499 gr4269 LINE PAP MILK NELL BUOY TROY To accept the default seed, press Return. Before entering an access password, move over to the secure connection and give it the same parameters: &prompt.user; opiekey 498 to4268 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: GAME GAG WELT OUT DOWN CHAT Switch back over to the insecure connection, and copy the generated one-time password over to the relevant program. Generating a Single One-time Password After initializing OPIE and logging in, a prompt like this will be displayed: &prompt.user; telnet example.com Trying 10.0.0.1... Connected to example.com Escape character is '^]'. FreeBSD/i386 (example.com) (ttypa) login: <username> otp-md5 498 gr4269 ext Password: The OPIE prompts provides a useful feature. If Return is pressed at the password prompt, the prompt will turn echo on and display what is typed. This can be useful when attempting to type in a password by hand from a printout. MS-DOS Windows MacOS At this point, generate the one-time password to answer this login prompt. This must be done on a trusted system where it is safe to run &man.opiekey.1;. There are versions of this command for &windows;, &macos; and &os;. This command needs the iteration count and the seed as command line options. Use cut-and-paste from the login prompt on the machine being logged in to. On the trusted system: &prompt.user; opiekey 498 to4268 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: GAME GAG WELT OUT DOWN CHAT Once the one-time password is generated, continue to log in. Generating Multiple One-time Passwords Sometimes there is no access to a trusted machine or secure connection. In this case, it is possible to use &man.opiekey.1; to generate a number of one-time passwords beforehand. For example: &prompt.user; opiekey -n 5 30 zz99999 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: <secret password> 26: JOAN BORE FOSS DES NAY QUIT 27: LATE BIAS SLAY FOLK MUCH TRIG 28: SALT TIN ANTI LOON NEAL USE 29: RIO ODIN GO BYE FURY TIC 30: GREW JIVE SAN GIRD BOIL PHI The requests five keys in sequence, and specifies what the last iteration number should be. Note that these are printed out in reverse order of use. The really paranoid might want to write the results down by hand; otherwise, print the list. Each line shows both the iteration count and the one-time password. Scratch off the passwords as they are used. Restricting Use of &unix; Passwords OPIE can restrict the use of &unix; passwords based on the IP address of a login session. The relevant file is /etc/opieaccess, which is present by default. Refer to &man.opieaccess.5; for more information on this file and which security considerations to be aware of when using it. Here is a sample opieaccess: permit 192.168.0.0 255.255.0.0 This line allows users whose IP source address (which is vulnerable to spoofing) matches the specified value and mask, to use &unix; passwords at any time. If no rules in opieaccess are matched, the default is to deny non-OPIE logins. TCP Wrapper TomRhodesWritten by TCP Wrapper TCP Wrapper is a host-based access control system which extends the abilities of . It can be configured to provide logging support, return messages, and connection restrictions for the server daemons under the control of inetd. Refer to &man.tcpd.8; for more information about TCP Wrapper and its features. TCP Wrapper should not be considered a replacement for a properly configured firewall. Instead, TCP Wrapper should be used in conjunction with a firewall and other security enhancements in order to provide another layer of protection in the implementation of a security policy. Initial Configuration To enable TCP Wrapper in &os;, add the following lines to /etc/rc.conf: inetd_enable="YES" inetd_flags="-Ww" Then, properly configure /etc/hosts.allow. Unlike other implementations of TCP Wrapper, the use of hosts.deny is deprecated in &os;. All configuration options should be placed in /etc/hosts.allow. In the simplest configuration, daemon connection policies are set to either permit or block, depending on the options in /etc/hosts.allow. The default configuration in &os; is to allow all connections to the daemons started with inetd. Basic configuration usually takes the form of daemon : address : action, where daemon is the daemon which inetd started, address is a valid hostname, IP address, or an IPv6 address enclosed in brackets ([ ]), and action is either allow or deny. TCP Wrapper uses a first rule match semantic, meaning that the configuration file is scanned from the beginning for a matching rule. When a match is found, the rule is applied and the search process stops. For example, to allow POP3 connections via the mail/qpopper daemon, the following lines should be appended to hosts.allow: # This line is required for POP3 connections: qpopper : ALL : allow Whenever this file is edited, restart inetd: &prompt.root; service inetd restart Advanced Configuration TCP Wrapper provides advanced options to allow more control over the way connections are handled. In some cases, it may be appropriate to return a comment to certain hosts or daemon connections. In other cases, a log entry should be recorded or an email sent to the administrator. Other situations may require the use of a service for local connections only. This is all possible through the use of configuration options known as wildcards, expansion characters, and external command execution. Suppose that a situation occurs where a connection should be denied yet a reason should be sent to the host who attempted to establish that connection. That action is possible with . When a connection attempt is made, executes a shell command or script. An example exists in hosts.allow: # The rest of the daemons are protected. ALL : ALL \ : severity auth.info \ : twist /bin/echo "You are not welcome to use %d from %h." In this example, the message You are not allowed to use daemon name from hostname. will be returned for any daemon not configured in hosts.allow. This is useful for sending a reply back to the connection initiator right after the established connection is dropped. Any message returned must be wrapped in quote (") characters. It may be possible to launch a denial of service attack on the server if an attacker floods these daemons with connection requests. Another possibility is to use . Like , implicitly denies the connection and may be used to run external shell commands or scripts. Unlike , will not send a reply back to the host who established the connection. For example, consider the following configuration: # We do not allow connections from example.com: ALL : .example.com \ : spawn (/bin/echo %a from %h attempted to access %d >> \ /var/log/connections.log) \ : deny This will deny all connection attempts from *.example.com and log the hostname, IP address, and the daemon to which access was attempted to /var/log/connections.log. This example uses the substitution characters %a and %h. Refer to &man.hosts.access.5; for the complete list. To match every instance of a daemon, domain, or IP address, use ALL. Another wildcard is PARANOID which may be used to match any host which provides an IP address that may be forged because the IP address differs from its resolved hostname. In this example, all connection requests to Sendmail which have an IP address that varies from its hostname will be denied: # Block possibly spoofed requests to sendmail: sendmail : PARANOID : deny Using the PARANOID wildcard will result in denied connections if the client or server has a broken DNS setup. To learn more about wildcards and their associated functionality, refer to &man.hosts.access.5;. When adding new configuration lines, make sure that any unneeded entries for that daemon are commented out in hosts.allow. <application>Kerberos</application> TillmanHodgsonContributed by MarkMurrayBased on a contribution by Kerberos is a network authentication protocol which was originally created by the Massachusetts Institute of Technology (MIT) as a solution to network security problems. The Kerberos protocol uses strong cryptography so that both a client and server can prove their identity over an insecure network. Kerberos can be described as an identity-verifying proxy system and as a trusted third-party authentication system. After a user authenticates with Kerberos, their communications can be encrypted to assure privacy and data integrity. The only function of Kerberos is to provide the secure authentication of users on the network. It does not provide authorization or auditing functions. It is recommended that Kerberos be used with other security methods which provide authorization and audit services. The current version of the protocol is version 5, described in RFC 1510. Several free implementations of this protocol are available, covering a wide range of operating systems. MIT continues to develop their Kerberos package. It is commonly used in the US as a cryptography product, and has historically been affected by US export regulations. In &os;, MIT Kerberos is available as the security/krb5 package or port. Heimdal Kerberos was explicitly developed outside of the US to avoid export regulations. The Heimdal Kerberos distribution is available as the security/heimdal package or port, and a minimal installation is included in the base &os; install. This section provides a guide on how to set up Kerberos using the Heimdal distribution included in &os;. For purposes of demonstrating a Kerberos installation, the name spaces will be as follows: The DNS domain (zone) will be example.org. The Kerberos realm will be EXAMPLE.ORG. Use real domain names when setting up Kerberos, even if it will run internally. This avoids DNS problems and assures inter-operation with other Kerberos realms. Setting up a Heimdal <acronym>KDC</acronym> Kerberos5 Key Distribution Center The Key Distribution Center (KDC) is the centralized authentication service that Kerberos provides. It is the computer that issues Kerberos tickets. The KDC is considered trusted by all other computers in the Kerberos realm, and thus has heightened security concerns. While running a KDC requires few computing resources, a dedicated machine acting only as a KDC is recommended for security reasons. To begin setting up a KDC, add these lines to /etc/rc.conf: kerberos5_server_enable="YES" kadmind5_server_enable="YES" Next, edit /etc/krb5.conf as follows: [libdefaults] default_realm = EXAMPLE.ORG [realms] EXAMPLE.ORG = { kdc = kerberos.example.org admin_server = kerberos.example.org } [domain_realm] .example.org = EXAMPLE.ORG In this example, the KDC will use the fully-qualified hostname kerberos.example.org. Add a CNAME entry to the DNS zone file if the KDC has a different hostname than that specified in /etc/krb5.conf. For large networks with a properly configured DNS server, the above example could be trimmed to: [libdefaults] default_realm = EXAMPLE.ORG With the following lines being appended to the example.org zone file: _kerberos._udp IN SRV 01 00 88 kerberos.example.org. _kerberos._tcp IN SRV 01 00 88 kerberos.example.org. _kpasswd._udp IN SRV 01 00 464 kerberos.example.org. _kerberos-adm._tcp IN SRV 01 00 749 kerberos.example.org. _kerberos IN TXT EXAMPLE.ORG In order for clients to be able to find the Kerberos services, the KDC must have either a fully configured /etc/krb5.conf or a minimally configured /etc/krb5.conf and a properly configured DNS server. Next, create the Kerberos database which contains the keys of all principals (users and hosts) encrypted with a master password. It is not required to remember this password as it will be stored in /var/heimdal/m-key. To create the master key, run kstash and enter a password: &prompt.root; kstash Master key: xxxxxxxx Verifying password - Master key: xxxxxxxx Once the master key has been created, initialize the database using kadmin -l. This option instructs kadmin to modify the local database files directly rather than going through the &man.kadmind.8; network service. This handles the chicken-and-egg problem of trying to connect to the database before it is created. At the kadmin prompt, use init to create the realm's initial database: &prompt.root; kadmin -l kadmin> init EXAMPLE.ORG Realm max ticket life [unlimited]: Lastly, while still in kadmin, create the first principal using add. Stick to the default options for the principal for now, as these can be changed later with modify. Type ? at the prompt to see the available options. kadmin> add tillman Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: Password: xxxxxxxx Verifying password - Password: xxxxxxxx Next, start the KDC services by running service kerberos start and service kadmind start. While there will not be any kerberized daemons running at this point, it is possible to confirm that the KDC is functioning by obtaining and listing a ticket for the principal that was just created from the command-line of the KDC: &prompt.user; kinit tillman tillman@EXAMPLE.ORG's Password: &prompt.user; klist Credentials cache: FILE:/tmp/krb5cc_500 Principal: tillman@EXAMPLE.ORG Issued Expires Principal Aug 27 15:37:58 Aug 28 01:37:58 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG The temporary ticket can be revoked when the test is finished: &prompt.user; kdestroy Configuring a Server to Use <application>Kerberos</application> Kerberos5 enabling services To configure a server to use Kerberos authentication, copy /etc/krb5.conf from the KDC to the server in a secure fashion, such as &man.scp.1;, or physically via removable media. Next, create /etc/krb5.keytab on the server. This is the major difference between a server providing Kerberos enabled daemons and a workstation: the server must have a keytab. This file contains the server's host key, which allows it and the KDC to verify each others identity. It must be transmitted to the server in a secure fashion, as the security of the server can be broken if the key is made public. Typically, the keytab is transferred to the server using kadmin. This is handy because the host principal, the KDC end of the krb5.keytab, is also created using kadmin. A ticket must first be obtained and this ticket must be allowed to use the kadmin interface in the kadmind.acl. See the section titled Remote administration in info heimdal for details on designing access control lists. Instead of enabling remote kadmin access, the administrator can securely connect to the KDC via the local console or &man.ssh.1;, and perform administration locally using kadmin -l. After installing /etc/krb5.conf, use add --random-key from the Kerberos server. This adds the server's host principal. Then, use ext to extract the server's host principal to its own keytab: &prompt.root; kadmin kadmin> add --random-key host/myserver.example.org Max ticket life [unlimited]: Max renewable life [unlimited]: Attributes []: kadmin> ext host/myserver.example.org kadmin> exit Note that ext stores the extracted key in /etc/krb5.keytab by default. If &man.kadmind.8; is not running on the KDC and there is no access to &man.kadmin.8; remotely, add the server's host principal directly on the KDC and then extract it to a temporary file to avoid overwriting the /etc/krb5.keytab on the KDC: &prompt.root; kadmin kadmin> ext --keytab=/tmp/example.keytab host/myserver.example.org kadmin> exit The keytab can then be securely copied to the server using &man.scp.1; or a removable media. Be sure to specify a non-default keytab name to avoid overwriting the keytab on the KDC. At this point, the server can communicate with the KDC using krb5.conf and it can prove its own identity with krb5.keytab. It is now ready for the Kerberos services to be enabled. For this example, the &man.telnetd.8; service is enabled in /etc/inetd.conf and &man.inetd.8; has been restarted with service inetd restart: telnet stream tcp nowait root /usr/libexec/telnetd telnetd -a user The critical change is that the authentication type is set to user. Refer to &man.telnetd.8; for more details. Configuring a Client to Use <application>Kerberos</application> Kerberos5 configure clients To configure a client to use Kerberos, securely copy /etc/krb5.conf to the client computer from the KDC. Test the client by using kinit, klist, and kdestroy from the client to obtain, show, and then delete an existing ticket for the principal. Kerberos applications should also be able to connect to Kerberos enabled servers. If that does not work but obtaining a ticket does, the problem is likely with the server and not with the client or the KDC. When testing a Kerberized application, try using a packet sniffer such as tcpdump to confirm that the password is not sent in the clear. Various Kerberos client applications are available. &os; installs telnetd as the only Kerberos enabled service. The Heimdal package or port installs Kerberos enabled versions of ftpd, rshd, rcp, rlogind, and a few other less common programs. The MIT port contains a full suite of Kerberos client applications. .k5login .k5users Users within a realm typically have their Kerberos principal mapped to a local user account. Occasionally, one needs to grant access to a local user account to someone who does not have a matching Kerberos principal. For example, tillman@EXAMPLE.ORG may need access to the local user account webdevelopers. Other principals may also need access to that local account. The .k5login and .k5users files, placed in a user's home directory, can be used to solve this problem. For example, if the following .k5login is placed in the home directory of webdevelopers, both principals listed will have access to that account without requiring a shared password.: tillman@example.org jdoe@example.org Refer to &man.ksu.1; for more information about .k5users. <acronym>MIT</acronym> Differences The major difference between the MIT and Heimdal implementations is that kadmin has a different, but equivalent, set of commands and uses a different protocol. If the KDC is MIT, the Heimdal version of kadmin cannot be used to administer the KDC remotely, and vice versa. Client applications may also use slightly different command line options to accomplish the same tasks. Following the instructions at http://web.mit.edu/Kerberos/www/ is recommended. Be careful of path issues: the MIT port installs into /usr/local/ by default, and the &os; system applications run instead of the MIT versions if PATH lists the system directories first. With the &os; MIT security/krb5 port, be sure to read /usr/local/share/doc/krb5/README.FreeBSD installed by the port to understand why logins via telnetd and klogind behave somewhat oddly. Correcting the incorrect permissions on cache file behavior requires that the login.krb5 binary be used for authentication so that it can properly change ownership for the forwarded credentials. The following edits should also be made to rc.conf: kerberos5_server="/usr/local/sbin/krb5kdc" kadmind5_server="/usr/local/sbin/kadmind" kerberos5_server_flags="" kerberos5_server_enable="YES" kadmind5_server_enable="YES" <application>Kerberos</application> Tips, Tricks, and Troubleshooting When configuring and troubleshooting Kerberos, keep the following points in mind: When using either Heimdal or MIT Kerberos, ensure that the PATH lists the Kerberos versions of the client applications before the system versions. If all the computers in the realm do not have synchronized time settings, authentication may fail. describes how to synchronize clocks using NTP. If the hostname is changed, the host/ principal must be changed and the keytab updated. This also applies to special keytab entries like the www/ principal used for Apache's www/mod_auth_kerb. All hosts in the realm must be both forward and reverse resolvable in DNS or, at a minimum, exist in /etc/hosts. CNAMEs will work, but the A and PTR records must be correct and in place. The error message for unresolvable hosts is not intuitive: Kerberos5 refuses authentication because Read req failed: Key table entry not found. Some operating systems that act as clients to the KDC do not set the permissions for ksu to be setuid root. This means that ksu does not work. This is a permissions problem, not a KDC error. With MIT Kerberos, to allow a principal to have a ticket life longer than the default ten hours, use modify_principal at the &man.kadmin.8; prompt to change the maxlife of both the principal in question and the krbtgt principal. The principal can then use kinit -l to request a ticket with a longer lifetime. When running a packet sniffer on the KDC to aid in troubleshooting while running kinit from a workstation, the Ticket Granting Ticket (TGT) is sent immediately, even before the password is typed. This is because the Kerberos server freely transmits a TGT to any unauthorized request. However, every TGT is encrypted in a key derived from the user's password. When a user types their password, it is not sent to the KDC, it is instead used to decrypt the TGT that kinit already obtained. If the decryption process results in a valid ticket with a valid time stamp, the user has valid Kerberos credentials. These credentials include a session key for establishing secure communications with the Kerberos server in the future, as well as the actual TGT, which is encrypted with the Kerberos server's own key. This second layer of encryption allows the Kerberos server to verify the authenticity of each TGT. To use long ticket lifetimes when using OpenSSH to connect to the machine where the ticket is stored, make sure that Kerberos is set to no in /etc/ssh/sshd_config. Otherwise, tickets will be deleted at log out. Host principals can have a longer ticket lifetime. If the user principal has a lifetime of a week but the host being connected to has a lifetime of nine hours, the user cache will have an expired host principal and the ticket cache will not work as expected. When setting up krb5.dict to prevent specific bad passwords from being used as described in &man.kadmind.8;, remember that it only applies to principals that have a password policy assigned to them. The format used in krb5.dict is one string per line. Creating a symbolic link to /usr/share/dict/words might be useful. Mitigating <application>Kerberos</application> Limitations Kerberos5 limitations and shortcomings Since Kerberos is an all or nothing approach, every service enabled on the network must either be modified to work with Kerberos or be otherwise secured against network attacks. This is to prevent user credentials from being stolen and re-used. An example is when Kerberos is enabled on all remote shells but the non-Kerberized POP3 mail server sends passwords in plain text. Kerberos is intended for single-user workstations. In a multi-user environment, Kerberos is less secure as it stores the tickets in /tmp, which is readable by all users. If a user is sharing a computer, it is possible that the user's tickets can be stolen or copied by another user. This can be overcome with kinit -c or, preferably, the KRB5CCNAME environment variable. Storing the ticket in the user's home directory and using file permissions are commonly used to mitigate this problem. The KDC is a single point of failure. By design, the KDC must be as secure as its master password database. The KDC should have absolutely no other services running on it and should be physically secure. The danger is high because Kerberos stores all passwords encrypted with the same master key which is stored as a file on the KDC. A compromised master key is not quite as bad as one might fear. The master key is only used to encrypt the Kerberos database and as a seed for the random number generator. As long as access to the KDC is secure, an attacker cannot do much with the master key. If the KDC is unavailable, network services are unusable as authentication cannot be performed. This can be alleviated with a single master KDC and one or more slaves, and with careful implementation of secondary or fall-back authentication using PAM. Kerberos allows users, hosts and services to authenticate between themselves. It does not have a mechanism to authenticate the KDC to the users, hosts, or services. This means that a trojanned kinit could record all user names and passwords. File system integrity checking tools like security/tripwire can alleviate this. Access Issues with Kerberos and <command>ssh</command> &man.ssh.1; Kerberos is an excellent authentication protocol, but there are bugs in the Kerberized versions of telnet and rlogin that make them unsuitable for dealing with binary streams. By default, Kerberos does not encrypt a session unless is used, whereas ssh encrypts everything. While ssh works well, it forwards encryption keys by default. This introduces a security risk to a user who uses ssh to access an insecure machine from a secure workstation. The keys themselves are not exposed, but ssh installs a forwarding port for the duration of the login. If an attacker has broken root on the insecure machine, he can utilize that port to gain access to any other machine that those keys unlock. It is recommended that ssh is used in combination with Kerberos whenever possible for staff logins as it can be compiled with Kerberos support. This reduces reliance on potentially exposed SSH keys while protecting passwords via Kerberos. Keys should only be used for automated tasks from secure machines as this is something that Kerberos is unsuited to. It is recommended to either turn off key-forwarding in the SSH configuration, or to make use of from=IP/DOMAIN in authorized_keys to make the key only usable to entities logging in from specific machines. Resources and Further Information Kerberos5 external resources The Kerberos FAQ Designing an Authentication System: a Dialog in Four Scenes RFC 1510, The Kerberos Network Authentication Service (V5) MIT Kerberos home page Heimdal Kerberos home page OpenSSL TomRhodesWritten by security OpenSSL OpenSSL is an open source implementation of the SSL and TLS protocols. It provides an encryption transport layer on top of the normal communications layer, allowing it to be intertwined with many network applications and services. The version of OpenSSL included in &os; supports the Secure Sockets Layer v2/v3 (SSLv2/SSLv3) and Transport Layer Security v1 (TLSv1) network security protocols and can be used as a general cryptographic library. OpenSSL is often used to encrypt authentication of mail clients and to secure web based transactions such as credit card payments. Some ports, such as www/apache24 and databases/postgresql91-server, include a compile option for building with OpenSSL. If selected, the port will add support using the security/openssl port. To instead have the port compile against the built in version of OpenSSL, include WITH_OPENSSL_BASE when compiling in OpenSSL support. Another common use of OpenSSL is to provide certificates for use with software applications. Certificates can be used to verify the credentials of a company or individual. If a certificate has not been signed by an external Certificate Authority (CA), such as http://www.verisign.com, the application that uses the certificate will produce a warning. There is a cost associated with obtaining a signed certificate and using a signed certificate is not mandatory as certificates can be self-signed. However, using an external authority will prevent warnings and can put users at ease. This section demonstrates how to create and use certificates on a &os; system. Refer to for an example of how to create a CA for signing one's own certificates. Generating Certificates OpenSSL certificate generation To generate a certificate that will be signed by an external CA, issue the following command and input the information requested at the prompts. This input information will be written to the certificate. At the Common Name prompt, input the fully qualified name for the system that will use the certificate. If this name does not match the server, the application verifying the certificate will issue a warning to the user, rendering the verification provided by the certificate as useless. &prompt.root; openssl req -new -nodes -out req.pem -keyout cert.pem Generating a 1024 bit RSA private key ................++++++ .......................................++++++ writing new private key to 'cert.pem' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:PA Locality Name (eg, city) []:Pittsburgh Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company Organizational Unit Name (eg, section) []:Systems Administrator Common Name (eg, YOUR name) []:localhost.example.org Email Address []:trhodes@FreeBSD.org Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:SOME PASSWORD An optional company name []:Another Name Other options, such as the expire time and alternate encryption algorithms, are available when creating a certificate. A complete list of options is described in &man.openssl.1;. This command will create two files in the current directory. The certificate request, req.pem, can be sent to a CA who will validate the entered credentials, sign the request, and return the signed certificate. The second file, cert.pem, is the private key for the certificate and should be stored in a secure location. If this falls in the hands of others, it can be used to impersonate the user or the server. Alternately, if a signature from a CA is not required, a self-signed certificate can be created. First, generate the RSA key: &prompt.root; openssl dsaparam -rand -genkey -out myRSA.key 1024 0 semi-random bytes loaded Generating DSA parameters, 1024 bit long prime This could take some time .............+........+...........+...+....+........+.....+++++++++++++++++++++++++++++++++++++++++++++++++++* ..........+.+...........+....+........+.................+.+++++++++++++++++++++++++++++++++++++++++++++++++++* Next, generate the CA key. When prompted, enter a passphrase between 4 to 1023 characters. Remember this passphrase as it is needed whenever the key is used to sign a certificate. &prompt.root; openssl gendsa -des3 -out myca.key myRSA.key Generating DSA key, 1024 bits Enter PEM pass phrase: Verifying - Enter PEM pass phrase: Use this key to create a self-signed certificate. When prompted, enter the passphrase. Then follow the usual prompts for creating a certificate: &prompt.root; openssl req -new -x509 -days 365 -key myca.key -out new.crt Enter pass phrase for myca.key: You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:PA Locality Name (eg, city) []:Pittsburgh Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company Organizational Unit Name (eg, section) []:Systems Administrator Common Name (e.g. server FQDN or YOUR name) []:localhost.example.org Email Address []:trhodes@FreeBSD.org This will create two new files in the current directory: a certificate authority signature file, myca.key, and the certificate itself, new.crt. These should be placed in a directory, preferably under /etc, which is readable only by root. Permissions of 0700 are appropriate for these files and can be set using chmod. Using Certificates One use for a certificate is to encrypt connections to the Sendmail mail server in order to prevent the use of clear text authentication. Some mail clients will display an error if the user has not installed a local copy of the certificate. Refer to the documentation included with the software for more information on certificate installation. To configure Sendmail, add the following lines to /etc/rc.conf: sendmail_enable="YES" sendmail_cert_create="YES" sendmail_cert_cn="localhost.example.org" This will automatically create a self-signed certificate, /etc/mail/certs/host.cert, a signing key, /etc/mail/certs/host.key, and a CA certificate, /etc/mail/certs/cacert.pem. The certificate will use the Common Name specified in . After saving the edits, restart Sendmail: &prompt.root; service sendmail restart If all went well, there will be no error messages in /var/log/maillog. For a simple test, connect to the mail server's listening port using telnet: &prompt.root; telnet example.com 25 Trying 192.0.34.166... Connected to example.com. Escape character is '^]'. 220 example.com ESMTP Sendmail 8.14.7/8.14.7; Fri, 18 Apr 2014 11:50:32 -0400 (EDT) ehlo example.com 250-example.com Hello example.com [192.0.34.166], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-AUTH LOGIN PLAIN 250-STARTTLS 250-DELIVERBY 250 HELP quit 221 2.0.0 example.com closing connection Connection closed by foreign host. If the STARTTLS line appears in the output, everything is working correctly. <acronym>VPN</acronym> over <acronym>IPsec</acronym> NikClayton
nik@FreeBSD.org
Written by
Hiten M.Pandya
hmp@FreeBSD.org
Written by
IPsec Internet Protocol Security (IPsec) is a set of protocols which sit on top of the Internet Protocol (IP) layer. It allows two or more hosts to communicate in a secure manner by authenticating and encrypting each IP packet of a communication session. The &os; IPsec network stack is based on the http://www.kame.net/ implementation and supports both IPv4 and IPv6 sessions. IPsec ESP IPsec AH IPsec is comprised of the following sub-protocols: Encapsulated Security Payload (ESP): this protocol protects the IP packet data from third party interference by encrypting the contents using symmetric cryptography algorithms such as Blowfish and 3DES. Authentication Header (AH)): this protocol protects the IP packet header from third party interference and spoofing by computing a cryptographic checksum and hashing the IP packet header fields with a secure hashing function. This is then followed by an additional header that contains the hash, to allow the information in the packet to be authenticated. IP Payload Compression Protocol (IPComp): this protocol tries to increase communication performance by compressing the IP payload in order ro reduce the amount of data sent. These protocols can either be used together or separately, depending on the environment. VPN virtual private network VPN IPsec supports two modes of operation. The first mode, Transport Mode, protects communications between two hosts. The second mode, Tunnel Mode, is used to build virtual tunnels, commonly known as Virtual Private Networks (VPNs). Consult &man.ipsec.4; for detailed information on the IPsec subsystem in &os;. To add IPsec support to the kernel, add the following options to the custom kernel configuration file and rebuild the kernel using the instructions in : kernel options IPSEC options IPSEC #IP security device crypto kernel options IPSEC_DEBUG If IPsec debugging support is desired, the following kernel option should also be added: options IPSEC_DEBUG #debug for IP security This rest of this chapter demonstrates the process of setting up an IPsec VPN between a home network and a corporate network. In the example scenario: Both sites are connected to the Internet through a gateway that is running &os;. The gateway on each network has at least one external IP address. In this example, the corporate LAN's external IP address is 172.16.5.4 and the home LAN's external IP address is 192.168.1.12. The internal addresses of the two networks can be either public or private IP addresses. However, the address space must not collide. For example, both networks cannot use 192.168.1.x. In this example, the corporate LAN's internal IP address is 10.246.38.1 and the home LAN's internal IP address is 10.0.0.5. Configuring a <acronym>VPN</acronym> on &os; TomRhodes
trhodes@FreeBSD.org
Written by
To begin, security/ipsec-tools must be installed from the Ports Collection. This software provides a number of applications which support the configuration. The next requirement is to create two &man.gif.4; pseudo-devices which will be used to tunnel packets and allow both networks to communicate properly. As root, run the following commands, replacing internal and external with the real IP addresses of the internal and external interfaces of the two gateways: &prompt.root; ifconfig gif0 create &prompt.root; ifconfig gif0 internal1 internal2 &prompt.root; ifconfig gif0 tunnel external1 external2 Verify the setup on each gateway, using ifconfig. Here is the output from Gateway 1: gif0: flags=8051 mtu 1280 tunnel inet 172.16.5.4 --> 192.168.1.12 inet6 fe80::2e0:81ff:fe02:5881%gif0 prefixlen 64 scopeid 0x6 inet 10.246.38.1 --> 10.0.0.5 netmask 0xffffff00 Here is the output from Gateway 2: gif0: flags=8051 mtu 1280 tunnel inet 192.168.1.12 --> 172.16.5.4 inet 10.0.0.5 --> 10.246.38.1 netmask 0xffffff00 inet6 fe80::250:bfff:fe3a:c1f%gif0 prefixlen 64 scopeid 0x4 Once complete, both internal IP addresses should be reachable using &man.ping.8;: priv-net# ping 10.0.0.5 PING 10.0.0.5 (10.0.0.5): 56 data bytes 64 bytes from 10.0.0.5: icmp_seq=0 ttl=64 time=42.786 ms 64 bytes from 10.0.0.5: icmp_seq=1 ttl=64 time=19.255 ms 64 bytes from 10.0.0.5: icmp_seq=2 ttl=64 time=20.440 ms 64 bytes from 10.0.0.5: icmp_seq=3 ttl=64 time=21.036 ms --- 10.0.0.5 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max/stddev = 19.255/25.879/42.786/9.782 ms corp-net# ping 10.246.38.1 PING 10.246.38.1 (10.246.38.1): 56 data bytes 64 bytes from 10.246.38.1: icmp_seq=0 ttl=64 time=28.106 ms 64 bytes from 10.246.38.1: icmp_seq=1 ttl=64 time=42.917 ms 64 bytes from 10.246.38.1: icmp_seq=2 ttl=64 time=127.525 ms 64 bytes from 10.246.38.1: icmp_seq=3 ttl=64 time=119.896 ms 64 bytes from 10.246.38.1: icmp_seq=4 ttl=64 time=154.524 ms --- 10.246.38.1 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 28.106/94.594/154.524/49.814 ms As expected, both sides have the ability to send and receive ICMP packets from the privately configured addresses. Next, both gateways must be told how to route packets in order to correctly send traffic from either network. The following commands will achieve this goal: &prompt.root; corp-net# route add 10.0.0.0 10.0.0.5 255.255.255.0 &prompt.root; corp-net# route add net 10.0.0.0: gateway 10.0.0.5 &prompt.root; priv-net# route add 10.246.38.0 10.246.38.1 255.255.255.0 &prompt.root; priv-net# route add host 10.246.38.0: gateway 10.246.38.1 At this point, internal machines should be reachable from each gateway as well as from machines behind the gateways. Again, use &man.ping.8; to confirm: corp-net# ping 10.0.0.8 PING 10.0.0.8 (10.0.0.8): 56 data bytes 64 bytes from 10.0.0.8: icmp_seq=0 ttl=63 time=92.391 ms 64 bytes from 10.0.0.8: icmp_seq=1 ttl=63 time=21.870 ms 64 bytes from 10.0.0.8: icmp_seq=2 ttl=63 time=198.022 ms 64 bytes from 10.0.0.8: icmp_seq=3 ttl=63 time=22.241 ms 64 bytes from 10.0.0.8: icmp_seq=4 ttl=63 time=174.705 ms --- 10.0.0.8 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.870/101.846/198.022/74.001 ms priv-net# ping 10.246.38.107 PING 10.246.38.1 (10.246.38.107): 56 data bytes 64 bytes from 10.246.38.107: icmp_seq=0 ttl=64 time=53.491 ms 64 bytes from 10.246.38.107: icmp_seq=1 ttl=64 time=23.395 ms 64 bytes from 10.246.38.107: icmp_seq=2 ttl=64 time=23.865 ms 64 bytes from 10.246.38.107: icmp_seq=3 ttl=64 time=21.145 ms 64 bytes from 10.246.38.107: icmp_seq=4 ttl=64 time=36.708 ms --- 10.246.38.107 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.145/31.721/53.491/12.179 ms Setting up the tunnels is the easy part. Configuring a secure link is a more in depth process. The following configuration uses pre-shared (PSK) RSA keys. Other than the IP addresses, the /usr/local/etc/racoon/racoon.conf on both gateways will be identical and look similar to: path pre_shared_key "/usr/local/etc/racoon/psk.txt"; #location of pre-shared key file log debug; #log verbosity setting: set to 'notify' when testing and debugging is complete padding # options are not to be changed { maximum_length 20; randomize off; strict_check off; exclusive_tail off; } timer # timing options. change as needed { counter 5; interval 20 sec; persend 1; # natt_keepalive 15 sec; phase1 30 sec; phase2 15 sec; } listen # address [port] that racoon will listen on { isakmp 172.16.5.4 [500]; isakmp_natt 172.16.5.4 [4500]; } remote 192.168.1.12 [500] { exchange_mode main,aggressive; doi ipsec_doi; situation identity_only; my_identifier address 172.16.5.4; peers_identifier address 192.168.1.12; lifetime time 8 hour; passive off; proposal_check obey; # nat_traversal off; generate_policy off; proposal { encryption_algorithm blowfish; hash_algorithm md5; authentication_method pre_shared_key; lifetime time 30 sec; dh_group 1; } } sainfo (address 10.246.38.0/24 any address 10.0.0.0/24 any) # address $network/$netmask $type address $network/$netmask $type ( $type being any or esp) { # $network must be the two internal networks you are joining. pfs_group 1; lifetime time 36000 sec; encryption_algorithm blowfish,3des,des; authentication_algorithm hmac_md5,hmac_sha1; compression_algorithm deflate; } For descriptions of each available option, refer to the manual page for racoon.conf. The Security Policy Database (SPD) needs to be configured so that &os; and racoon are able to encrypt and decrypt network traffic between the hosts. This can be achieved with a shell script, similar to the following, on the corporate gateway. This file will be used during system initialization and should be saved as /usr/local/etc/racoon/setkey.conf. flush; spdflush; # To the home network spdadd 10.246.38.0/24 10.0.0.0/24 any -P out ipsec esp/tunnel/172.16.5.4-192.168.1.12/use; spdadd 10.0.0.0/24 10.246.38.0/24 any -P in ipsec esp/tunnel/192.168.1.12-172.16.5.4/use; Once in place, racoon may be started on both gateways using the following command: &prompt.root; /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf -l /var/log/racoon.log The output should be similar to the following: corp-net# /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf Foreground mode. 2006-01-30 01:35:47: INFO: begin Identity Protection mode. 2006-01-30 01:35:48: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:35:55: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:36:04: INFO: ISAKMP-SA established 172.16.5.4[500]-192.168.1.12[500] spi:623b9b3bd2492452:7deab82d54ff704a 2006-01-30 01:36:05: INFO: initiate new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=28496098(0x1b2d0e2) 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=47784998(0x2d92426) 2006-01-30 01:36:13: INFO: respond new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=124397467(0x76a279b) 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=175852902(0xa7b4d66) To ensure the tunnel is working properly, switch to another console and use &man.tcpdump.1; to view network traffic using the following command. Replace em0 with the network interface card as required: &prompt.root; tcpdump -i em0 host 172.16.5.4 and dst 192.168.1.12 Data similar to the following should appear on the console. If not, there is an issue and debugging the returned data will be required. 01:47:32.021683 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xa) 01:47:33.022442 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xb) 01:47:34.024218 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xc) At this point, both networks should be available and seem to be part of the same network. Most likely both networks are protected by a firewall. To allow traffic to flow between them, rules need to be added to pass packets. For the &man.ipfw.8; firewall, add the following lines to the firewall configuration file: ipfw add 00201 allow log esp from any to any ipfw add 00202 allow log ah from any to any ipfw add 00203 allow log ipencap from any to any ipfw add 00204 allow log udp from any 500 to any The rule numbers may need to be altered depending on the current host configuration. For users of &man.pf.4; or &man.ipf.8;, the following rules should do the trick: pass in quick proto esp from any to any pass in quick proto ah from any to any pass in quick proto ipencap from any to any pass in quick proto udp from any port = 500 to any port = 500 pass in quick on gif0 from any to any pass out quick proto esp from any to any pass out quick proto ah from any to any pass out quick proto ipencap from any to any pass out quick proto udp from any port = 500 to any port = 500 pass out quick on gif0 from any to any Finally, to allow the machine to start support for the VPN during system initialization, add the following lines to /etc/rc.conf: ipsec_enable="YES" ipsec_program="/usr/local/sbin/setkey" ipsec_file="/usr/local/etc/racoon/setkey.conf" # allows setting up spd policies on boot racoon_enable="yes"
OpenSSH ChernLeeContributed by OpenSSH security OpenSSH OpenSSH is a set of network connectivity tools used to provide secure access to remote machines. Additionally, TCP/IP connections can be tunneled or forwarded securely through SSH connections. OpenSSH encrypts all traffic to effectively eliminate eavesdropping, connection hijacking, and other network-level attacks. OpenSSH is maintained by the OpenBSD project and is installed by default in &os;. It is compatible with both SSH version 1 and 2 protocols. When data is sent over the network in an unencrypted form, network sniffers anywhere in between the client and server can steal user/password information or data transferred during the session. OpenSSH offers a variety of authentication and encryption methods to prevent this from happening. More information about OpenSSH is available from http://www.openssh.com/. This section provides an overview of the built-in client utilities to securely access other systems and securely transfer files from a &os; system. It then describes how to configure a SSH server on a &os; system. More information is available in the man pages mentioned in this chapter. Using the SSH Client Utilities OpenSSH client To log into a SSH server, use ssh and specify a username that exists on that server and the IP address or hostname of the server. If this is the first time a connection has been made to the specified server, the user will be prompted to first verify the server's fingerprint: &prompt.root; ssh user@example.com The authenticity of host 'example.com (10.0.0.1)' can't be established. ECDSA key fingerprint is 25:cc:73:b5:b3:96:75:3d:56:19:49:d2:5c:1f:91:3b. Are you sure you want to continue connecting (yes/no)? yes Permanently added 'example.com' (ECDSA) to the list of known hosts. Password for user@example.com: user_password SSH utilizes a key fingerprint system to verify the authenticity of the server when the client connects. When the user accepts the key's fingerprint by typing yes when connecting for the first time, a copy of the key is saved to .ssh/known_hosts in the user's home directory. Future attempts to login are verified against the saved key and ssh will display an alert if the server's key does not match the saved key. If this occurs, the user should first verify why the key has changed before continuing with the connection. By default, recent versions of OpenSSH only accept SSHv2 connections. By default, the client will use version 2 if possible and will fall back to version 1 if the server does not support version 2. To force ssh to only use the specified protocol, include or . Additional options are described in &man.ssh.1;. OpenSSH secure copy &man.scp.1; Use &man.scp.1; to securely copy a file to or from a remote machine. This example copies COPYRIGHT on the remote system to a file of the same name in the current directory of the local system: &prompt.root; scp user@example.com:/COPYRIGHT COPYRIGHT Password for user@example.com: ******* COPYRIGHT 100% |*****************************| 4735 00:00 &prompt.root; Since the fingerprint was already verified for this host, the server's key is automatically checked before prompting for the user's password. The arguments passed to scp are similar to cp. The file or files to copy is the first argument and the destination to copy to is the second. Since the file is fetched over the network, one or more of the file arguments takes the form . Be aware when copying directories recursively that scp uses , whereas cp uses . To open an interactive session for copying files, use sftp. Refer to &man.sftp.1; for a list of available commands while in an sftp session. Key-based Authentication Instead of using passwords, a client can be configured to connect to the remote machine using keys. To generate DSA or RSA authentication keys, use ssh-keygen. To generate a public and private key pair, specify the type of key and follow the prompts. It is recommended to protect the keys with a memorable, but hard to guess passphrase. &prompt.user; ssh-keygen -t dsa Generating public/private dsa key pair. Enter file in which to save the key (/home/user/.ssh/id_dsa): Created directory '/home/user/.ssh'. Enter passphrase (empty for no passphrase): type some passphrase here which can contain spaces Enter same passphrase again: type some passphrase here which can contain spaces Your identification has been saved in /home/user/.ssh/id_dsa. Your public key has been saved in /home/user/.ssh/id_dsa.pub. The key fingerprint is: bb:48:db:f2:93:57:80:b6:aa:bc:f5:d5:ba:8f:79:17 user@host.example.com Depending upon the specified protocol, the private key is stored in ~/.ssh/id_dsa (or ~/.ssh/id_rsa), and the public key is stored in ~/.ssh/id_dsa.pub (or ~/.ssh/id_rsa.pub). The public key must be first copied to ~/.ssh/authorized_keys on the remote machine in order for key-based authentication to work. Many users believe that keys are secure by design and will use a key without a passphrase. This is dangerous behavior. An administrator can verify that a key pair is protected by a passphrase by viewing the private key manually. If the private key file contains the word ENCRYPTED, the key owner is using a passphrase. In addition, to better secure end users, from may be placed in the public key file. For example, adding from="192.168.10.5" in the front of ssh-rsa or rsa-dsa prefix will only allow that specific user to login from that IP address. The various options and files can be different according to the OpenSSH version. To avoid problems, consult &man.ssh-keygen.1;. If a passphrase is used, the user will be prompted for the passphrase each time a connection is made to the server. To load SSH keys into memory, without needing to type the passphrase each time, use &man.ssh-agent.1; and &man.ssh-add.1;. Authentication is handled by ssh-agent, using the private key(s) that are loaded into it. Then, ssh-agent should be used to launch another application such as a shell or a window manager. To use ssh-agent in a shell, start it with a shell as an argument. Next, add the identity by running ssh-add and providing it the passphrase for the private key. Once these steps have been completed, the user will be able to ssh to any host that has the corresponding public key installed. For example: &prompt.user; ssh-agent csh &prompt.user; ssh-add Enter passphrase for key '/usr/home/user/.ssh/id_dsa': type passphrase here Identity added: /usr/home/user/.ssh/id_dsa (/usr/home/user/.ssh/id_dsa) &prompt.user; To use ssh-agent in &xorg;, add an entry for it in ~/.xinitrc. This provides the ssh-agent services to all programs launched in &xorg;. An example ~/.xinitrc might look like this: exec ssh-agent startxfce4 This launches ssh-agent, which in turn launches XFCE, every time &xorg; starts. Once &xorg; has been restarted so that the changes can take effect, run ssh-add to load all of the SSH keys. <acronym>SSH</acronym> Tunneling OpenSSH tunneling OpenSSH has the ability to create a tunnel to encapsulate another protocol in an encrypted session. The following command tells ssh to create a tunnel for telnet: &prompt.user; ssh -2 -N -f -L 5023:localhost:23 user@foo.example.com &prompt.user; This example uses the following options: Forces ssh to use version 2 to connect to the server. Indicates no command, or tunnel only. If omitted, ssh initiates a normal session. Forces ssh to run in the background. Indicates a local tunnel in localport:remotehost:remoteport format. The login name to use on the specified remote SSH server. An SSH tunnel works by creating a listen socket on localhost on the specified localport. It then forwards any connections received on localport via the SSH connection to the specified remotehost:remoteport. In the example, port 5023 on the client is forwarded to port 23 on the remote machine. Since port 23 is used by telnet, this creates an encrypted telnet session through an SSH tunnel. This method can be used to wrap any number of insecure TCP protocols such as SMTP, POP3, and FTP, as seen in the following examples. Create a Secure Tunnel for <acronym>SMTP</acronym> &prompt.user; ssh -2 -N -f -L 5025:localhost:25 user@mailserver.example.com user@mailserver.example.com's password: ***** &prompt.user; telnet localhost 5025 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 220 mailserver.example.com ESMTP This can be used in conjunction with ssh-keygen and additional user accounts to create a more seamless SSH tunneling environment. Keys can be used in place of typing a password, and the tunnels can be run as a separate user. Secure Access of a <acronym>POP3</acronym> Server In this example, there is an SSH server that accepts connections from the outside. On the same network resides a mail server running a POP3 server. To check email in a secure manner, create an SSH connection to the SSH server and tunnel through to the mail server: &prompt.user; ssh -2 -N -f -L 2110:mail.example.com:110 user@ssh-server.example.com user@ssh-server.example.com's password: ****** Once the tunnel is up and running, point the email client to send POP3 requests to localhost on port 2110. This connection will be forwarded securely across the tunnel to mail.example.com. Bypassing a Firewall Some firewalls filter both incoming and outgoing connections. For example, a firewall might limit access from remote machines to ports 22 and 80 to only allow SSH and web surfing. This prevents access to any other service which uses a port other than 22 or 80. The solution is to create an SSH connection to a machine outside of the network's firewall and use it to tunnel to the desired service: &prompt.user; ssh -2 -N -f -L 8888:music.example.com:8000 user@unfirewalled-system.example.org user@unfirewalled-system.example.org's password: ******* In this example, a streaming Ogg Vorbis client can now be pointed to localhost port 8888, which will be forwarded over to music.example.com on port 8000, successfully bypassing the firewall. Enabling the SSH Server OpenSSH enabling In addition to providing built-in SSH client utilities, a &os; system can be configured as an SSH server, accepting connections from other SSH clients. To see if sshd is enabled, check /etc/rc.conf for this line and add it if it is missing: sshd_enable="YES" This will start sshd, the daemon program for OpenSSH, the next time the system boots. To start it now: &prompt.root; service sshd start The first time sshd starts on a &os; system, the system's host keys will be automatically created and the fingerprint will be displayed on the console. Provide users with the fingerprint so that they can verify it the first time they connect to the server. Refer to &man.sshd.8; for the list of available options when starting sshd and a more complete discussion about authentication, the login process, and the various configuration files. It is a good idea to limit which users can log into the SSH server and from where using the AllowUsers keyword in the OpenSSH server configuration file. For example, to only allow root to log in from 192.168.1.32, add this line to /etc/ssh/sshd_config: AllowUsers root@192.168.1.32 To allow admin to log in from anywhere, list that user without specifying an IP address: AllowUsers admin Multiple users should be listed on the same line, like so: AllowUsers root@192.168.1.32 admin After making changes to /etc/ssh/sshd_config, tell sshd to reload its configuration file by running: &prompt.root; service sshd reload When this keyword is used, it is important to list each user that needs to log into this machine. Any user that is not specified in that line will be locked out. Also, the keywords used in the OpenSSH server configuration file are case-sensitive. If the keyword is not spelled correctly, including its case, it will be ignored. Always test changes to this file to make sure that the edits are working as expected. Refer to &man.sshd.config.5; to verify the spelling and use of the available keywords. Do not confuse /etc/ssh/sshd_config with /etc/ssh/ssh_config (note the extra d in the first filename). The first file configures the server and the second file configures the client. Refer to &man.ssh.config.5; for a listing of the available client settings,. Access Control Lists TomRhodesContributed by ACL Access Control Lists (ACLs) extend the standard &unix; permission model in a &posix;.1e compatible way. This permits an administrator to take advantage of a more fine-grained permissions model. The &os; GENERIC kernel provides ACL support for UFS file systems. Users who prefer to compile a custom kernel must include the following option in their custom kernel configuration file: options UFS_ACL If this option is not compiled in, a warning message will be displayed when attempting to mount a file system with ACL support. ACLs rely on extended attributes which are natively supported in UFS2. This chapter describes how to enable ACL support and provides some usage examples. Enabling <acronym>ACL</acronym> Support ACLs are enabled by the mount-time administrative flag, , which may be added to /etc/fstab. The mount-time flag can also be automatically set in a persistent manner using &man.tunefs.8; to modify a superblock ACLs flag in the file system header. In general, it is preferred to use the superblock flag for several reasons: The superblock flag cannot be changed by a remount using as it requires a complete umount and fresh mount. This means that ACLs cannot be enabled on the root file system after boot. It also means that ACL support on a file system cannot be changed while the system is in use. Setting the superblock flag causes the file system to always be mounted with ACLs enabled, even if there is not an fstab entry or if the devices re-order. This prevents accidental mounting of the file system without ACL support. It is desirable to discourage accidental mounting without ACLs enabled because nasty things can happen if ACLs are enabled, then disabled, then re-enabled without flushing the extended attributes. In general, once ACLs are enabled on a file system, they should not be disabled, as the resulting file protections may not be compatible with those intended by the users of the system, and re-enabling ACLs may re-attach the previous ACLs to files that have since had their permissions changed, resulting in unpredictable behavior. File systems with ACLs enabled will show a plus (+) sign in their permission settings: drwx------ 2 robert robert 512 Dec 27 11:54 private drwxrwx---+ 2 robert robert 512 Dec 23 10:57 directory1 drwxrwx---+ 2 robert robert 512 Dec 22 10:20 directory2 drwxrwx---+ 2 robert robert 512 Dec 27 11:57 directory3 drwxr-xr-x 2 robert robert 512 Nov 10 11:54 public_html In this example, directory1, directory2, and directory3 are all taking advantage of ACLs, whereas public_html is not. Using <acronym>ACL</acronym>s File system ACLs can be viewed using getfacl. For instance, to view the ACL settings on test: &prompt.user; getfacl test #file:test #owner:1001 #group:1001 user::rw- group::r-- other::r-- To change the ACL settings on this file, use setfacl. To remove all of the currently defined ACLs from a file or file system, include . However, the preferred method is to use as it leaves the basic fields required for ACLs to work. &prompt.user; setfacl -k test To modify the default ACL entries, use : &prompt.user; setfacl -m u:trhodes:rwx,group:web:r--,o::--- test In this example, there were no pre-defined entries, as they were removed by the previous command. This command restores the default options and assigns the options listed. If a user or group is added which does not exist on the system, an Invalid argument error will be displayed. Refer to &man.getfacl.1; and &man.setfacl.1; for more information about the options available for these commands. Monitoring Third Party Security Issues TomRhodesContributed by portaudit In recent years, the security world has made many improvements to how vulnerability assessment is handled. The threat of system intrusion increases as third party utilities are installed and configured for virtually any operating system available today. Vulnerability assessment is a key factor in security. While &os; releases advisories for the base system, doing so for every third party utility is beyond the &os; Project's capability. There is a way to mitigate third party vulnerabilities and warn administrators of known security issues. A &os; add on utility known as portaudit exists solely for this purpose. The ports-mgmt/portaudit port polls a database, which is updated and maintained by the &os; Security Team and ports developers, for known security issues. To install portaudit from the Ports Collection: &prompt.root; cd /usr/ports/ports-mgmt/portaudit && make install clean During the installation, the configuration files for &man.periodic.8; will be updated, permitting portaudit output in the daily security runs. Ensure that the daily security run emails, which are sent to root's email account, are being read. No other configuration is required. After installation, an administrator can update the database and view known vulnerabilities in installed packages by invoking the following command: &prompt.root; portaudit -Fda The database is automatically updated during the &man.periodic.8; run. The above command is optional and can be used to manually update the database now. To audit the third party utilities installed as part of the Ports Collection at anytime, an administrator can run the following command: &prompt.root; portaudit -a portaudit will display messages for any installed vulnerable packages: Affected package: cups-base-1.1.22.0_1 Type of problem: cups-base -- HPGL buffer overflow vulnerability. Reference: <http://www.FreeBSD.org/ports/portaudit/40a3bca2-6809-11d9-a9e7-0001020eed82.html> 1 problem(s) in your installed packages found. You are advised to update or deinstall the affected package(s) immediately. By pointing a web browser to the displayed URL, an administrator may obtain more information about the vulnerability. This will include the versions affected, by &os; port version, along with other web sites which may contain security advisories. portaudit is a powerful utility and is extremely useful when coupled with the portmaster port. &os; Security Advisories TomRhodesContributed by &os; Security Advisories Like many producers of quality operating systems, the &os; Project has a security team which is responsible for determining the End-of-Life (EoL) date for each &os; release and to provide security updates for supported releases which have not yet reached their EoL. More information about the &os; security team and the supported releases is available on the &os; security page. One task of the security team is to respond to reported security vulnerabilities in the &os; operating system. Once a vulnerability is confirmed, the security team verifies the steps necessary to fix the vulnerability and updates the source code with the fix. It then publishes the details as a Security Advisory. Security advisories are published on the &os; website and mailed to the &a.security-notifications.name;, &a.security.name;, and &a.announce.name; mailing lists. This section describes the format of a &os; security advisory. Format of a Security Advisory Here is an example of a &os; security advisory: ============================================================================= -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 ============================================================================= FreeBSD-SA-14:04.bind Security Advisory The FreeBSD Project Topic: BIND remote denial of service vulnerability Category: contrib Module: bind Announced: 2014-01-14 Credits: ISC Affects: FreeBSD 8.x and FreeBSD 9.x Corrected: 2014-01-14 19:38:37 UTC (stable/9, 9.2-STABLE) 2014-01-14 19:42:28 UTC (releng/9.2, 9.2-RELEASE-p3) 2014-01-14 19:42:28 UTC (releng/9.1, 9.1-RELEASE-p10) 2014-01-14 19:38:37 UTC (stable/8, 8.4-STABLE) 2014-01-14 19:42:28 UTC (releng/8.4, 8.4-RELEASE-p7) 2014-01-14 19:42:28 UTC (releng/8.3, 8.3-RELEASE-p14) CVE Name: CVE-2014-0591 For general information regarding FreeBSD Security Advisories, including descriptions of the fields above, security branches, and the following sections, please visit <URL:http://security.FreeBSD.org/>. I. Background BIND 9 is an implementation of the Domain Name System (DNS) protocols. The named(8) daemon is an Internet Domain Name Server. II. Problem Description Because of a defect in handling queries for NSEC3-signed zones, BIND can crash with an "INSIST" failure in name.c when processing queries possessing certain properties. This issue only affects authoritative nameservers with at least one NSEC3-signed zone. Recursive-only servers are not at risk. III. Impact An attacker who can send a specially crafted query could cause named(8) to crash, resulting in a denial of service. IV. Workaround No workaround is available, but systems not running authoritative DNS service with at least one NSEC3-signed zone using named(8) are not vulnerable. V. Solution Perform one of the following: 1) Upgrade your vulnerable system to a supported FreeBSD stable or release / security branch (releng) dated after the correction date. 2) To update your vulnerable system via a source code patch: The following patches have been verified to apply to the applicable FreeBSD release branches. a) Download the relevant patch from the location below, and verify the detached PGP signature using your PGP utility. [FreeBSD 8.3, 8.4, 9.1, 9.2-RELEASE and 8.4-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch.asc # gpg --verify bind-release.patch.asc [FreeBSD 9.2-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch.asc # gpg --verify bind-stable-9.patch.asc b) Execute the following commands as root: # cd /usr/src # patch < /path/to/patch Recompile the operating system using buildworld and installworld as described in <URL:http://www.FreeBSD.org/handbook/makeworld.html>. Restart the applicable daemons, or reboot the system. 3) To update your vulnerable system via a binary patch: Systems running a RELEASE version of FreeBSD on the i386 or amd64 platforms can be updated via the freebsd-update(8) utility: # freebsd-update fetch # freebsd-update install VI. Correction details The following list contains the correction revision numbers for each affected branch. Branch/path Revision - ------------------------------------------------------------------------- stable/8/ r260646 releng/8.3/ r260647 releng/8.4/ r260647 stable/9/ r260646 releng/9.1/ r260647 releng/9.2/ r260647 - ------------------------------------------------------------------------- To see which files were modified by a particular revision, run the following command, replacing NNNNNN with the revision number, on a machine with Subversion installed: # svn diff -cNNNNNN --summarize svn://svn.freebsd.org/base Or visit the following URL, replacing NNNNNN with the revision number: <URL:http://svnweb.freebsd.org/base?view=revision&revision=NNNNNN> VII. References <URL:https://kb.isc.org/article/AA-01078> <URL:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0591> The latest revision of this advisory is available at <URL:http://security.FreeBSD.org/advisories/FreeBSD-SA-14:04.bind.asc> -----BEGIN PGP SIGNATURE----- iQIcBAEBCgAGBQJS1ZTYAAoJEO1n7NZdz2rnOvQP/2/68/s9Cu35PmqNtSZVVxVG ZSQP5EGWx/lramNf9566iKxOrLRMq/h3XWcC4goVd+gZFrvITJSVOWSa7ntDQ7TO XcinfRZ/iyiJbs/Rg2wLHc/t5oVSyeouyccqODYFbOwOlk35JjOTMUG1YcX+Zasg ax8RV+7Zt1QSBkMlOz/myBLXUjlTZ3Xg2FXVsfFQW5/g2CjuHpRSFx1bVNX6ysoG 9DT58EQcYxIS8WfkHRbbXKh9I1nSfZ7/Hky/kTafRdRMrjAgbqFgHkYTYsBZeav5 fYWKGQRJulYfeZQ90yMTvlpF42DjCC3uJYamJnwDIu8OhS1WRBI8fQfr9DRzmRua OK3BK9hUiScDZOJB6OqeVzUTfe7MAA4/UwrDtTYQ+PqAenv1PK8DZqwXyxA9ThHb zKO3OwuKOVHJnKvpOcr+eNwo7jbnHlis0oBksj/mrq2P9m2ueF9gzCiq5Ri5Syag Wssb1HUoMGwqU0roS8+pRpNC8YgsWpsttvUWSZ8u6Vj/FLeHpiV3mYXPVMaKRhVm 067BA2uj4Th1JKtGleox+Em0R7OFbCc/9aWC67wiqI6KRyit9pYiF3npph+7D5Eq 7zPsUdDd+qc+UTiLp3liCRp5w6484wWdhZO6wRtmUgxGjNkxFoNnX8CitzF8AaqO UWWemqWuz3lAZuORQ9KX =OQzQ -----END PGP SIGNATURE----- Every security advisory uses the following format: Each security advisory is signed by the PGP key of the Security Officer. The public key for the Security Officer can be verified at . The name of the security advisory always begins with FreeBSD-SA- (for FreeBSD Security Advisory), followed by the year in two digit format (14:), followed by the advisory number for that year (04.), followed by the name of the affected application or subsystem (bind). The advisory shown here is the fourth advisory for 2014 and it affects BIND. The Topic field summarizes the vulnerability. The Category refers to the affected part of the system which may be one of core, contrib, or ports. The core category means that the vulnerability affects a core component of the &os; operating system. The contrib category means that the vulnerability affects software included with &os;, such as BIND. The ports category indicates that the vulnerability affects software available through the Ports Collection. The Module field refers to the component location. In this example, the bind module is affected; therefore, this vulnerability affects an application installed with the operating system. The Announced field reflects the date the security advisory was published. This means that the security team has verified that the problem exists and that a patch has been committed to the &os; source code repository. The Credits field gives credit to the individual or organization who noticed the vulnerability and reported it. The Affects field explains which releases of &os; are affected by this vulnerability. The Corrected field indicates the date, time, time offset, and releases that were corrected. The CVE Name field lists the advisory number, if one exists, in the public cve.mitre.org security vulnerabilities database. The Background field provides a description of the affected module. The Problem Description field explains the vulnerability. This can include information about the flawed code and how the utility could be maliciously used. The Impact field describes what type of impact the problem could have on a system. The Workaround field indicates if a workaround is available to system administrators who cannot immediately patch the system . The Solution field provides the instructions for patching the affected system. This is a step by step tested and verified method for getting a system patched and working securely. The Correction Details field displays each affected Subversion branch with the revision number that contains the corrected code. The References field offers sources of additional information regarding the vulnerability. Process Accounting TomRhodesContributed by Process Accounting Process accounting is a security method in which an administrator may keep track of system resources used and their allocation among users, provide for system monitoring, and minimally track a user's commands. Process accounting has both positive and negative points. One of the positives is that an intrusion may be narrowed down to the point of entry. A negative is the amount of logs generated by process accounting, and the disk space they may require. This section walks an administrator through the basics of process accounting. If more fine-grained accounting is needed, refer to . Enabling and Utilizing Process Accounting Before using process accounting, it must be enabled using the following commands: &prompt.root; touch /var/account/acct &prompt.root; chmod 600 /var/account/acct &prompt.root; accton /var/account/acct &prompt.root; echo 'accounting_enable="YES"' >> /etc/rc.conf Once enabled, accounting will begin to track information such as CPU statistics and executed commands. All accounting logs are in a non-human readable format which can be viewed using sa. If issued without any options, sa prints information relating to the number of per-user calls, the total elapsed time in minutes, total CPU and user time in minutes, and the average number of I/O operations. Refer to &man.sa.8; for the list of available options which control the output. To display the commands issued by users, use lastcomm. For example, this command prints out all usage of ls by trhodes on the ttyp1 terminal: &prompt.root; lastcomm ls trhodes ttyp1 Many other useful options exist and are explained in &man.lastcomm.1;, &man.acct.5;, and &man.sa.8;. Resource Limits TomRhodesContributed by Resource limits Traditionally, &os; used a resource limits database controlled through a flat file, /etc/login.conf. While this method is still supported, any changes require a multi-step process of editing this file in order to divide users into various group labels known as classes, rebuilding the resource database using cap_mkdb, making necessary changes to /etc/master.passwd, and rebuilding the password database using pwd_mkdb. This could be time consuming, depending upon the number of users to configure. Beginning with &os; 9.0-RELEASE, rctl can be used to provide a more fine-grained method of controlling resources limits for users. This command supports much more than users as it can be used to set resource constraints on processes, jails, and the original login class. These advanced features provide administrators and users with methods to control resources through the command line and to set rules on system initialization using a configuration file. + This section demonstrates both methods for controlling + resources. + + + Login Classes + + + limiting users + + + accounts + limiting + + + &os; provides several methods for an administrator to + limit the amount of system resources an individual may use. + These limits are discussed in two sections: disk quotas and + other resource limits. + + + quotas + + + limiting users + quotas + + + disk quotas + + + Disk quotas limit the amount of disk space available to + users and provide a way to quickly check that usage without + calculating it every time. Quotas are discussed in + . + + The other resource limits include ways to limit the amount + of CPU, memory, and other resources a user may consume. These + are defined using login classes and are discussed here. + + + /etc/login.conf + + + Login classes are defined in + /etc/login.conf and are described in + detail in &man.login.conf.5;. Each user account is assigned + to a login class, default by default, and + each login class has a set of login capabilities associated + with it. A login capability is a + name=value + pair, where name is a well-known + identifier and value is an + arbitrary string which is processed accordingly depending on + the name. Setting up login classes + and capabilities is rather straightforward and is also + described in &man.login.conf.5;. + + + &os; does not normally read the configuration in + /etc/login.conf directly, but instead + reads the /etc/login.conf.db database + which provides faster lookups. Whenever + /etc/login.conf is edited, the + /etc/login.conf.db must be updated by + executing the following command: + + &prompt.root; cap_mkdb /etc/login.conf + + + Resource limits differ from the default login capabilities + in two ways. First, for every limit, there is a soft + (current) and hard limit. A soft limit may be adjusted by the + user or application, but may not be set higher than the hard + limit. The hard limit may be lowered by the user, but can + only be raised by the superuser. Second, most resource limits + apply per process to a specific user, not to the user as a + whole. These differences are mandated by the specific + handling of the limits, not by the implementation of the login + capability framework. + + Below are the most commonly used resource limits. The + rest of the limits, along with all the other login + capabilities, can be found in &man.login.conf.5;. + + + + coredumpsize + + + The limit on the size of a core file + + coredumpsize + + generated by a program is subordinate to other limits + + limiting users + coredumpsize + + on disk usage, such as filesize, or + disk quotas. This limit is often used as a less-severe + method of controlling disk space consumption. Since + users do not generate core files themselves, and often + do not delete them, setting this may save them from + running out of disk space should a large program + crash. + + + + + cputime + + + The maximum amount of CPU + + cputime + + + limiting users + cputime + + time a user's process may consume. Offending processes + will be killed by the kernel. + + + This is a limit on CPU time + consumed, not percentage of the CPU as displayed in + some fields by &man.top.1; and &man.ps.1;. + + + + + + filesize + + + The maximum size of a file + + filesize + + + limiting users + filesize + + the user may own. Unlike + disk quotas, this limit is + enforced on individual files, not the set of all files a + user owns. + + + + + maxproc + + + The maximum number of processes + + maxproc + + + limiting users + maxproc + + a user can run. This includes foreground and background + processes. This limit may not be larger than the system + limit specified by the kern.maxproc + &man.sysctl.8;. Setting this limit too small may hinder + a user's productivity as it is often useful to be logged + in multiple times or to execute pipelines. Some tasks, + such as compiling a large program, start lots of + processes. + + + + + memorylocked + + + The maximum amount of memory + + memorylocked + + + limiting users + memorylocked + + a process may request to be locked into main memory + using &man.mlock.2;. Some system-critical programs, + such as &man.amd.8;, lock into main memory so that if + the system begins to swap, they do not contribute to + disk thrashing. + + + + + memoryuse + + + The maximum amount of memory + + memoryuse + + + limiting users + memoryuse + + a process may consume at any given time. It includes + both core memory and swap usage. This is not a + catch-all limit for restricting memory consumption, but + is a good start. + + + + + openfiles + + + The maximum number of files a process may have open + + openfiles + + + limiting users + openfiles + . + In &os;, files are used to represent sockets and IPC + channels, so be careful not to set this too low. The + system-wide limit for this is defined by the + kern.maxfiles &man.sysctl.8;. + + + + + sbsize + + + The limit on the amount of network memory, and + thus mbufs + + sbsize + + + limiting users + sbsize + , + a user may consume. This can be generally used to limit + network communications. + + + + + stacksize + + + The maximum size of a process stack + + stacksize + + + limiting users + stacksize + . + This alone is not sufficient to limit the amount of + memory a program may use so it should be used in + conjunction with other limits. + + + + + There are a few other things to remember when setting + resource limits. Following are some general tips, + suggestions, and miscellaneous comments. + + + + Processes started at system startup by + /etc/rc are assigned to the + daemon login class. + + + + Although the /etc/login.conf that + comes with the system is a good source of reasonable + values for most limits, they may not be appropriate for + every system. Setting a limit too high may open the + system up to abuse, while setting it too low may put a + strain on productivity. + + + + Users of &xorg; should + probably be granted more resources than other users. + &xorg; by itself takes a lot of + resources, but it also encourages users to run more + programs simultaneously. + + + + Many limits apply to individual processes, not the + user as a whole. For example, setting + openfiles to 50 means that each process + the user runs may open up to 50 files. The total amount + of files a user may open is the value of + openfiles multiplied by the value of + maxproc. This also applies to memory + consumption. + + + + For further information on resource limits and login + classes and capabilities in general, refer to + &man.cap.mkdb.1;, &man.getrlimit.2;, and + &man.login.conf.5;. + + Enabling and Configuring Resource Limits By default, kernel support for rctl is not built-in, meaning that the kernel will first need to be recompiled using the instructions in . Add these lines to either GENERIC or a custom kernel configuration file, then rebuild the kernel: options RACCT options RCTL Once the system has rebooted into the new kernel, rctl may be used to set rules for the system. Rule syntax is controlled through the use of a subject, subject-id, resource, and action, as seen in this example rule: user:trhodes:maxproc:deny=10/user In this rule, the subject is user, the subject-id is trhodes, the resource, maxproc, is the maximum number of processes, and the action is deny, which blocks any new processes from being created. This means that the user, trhodes, will be constrained to no greater than 10 processes. Other possible actions include logging to the console, passing a notification to &man.devd.8;, or sending a sigterm to the process. Some care must be taken when adding rules. Since this user is constrained to 10 processes, this example will prevent the user from performing other tasks after logging in and executing a screen session. Once a resource limit has been hit, an error will be printed, as in this example: &prompt.user; man test /usr/bin/man: Cannot fork: Resource temporarily unavailable eval: Cannot fork: Resource temporarily unavailable As another example, a jail can be prevented from exceeding a memory limit. This rule could be written as: &prompt.root; rctl -a jail:httpd:memoryuse:deny=2G/jail Rules will persist across reboots if they have been added to /etc/rctl.conf. The format is a rule, without the preceding command. For example, the previous rule could be added as: # Block jail from using more than 2G memory: jail:httpd:memoryuse:deny=2G/jail To remove a rule, use rctl to remove it from the list: &prompt.root; rctl -r user:trhodes:maxproc:deny=10/user A method for removing all rules is documented in &man.rctl.8;. However, if removing all rules for a single user is required, this command may be issued: &prompt.root; rctl -r user:trhodes Many other resources exist which can be used to exert additional control over various subjects. See &man.rctl.8; to learn about them.