diff --git a/documentation/content/en/books/handbook/basics/_index.adoc b/documentation/content/en/books/handbook/basics/_index.adoc index 3d9da088b7..4eee8f3079 100644 --- a/documentation/content/en/books/handbook/basics/_index.adoc +++ b/documentation/content/en/books/handbook/basics/_index.adoc @@ -1,1960 +1,1960 @@ --- title: Chapter 3. FreeBSD Basics part: Part I. Getting Started prev: books/handbook/bsdinstall next: books/handbook/ports description: Basic commands and functionality of the FreeBSD operating system tags: ["basics", "virtual consoles", "users", "management", "permissions", "directory structure", "disk organization", "mounting", "processes", "daemons", "shell", "editor", "manual pages", "devices"] showBookMenu: true weight: 5 path: "/books/handbook/" --- [[basics]] = FreeBSD Basics :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 3 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/basics/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[basics-synopsis]] == Synopsis This chapter covers the basic commands and functionality of the FreeBSD operating system. Much of this material is relevant for any UNIX(R)-like operating system. New FreeBSD 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 FreeBSD. * How UNIX(R) file permissions and FreeBSD file flags work. * The default FreeBSD file system layout. * The FreeBSD 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. [[consoles]] == Virtual Consoles and Terminals Unless FreeBSD 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: [.programlisting] .... FreeBSD/amd64 (pc3.example.org) (ttyv0) login: .... The first line contains some information about the system. The `amd64` indicates that FreeBSD is running on a 64-bit x86 system. The hostname is `pc3.example.org`, and `ttyv0` indicates that this is the "system console". The second line is the login prompt. Since FreeBSD 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 "username" and a personal "password". To log into the system console, type the username that was configured during system installation, as described in crossref:bsdinstall[bsdinstall-addusers,Add Users], and press kbd:[Enter]. Then enter the password associated with the username and press kbd:[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 FreeBSD system console and ready to try the available commands. [[consoles-virtual]] === 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 FreeBSD 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, FreeBSD 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 kbd:[Alt+F1] through kbd:[Alt+F8] have been reserved by FreeBSD for switching between virtual consoles. Use kbd:[Alt+F1] to switch to the system console (`ttyv0`), kbd:[Alt+F2] to access the first virtual console (`ttyv1`), kbd:[Alt+F3] to access the second virtual console (`ttyv2`), and so on. When using Xorg as a graphical console, the combination becomes kbd:[Ctrl+Alt+F1] to return to a text-based virtual console. When switching from one console to the next, FreeBSD manages the screen output. The result is an illusion of having multiple virtual screens and keyboards that can be used to type commands for FreeBSD 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:kbdcontrol[1], man:vidcontrol[1], man:atkbd[4], man:syscons[4], and man:vt[4] for a more technical description of the FreeBSD console and its keyboard drivers. In FreeBSD, the number of available virtual consoles is configured in this section of `/etc/ttys`: [.programlisting] .... # name getty type status comments # ttyv0 "/usr/libexec/getty Pc" xterm on secure # Virtual terminals ttyv1 "/usr/libexec/getty Pc" xterm on secure ttyv2 "/usr/libexec/getty Pc" xterm on secure ttyv3 "/usr/libexec/getty Pc" xterm on secure ttyv4 "/usr/libexec/getty Pc" xterm on secure ttyv5 "/usr/libexec/getty Pc" xterm on secure ttyv6 "/usr/libexec/getty Pc" xterm on secure ttyv7 "/usr/libexec/getty Pc" xterm 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 crossref:x11[x11,The X Window System]. For a detailed description of every column in this file and the available options for the virtual consoles, refer to man:ttys[5]. [[consoles-singleuser]] === Single User Mode The FreeBSD 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 FreeBSD system. The settings which control single user mode are found in this section of `/etc/ttys`: [.programlisting] .... # 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`, FreeBSD will prompt for the `root` password when a user selects to boot into single user mode. [NOTE] ==== _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 FreeBSD booting process. ==== [[consoles-vidcontrol]] === Changing Console Video Modes The FreeBSD 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: [source,shell] .... # 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: [source,shell] .... # 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: [source,shell] .... # vidcontrol MODE_279 .... If the new video mode is acceptable, it can be permanently set on boot by adding it to `/etc/rc.conf`: [.programlisting] .... allscreens_flags="MODE_279" .... [[users-synopsis]] == Users and Basic Account Management FreeBSD 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 FreeBSD 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. [[users-introduction]] === Account Types Since all access to the FreeBSD 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. [[users-system]] ==== System Accounts 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. Examples of system accounts are `daemon`, `operator`, `bind`, `news`, and `www`. `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. [[users-user]] ==== User Accounts 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 FreeBSD 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 FreeBSD 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 crossref:security[users-limiting,Configuring Login Classes]. 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 expiration time:: By default, FreeBSD 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 FreeBSD, 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. [[users-superuser]] ==== The Superuser Account 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 [example] ==== [source,shell] .... % configure % make % su - Password: # make install # exit % .... ==== 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 package: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. [[users-modifying]] === Managing Accounts FreeBSD 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. [[users-modifying-utilities]] .Utilities for Managing User Accounts [cols="25h,~"] |=== | 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. |man:bsdconfig[8] |A system configuration utility with account management support. |=== [[users-adduser]] ==== Adding a user 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 kbd:[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. [[users-modifying-adduser]] .Adding a User on FreeBSD [example] ==== [source,shell] .... # adduser .... The output should be similar to the following: [.programlisting] .... 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! .... ==== [NOTE] ==== Since the password is not echoed when typed, be careful to not mistype the password when creating the user account. ==== [[users-rmuser]] ==== Removing a user To completely remove a user from the system, run man:rmuser[8] as the superuser. This command performs the following steps: [.procedure] ==== . Removes the user's man:crontab[1] entry, if one exists. . Removes any man:at[1] jobs belonging to the user. . Sends a SIGKILL signal to all processes owned by the user. . Removes the user from the system's local password file. . Removes the user's home directory (if it is owned by the user), including handling of symbolic links in the path to the actual home directory. . Removes the incoming mail files belonging to the user from `/var/mail`. . Removes all files owned by the user from `/tmp`, `/var/tmp`, and `/var/tmp/vi.recover`. . 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 man:adduser[8]'s per-user unique groups.) . Removes all message queues, shared memory segments and semaphores owned by the user. ==== 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. .`rmuser` Interactive Account Removal [example] ==== [source,shell] .... # rmuser jru .... The output should be similar to the following: [.programlisting] .... 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. .... ==== [[users-chpass]] ==== Change user information 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. [NOTE] ==== 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 <>. [[users-modifying-chpass-su]] .Using `chpass` as Superuser [example] ==== [source,shell] .... # chpass .... The output should be similar to the following: [.programlisting] .... # 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: .... ==== [[users-modifying-chpass-ru]] .Using `chpass` as Regular User [example] ==== [source,shell] .... #Changing user database information for jru. Shell: /usr/local/bin/zsh Full Name: J. Random User Office Location: Office Phone: Home Phone: Other information: .... ==== [NOTE] ==== 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 crossref:network-servers[network-servers,Network Servers]. ==== [[users-passwd]] ==== Change user 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 [example] ==== [source,shell] .... % passwd .... The output should be similar to the following: [.programlisting] .... 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 [example] ==== [source,shell] .... # passwd jru .... The output should be similar to the following: [.programlisting] .... Changing local password for jru. New password: Retype new password: passwd: updating the database... passwd: done .... ==== [NOTE] ==== As with man:chpass[1], man:yppasswd[1] is a link to man:passwd[1], so NIS works with either command. ==== [[users-pw]] ==== Create, remove, modify and display system users and groups 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. [[users-groups]] === Managing Groups A group is a list of users. A group is identified by its group name and GID. In FreeBSD, 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]. +For a complete description of the syntax, refer to man:group[5]. The superuser can modify `/etc/group` using a text editor, although editing the group file using man:vigr[8] is preferred because it can catch some common mistakes. 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: [WARNING] ==== Care must be taken when using the operator group, as unintended superuser-like access privileges may be granted, including but not limited to shutdown, reboot, and access to all items in `/dev` in the group. ==== .Adding a Group Using man:pw[8] [example] ==== [source,shell] .... # pw groupadd teamtwo # pw groupshow teamtwo .... The output should be similar to the following: [.programlisting] .... 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] [example] ==== [source,shell] .... # pw groupmod teamtwo -M jru # pw groupshow teamtwo .... The output should be similar to the following: [.programlisting] .... teamtwo:*:1100:jru .... ==== The argument to `-M` 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 `groupshow` 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] [example] ==== [source,shell] .... # pw groupmod teamtwo -m db # pw groupshow teamtwo .... The output should be similar to the following: [.programlisting] .... teamtwo:*:1100:jru,db .... ==== In this example, the argument to `-m` 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 [example] ==== [source,shell] .... % id jru .... The output should be similar to the following: [.programlisting] .... 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]] == Permissions In FreeBSD, 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(R) permissions used in FreeBSD. For finer-grained file system access control, refer to crossref:security[fs-acl,Access Control Lists]. In UNIX(R), 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. .UNIX(R) Permissions [cols="1,1,1", frame="none", options="header"] |=== | 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` |=== Use the `-l` argument with 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, `ls -l` in an arbitrary directory may show: [source,shell] .... % ls -l .... The output should be similar to the following: [.programlisting] .... 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 .... Focusing on the line for `myfile`, the first `(leftmost)` character 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? FreeBSD 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 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: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | 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 both members of the group associated with _FILE_ and all other users from accessing _FILE_: [source,shell] .... % 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: [source,shell] .... % chmod go-w,a+x FILE .... === FreeBSD File Flags In addition to file permissions, FreeBSD 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: [source,shell] .... # chflags sunlink file1 .... To disable the system undeletable flag, put a "no" in front of the `sunlink`: [source,shell] .... # chflags nosunlink file1 .... To view the flags of a file, use `-lo` with man:ls[1]: [source,shell] .... # ls -lo file1 .... [.programlisting] .... -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 setuid, setgid, and sticky Permissions 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(R) 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 added symbolically by adding the `s` permission for the user as in the following example: [source,shell] .... # chmod u+s suidexample.sh .... The setuid permission may also be set by prefixing a permission set with the number four (4) as shown in the following example: [source,shell] .... # chmod 4755 suidexample.sh .... The permissions on `suidexample.sh` now look like the following: [.programlisting] .... -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]. [NOTE] ==== 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: [source,shell] .... Changing local password for trhodes Old Password: .... In terminal B: [source,shell] .... # ps aux | grep passwd .... [source,shell] .... 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 symbolically, add the `s` permission for the group with man:chmod[1]: [source,shell] .... # chmod g+s sgidexample.sh .... Alternatively, provide man:chmod[1] with a leading two (2): [source,shell] .... # chmod 2755 sgidexample.sh .... In the following listing, notice that the `s` is now in the field designated for the group permission settings: [source,shell] .... -rwxr-sr-x 1 trhodes trhodes 44 Aug 31 01:49 sgidexample.sh .... [NOTE] ==== 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, add the `t` mode to the file: [source,shell] .... # chmod +t /tmp .... Alternatively, prefix the permission set with a one (1): [source,shell] .... # chmod 1777 /tmp .... The `sticky bit` permission will display as a `t` at the very end of the permission set: [source,shell] .... # ls -al / | grep tmp .... [source,shell] .... drwxrwxrwt 10 root wheel 512 Aug 31 01:49 tmp .... [[dirstructure]] == Directory Structure The FreeBSD 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 `noauto`. 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. [cols="25h,~"] |=== | 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 special files managed by man:devfs[5] |`/etc/` |System configuration files and scripts. |`/etc/defaults/` |Default system configuration files. Refer to man:rc[8] for details. |`/etc/periodic/` |Scripts that run daily, weekly, and monthly, via man:cron[8]. Refer to man:periodic[8] for details. |`/lib/` |Critical system libraries needed for binaries in `/bin` and `/sbin` |`/libexec/` |Critical system files |`/media/` |Contains subdirectories to be used as mount points for removable media such as CDs, USB drives, and floppy disks |`/mnt/` |Empty directory commonly used by system administrators as a temporary mount point. |`/net/` |Automounted NFS shares; see man:auto_master[5] |`/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 FreeBSD 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/ports/` |The FreeBSD 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. |`/var/log/` |Miscellaneous system log files. |`/var/tmp/` |Temporary files which are usually preserved across a system reboot. |=== [[disk-organization]] == Disk Organization The smallest unit of organization that FreeBSD uses to find files is the filename. Filenames are case-sensitive, which means that `readme.txt` and `README.TXT` are two separate files. FreeBSD 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(R) which uses `\` to separate file and directory names. FreeBSD does not use drive letters, or other drive names in the path. For example, one would not type `c:\foo\bar\readme.txt` on FreeBSD. [[disks-file-systems]] === File systems 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 FreeBSD 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: image::example-dir1.png[Directory tree with the root directory and two subdirectories, A1 and 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: image::example-dir2.png[Directory tree with the root directory and two subdirectories, A1 and A2. And more subdirectories, B1 and B2 hanging from A1] 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: image::example-dir3.png[Directory tree with the root directory and two subdirectories, A1 and A2. And more subdirectories, B1 and B2 hanging from A2] 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: image::example-dir4.png[A complex directory tree. With different subdirectories hanging from root.] Or `C` could be mounted directly on to the `A` file system, under the `A1` directory: image::example-dir5.png[A complex directory tree. With different subdirectories hanging from root.] 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. * FreeBSD 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. * FreeBSD'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 FreeBSD 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. + [IMPORTANT] ==== FreeBSD features the man:growfs[8] command, which makes it possible to increase the size of file system on the fly, removing this limitation. A file system can only be expanded into free space in the partition in which it resides. If there is space after the partition, the partition can be expanded with man:gpart[8]. If the partition is the last one on a virtual disk, and the disk is expanded, the partition can then be expanded. ==== [[disks-partitions]] === Disk partitions File systems are contained in _partitions_. Disks are divided into partitions using one of several partitioning schemes; see <>. The newer scheme is GPT; older BIOS-based computers use MBR. GPT supports division of a disk into partitions with a size, offset, and type. It supports a large number of partitions and partition types, and is recommended whenever its use is possible. GPT partitions use the disk name with a suffix, where the suffix is `p1` for the first partition, `p2` for the second, and so on. MBR, however, supports only a small number of partitions. The MBR partitions are known in FreeBSD as `slices`. Slices may be used for different operating systems. FreeBSD slices are subdivided into partitions using BSD labels (see man:bsdlabel[8]). Slice numbers follow the device name, prefixed with an `s`, starting at 1. So "da0__s1__" 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 "ada0__s5__" is the first extended slice on the first SATA disk. These devices are used by file systems that expect to occupy a slice. Each GPT or BSD 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 name of the partition they are contained in. FreeBSD 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 FreeBSD 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. This is called _paging_. Some BSD partitions have certain conventions associated with them. [cols="25h,~"] |=== | 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. |=== Slices and "dangerously dedicated" physical drives contain BSD partitions, which are represented as letters from `a` to `h`. This letter is appended to the device name, so "da0__a__" is the `a` partition on the first `da` drive, which is "dangerously dedicated". "ada1s3__e__" is the fifth partition in the third slice of the second SATA 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 partitions and slices, disk numbering starts at 0. Common codes are listed in <>. When referring to a partition in a slice, include the disk name, `s`, the slice number, and then the partition letter. Examples are shown in <>. GPT partitions include the disk name, `p`, and then the partition number. <> shows a conceptual model of a disk layout using MBR slices. When installing FreeBSD, configure the disk slices if using MBR, and create partitions within the slice to be used for FreeBSD. If using GPT, configure partitions for each file system. In either case, create a file system or swap space in each partition, and decide where each file system will be mounted. See man:gpart[8] for information on manipulating partitions. [[disks-naming]] .Disk Device Names [cols="1,1", frame="none", options="header"] |=== | Drive Type | Drive Device Name |SATA and IDE hard drives |`ada` |SCSI hard drives and USB storage devices |`da` |NVMe storage |`nvd` or `nda` |SATA and IDE CD-ROM drives |`cd` |SCSI CD-ROM drives |`cd` |Floppy drives |`fd` |SCSI tape drives |`sa` |RAID drives |Examples include `aacd` for Adaptec(R) AdvancedRAID, `mlxd` and `mlyd` for Mylex(R), `amrd` for AMI MegaRAID(R), `idad` for Compaq Smart RAID, `twed` for 3ware(R) RAID. |=== [example] ==== [[basics-disk-slice-part]] .Sample Disk, Slice, and Partition Names [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Name | Meaning |`ada0s1a` |The first partition (`a`) on the first slice (`s1`) on the first SATA disk (`ada0`). |`da1s2e` |The fifth partition (`e`) on the second slice (`s2`) on the second SCSI disk (`da1`). |=== ==== [[basics-concept-disk-model]] .Conceptual Model of a Disk [example] ==== This diagram shows FreeBSD's view of the first SATA disk attached to the system. Assume that the disk is 250 GB in size, and contains an 80 GB slice and a 170 GB slice (MS-DOS(R) partitions). The first slice contains a Windows(R) NTFS file system, `C:`, and the second slice contains a FreeBSD installation. This example FreeBSD installation has four data partitions and a swap partition. The four partitions each hold a file system. Partition `a` is used for the root file system, `d` for `/var/`, `e` for `/tmp/`, and `f` for `/usr/`. Partition letter `c` refers to the entire slice, and so is not used for ordinary partitions. image::disk-layout.png[Layout of a shared drive between Windows and FreeBSD] ==== [[mount-unmount]] == 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. 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 crossref:network-servers[network-nfs,“Network File System (NFS)”], or CDROM drives. [[disks-fstab]] === The fstab File During the boot process (crossref:boot[boot,The FreeBSD Booting Process]), file systems listed in `/etc/fstab` are automatically mounted except for the entries containing `noauto`. This file contains entries in the following format: [.programlisting] .... 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 FreeBSD file system is `ufs`. `options`:: Either `rw` for read-write file systems, or `ro` for read-only file systems, followed by any other options that may be needed. A common option is `noauto` 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 UFS file systems should be checked by man:fsck[8] after a reboot. 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. [[disks-mount]] === Using man:mount[8] File systems are mounted using man:mount[8]. The most basic syntax is as follows: [example] ==== [source,shell] .... # mount device mountpoint .... ==== A file system listed in `/etc/fstab` can also be mounted by providing just the mountpoint. This command provides many options which are described in man:mount[8]. The most commonly used options include: .Mount Options `-a`:: Mount all the file systems listed in `/etc/fstab`, except those marked as "noauto", excluded by the `-t` flag, or those that are already mounted. `-d`:: Do everything except for the actual mount system call. This option is useful in conjunction with the `-v` flag to determine what man:mount[8] is actually trying to do. `-f`:: 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. `-r`:: Mount the file system read-only. This is identical to using `-o ro`. ``-t _fstype_``:: Mount the specified file system type or mount only file systems of the given type, if `-a` is included. "ufs" is the default file system type. `-u`:: Update mount options on the file system. `-v`:: Be verbose. `-w`:: Mount the file system read-write. The following options can be passed to `-o` as a comma-separated list: nosuid:: Do not interpret setuid or setgid flags on the file system. This is also a useful security option. [[disks-umount]] === Using man:umount[8] To unmount a file system use man:umount[8]. This command takes one parameter which can be a mountpoint, device name, `-a` or `-A`. All forms take `-f` to force unmounting, and `-v` for verbosity. Be warned that `-f` 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 `-t`, use `-a` or `-A`. Note that `-A` does not attempt to unmount the root file system. [[basics-processes]] == Processes and Daemons FreeBSD 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 FreeBSD. 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: [source,shell] .... % ps .... The output should be similar to the following: [.programlisting] .... 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 `a` displays information about all the running processes of all users, `u` displays the username and memory usage of the process' owner, `x` displays information about daemon processes, and `ww` 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: [source,shell] .... % top .... The output should be similar to the following: [.programlisting] .... 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 `-s`. [[basics-daemons]] === 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, FreeBSD 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 cannot be interrupted. `SIGKILL` cannot be ignored by a process. Sending a `SIGKILL` to a process will usually stop that process there and then. footnote:[There are a few tasks that cannot 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. [IMPORTANT] ==== 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 kbd:[Return]. ==== [[shells]] == Shells 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. FreeBSD 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 FreeBSD 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(R) 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 kbd:[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 kbd:[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 kbd:[Tab] again is enough to let the shell determine which filename is desired and fill in the rest. 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. [[shell-env-vars]] .Common Environment Variables [cols="25h,~"] |=== | 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. |=== 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: [source,shell] .... % setenv EDITOR /usr/local/bin/emacs .... The equivalent command for `bash` would be: [source,shell] .... % 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-shells]] === 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`: [source,shell] .... % chsh -s /usr/local/bin/bash .... Enter your password at the prompt and press kbd:[Return] to change your shell. Log off and log in again to start using the new shell. [NOTE] ==== The new shell _must_ be present in `/etc/shells`. If the shell was installed from the FreeBSD Ports Collection as described in crossref:ports[ports,Installing Applications: Packages and Ports], 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: [source,shell] .... # echo /usr/local/bin/bash >> /etc/shells .... Then, rerun man:chsh[1]. ==== === Advanced Shell Techniques The UNIX(R) 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, redirect the output: [source,shell] .... % ls > directory_listing.txt .... The directory contents will now be listed in `directory_listing.txt`. Some commands can be used to read input, such as man:sort[1]. To sort this listing, redirect the input: [source,shell] .... % 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: [source,shell] .... % sort < directory_listing.txt > sorted.txt .... In all of the previous examples, the commands are performing redirection using file descriptors. Every UNIX(R) system has file descriptors, which include standard input (stdin), standard output (stdout), and standard error (stderr). 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. 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, 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(R) pipe operator, "|" allows the output of one command to be directly passed or directed to another program. Basically, a pipe allows the standard output of a command to be passed as standard input to another command, for example: [source,shell] .... % 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. [[editors]] == Text Editors Most FreeBSD configuration is done by editing text files, so it is a good idea to become familiar with a text editor. FreeBSD comes with a few as part of the base system, and many more are available in the Ports Collection. 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 kbd:[Ctrl], so `^e` expands to kbd:[Ctrl+e]. To leave man:ee[1], press kbd:[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. FreeBSD also comes with more powerful text editors, such as man:vi[1], as part of the base system. Other editors, like package:editors/emacs[] and package:editors/vim[], are part of the FreeBSD 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 <>. [[basics-devices]] == 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 FreeBSD boots, the majority of the boot messages refer to devices being detected. A copy of the boot messages is saved to `/var/run/dmesg.boot`. Each device has a device name and number. For example, `ada0` is the first SATA hard drive, while `kbd0` represents the keyboard. Most devices in FreeBSD must be accessed through special files called device nodes, which are located in `/dev`. [[basics-more-information]] == Manual Pages The most comprehensive documentation on FreeBSD 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`: [source,shell] .... % man command .... where _command_ is the name of the command to learn about. For example, to learn more about man:ls[1], type: [source,shell] .... % man ls .... Manual pages are divided into sections which represent the type of topic. In FreeBSD, 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: [source,shell] .... % 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: [source,shell] .... % 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 all of the commands in `/usr/sbin`, type: [source,shell] .... % cd /usr/sbin % man -f * | more .... or [source,shell] .... % cd /usr/sbin % whatis * |more .... [[basics-info]] === GNU Info Files FreeBSD includes several 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 package:editors/emacs[] is installed, the info mode of emacs. To use man:info[1], type: [source,shell] .... % info .... For a brief introduction, type `h`. For a quick command reference, type `?`. diff --git a/documentation/content/en/books/handbook/mail/_index.adoc b/documentation/content/en/books/handbook/mail/_index.adoc index f89e990075..711ab931da 100644 --- a/documentation/content/en/books/handbook/mail/_index.adoc +++ b/documentation/content/en/books/handbook/mail/_index.adoc @@ -1,964 +1,964 @@ --- title: Chapter 31. Electronic Mail part: IV. Network Communication prev: books/handbook/ppp-and-slip next: books/handbook/network-servers description: This chapter provides a basic introduction to running a mail server on FreeBSD, as well as an introduction to sending and receiving email using FreeBSD tags: ["mail", "sendmail", "dma", "MTA", "SMTP", "mail user agents", "fetchmail", "procmail", "alpine", "mutt", "postfix"] showBookMenu: true weight: 36 path: "/books/handbook/" --- [[mail]] = Electronic Mail :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 31 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/mail/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[mail-synopsis]] == Synopsis "Electronic Mail", better known as email, is one of the most widely used forms of communication today. This chapter provides a basic introduction to running a mail server on FreeBSD, as well as an introduction to sending and receiving email using FreeBSD. -For more complete coverage of this subject, refer to the books listed in crossref:bibliography[bibliography,Bibliography]. +For a complete coverage of this subject, refer to the books listed in crossref:bibliography[bibliography,Bibliography]. This chapter covers: * Which software components are involved in sending and receiving electronic mail. * How to configure DragonFly Mail Agent. * Where basic Sendmail configuration files are located in FreeBSD. * The difference between remote and local mailboxes. * How to install and configure an alternate Mail Transfer Agent, replacing DragonFly Mail Agent or Sendmail. * How to troubleshoot common mail server problems. * How to configure Sendmail to only send mail. * How to configure SMTP authentication for added security in Sendmail. * How to install and use a Mail User Agent, such as mutt, to send and receive email. * How to download mail from a remote POP or IMAP server. * How to automatically apply filters and rules to incoming email. [[mail-using]] == Mail Components There are five major parts involved in an email exchange: the Mail User Agent (MUA), the Mail Transfer Agent (MTA), a mail host, a remote or local mailbox, and DNS. This section provides an overview of these components. Mail User Agent (MUA):: The Mail User Agent (MUA) is an application which is used to compose, send, and receive emails. This application can be a command line program, such as the built-in `mail` utility or a third-party application from the Ports Collection, such as alpine, elm, or mutt. Dozens of graphical programs are also available in the Ports Collection, including Claws Mail, Evolution, and Thunderbird. Some organizations provide a web mail program which can be accessed through a web browser. More information about installing and using a MUA on FreeBSD can be found in <>. Mail Transfer Agent (MTA):: The Mail Transfer Agent (MTA) is responsible for receiving incoming mail and delivering outgoing mail. Starting with FreeBSD version 14.0, the default MTA is DragonFly Mail Agent (man:dma[8]); in earlier versions, it is man:sendmail[8]. Other MTAs, including Exim, Postfix, and qmail, may be installed to replace the default MTA. Mail Host and Mailboxes:: The mail host is a server that is responsible for delivering and receiving mail for a host or a network. The mail host collects all mail sent to the domain and stores it either in the default `mbox` or the alternative Maildir format, depending on the configuration. Once mail has been stored, it may either be read locally using a MUA or remotely accessed and collected using protocols such as POP or IMAP. If mail is read locally, a POP or IMAP server does not need to be installed. Domain Name System (DNS):: The Domain Name System (DNS) and its daemon man:named[8] play a large role in the delivery of mail. In order to deliver mail from one site to another, the MTA will look up the remote site in DNS to determine which host will receive mail for the destination. This process also occurs when mail is sent from a remote host to the MTA. [[dragonFly-mail-agent]] == DragonFly Mail Agent (DMA) DragonFly Mail Agent (DMA) is the default MTA in FreeBSD starting with version 14.0. man:dma[8] is a small Mail Transport Agent (MTA), designed for home and office use. It accepts mails from locally installed Mail User Agents (MUA) and delivers the mails either locally or to a remote destination. Remote delivery includes several features like TLS/SSL support and SMTP authentication. man:dma[8] is not intended as a replacement for real, big MTAs like man:sendmail[8] or man:postfix[1]. Consequently, man:dma[8] does not listen on port 25 for incoming connections. [[configuring-dragonfly-mail-agent]] === Configuring DragonFly Mail Agent (DMA) DMA comes with a default configuration that will be suitable for many deployments. Custom settings are defined in [.filename]#/etc/dma/dma.conf#, and SMTP authentication is configured in [.filename]#/etc/dma/auth.conf#. [[configuring-gmail-dma]] ==== Using DMA to Route Outgoing Mail through Gmail (STARTTLS:SMTP example) This example [.filename]#/etc/dma/dma.conf# can be used to send mail using Google's SMTP servers. [.programlisting] .... SMARTHOST smtp.gmail.com PORT 587 AUTHPATH /etc/dma/auth.conf SECURETRANSFER STARTTLS MASQUERADE username@gmail.com .... Authentication can be set with one line in [.filename]#/etc/dma/auth.conf#: [.programlisting] .... username@gmail.com|smtp.gmail.com:password .... Execute the following command to test the configuration: [source,shell] .... % echo this is a test | mail -v -s testing-email username@gmail.com .... [[configuring-fastmail-dma]] ==== Using DMA to Route Outgoing Mail through Fastmail (SSL/TLS example) This example [.filename]#/etc/dma/dma.conf# can be used to send mail using Fastmail's SMTP servers. [.programlisting] .... SMARTHOST smtp.fastmail.com PORT 465 AUTHPATH /etc/dma/auth.conf SECURETRANSFER MAILNAME example.server.com .... Authentication can be set with one line in [.filename]#/etc/dma/auth.conf#: [.programlisting] .... username@fastmail.com|smtp.fastmail.com:password .... Execute the following command to test the configuration: [source,shell] .... % echo this is a test | mail -v -s testing-email username@fastmail.com .... [[configuring-custom-dma]] ==== Using DMA to Route Outgoing Mail through a Custom Mail Host This example [.filename]#/etc/dma/dma.conf# can be used to send mail using a custom mail host. [.programlisting] .... SMARTHOST mail.example.org PORT 587 AUTHPATH /etc/dma/auth.conf SECURETRANSFER STARTTLS .... Authentication can be set with one line in [.filename]#/etc/dma/auth.conf#: [.programlisting] .... username@example.org|mail.example.org:password .... Execute the following command to test the configuration: [source,shell] .... % echo this is a test | mail -v -s testing-email username@example.org .... [[sendmail]] == Sendmail Sendmail is a venerable and versatile Mail Transfer Agent (MTA) with a long history in UNIX(R) and UNIX-like systems. It was a part of the FreeBSD base system until FreeBSD 13, offering robust email transport capabilities, extensive customization options, and support for complex routing and filtering. [[configuring-sendmail]] === Configuration Files The configuration files for Sendmail are located in [.filename]#/etc/mail/#. [.filename]#/etc/mail/access#:: This access database file defines which hosts or IP addresses have access to the local mail server and what kind of access they have. Hosts listed as `OK`, which is the default option, are allowed to send mail to this host as long as the mail's final destination is the local machine. Hosts listed as `REJECT` are rejected for all mail connections. Hosts listed as `RELAY` are allowed to send mail for any destination using this mail server. Hosts listed as `ERROR` will have their mail returned with the specified mail error. If a host is listed as `SKIP`, Sendmail will abort the current search for this entry without accepting or rejecting the mail. Hosts listed as `QUARANTINE` will have their messages held and will receive the specified text as the reason for the hold. + Examples of using these options for both IPv4 and IPv6 addresses can be found in the FreeBSD sample configuration, [.filename]#/etc/mail/access.sample#: + To configure the access database, use the format shown in the sample to make entries in [.filename]#/etc/mail/access#, but do not put a comment symbol (`+#+`) in front of the entries. Create an entry for each host or network whose access should be configured. Mail senders that match the left side of the table are affected by the action on the right side of the table. + Whenever this file is updated, update its database and restart Sendmail: + [source,shell] .... # makemap hash /etc/mail/access < /etc/mail/access # service sendmail restart .... [.filename]#/etc/mail/aliases#:: This database file contains a list of virtual mailboxes that are expanded to users, files, programs, or other aliases. Here are a few entries to illustrate the file format: + [.programlisting] .... root: localuser ftp-bugs: joe,eric,paul bit.bucket: /dev/null procmail: "|/usr/local/bin/procmail" .... + The mailbox name on the left side of the colon is expanded to the target(s) on the right. The first entry expands the `root` mailbox to the `localuser` mailbox, which is then looked up in the [.filename]#/etc/mail/aliases# database. If no match is found, the message is delivered to `localuser`. The second entry shows a mail list. Mail to `ftp-bugs` is expanded to the three local mailboxes `joe`, `eric`, and `paul`. A remote mailbox could be specified as _user@example.com_. The third entry shows how to write mail to a file, in this case [.filename]#/dev/null#. The last entry demonstrates how to send mail to a program, [.filename]#/usr/local/bin/procmail#, through a UNIX(R) pipe. Refer to man:aliases[5] for more information about the format of this file. + Whenever this file is updated, run `newaliases` to update and initialize the aliases database. [.filename]#/etc/mail/sendmail.cf#:: This is the master configuration file for Sendmail. It controls the overall behavior of Sendmail, including everything from rewriting email addresses to printing rejection messages to remote mail servers. Accordingly, this configuration file is quite complex. Fortunately, this file rarely needs to be changed for standard mail servers. + The master Sendmail configuration file can be built from man:m4[1] macros that define the features and behavior of Sendmail. Refer to [.filename]#/usr/src/contrib/sendmail/cf/README# for some of the details. + Whenever changes to this file are made, Sendmail needs to be restarted for the changes to take effect. [.filename]#/etc/mail/virtusertable#:: This database file maps mail addresses for virtual domains and users to real mailboxes. These mailboxes can be local, remote, aliases defined in [.filename]#/etc/mail/aliases#, or files. This allows multiple virtual domains to be hosted on one machine. + FreeBSD provides a sample configuration file in [.filename]#/etc/mail/virtusertable.sample# to further demonstrate its format. The following example demonstrates how to create custom entries using that format: + [.programlisting] .... root@example.com root postmaster@example.com postmaster@noc.example.net @example.com joe .... + This file is processed in a first match order. When an email address matches the address on the left, it is mapped to the local mailbox listed on the right. The format of the first entry in this example maps a specific email address to a local mailbox, whereas the format of the second entry maps a specific email address to a remote mailbox. Finally, any email address from `example.com` which has not matched any of the previous entries will match the last mapping and be sent to the local mailbox `joe`. When creating custom entries, use this format and add them to [.filename]#/etc/mail/virtusertable#. Whenever this file is edited, update its database and restart Sendmail: + [source,shell] .... # makemap hash /etc/mail/virtusertable < /etc/mail/virtusertable # service sendmail restart .... [.filename]#/etc/mail/relay-domains#:: In a default FreeBSD installation, Sendmail is configured to only send mail from the host it is running on. For example, if a POP server is available, users will be able to check mail from remote locations but they will not be able to send outgoing emails from outside locations. Typically, a few moments after the attempt, an email will be sent from `MAILER-DAEMON` with a `5.7 Relaying Denied` message. + The most straightforward solution is to add the ISP's FQDN to [.filename]#/etc/mail/relay-domains#. If multiple addresses are needed, add them one per line: + [.programlisting] .... your.isp.example.com other.isp.example.net users-isp.example.org www.example.org .... + After creating or editing this file, restart Sendmail with `service sendmail restart`. + Now any mail sent through the system by any host in this list, provided the user has an account on the system, will succeed. This allows users to send mail from the system remotely without opening the system up to relaying SPAM from the Internet. [[mail-changingmta]] == Changing the Mail Transfer Agent Starting with FreeBSD version 14.0, man:dma[8] is the default MTA, and before 14.0, the default MTA is man:sendmail[8]. However, the system administrator can change the system's MTA. A wide choice of alternative MTAs is available from the `mail` category of the FreeBSD Ports Collection. [WARNING] ==== If the default's outgoing mail service is disabled, it is important that it is replaced with an alternative mail delivery system. Otherwise, system functions such as man:periodic[8] will be unable to deliver their results by email. Many parts of the system expect a functional MTA. If applications continue to use the default binaries to try to send email after they are disabled, mail could go into an inactive queue and never be delivered. ==== [[replace-sendmail-dma]] === Replacing Sendmail with Other MTA In order to completely disable man:sendmail[8] execute the following commands: [source,shell] .... # sysrc sendmail_enable="NO" # sysrc sendmail_submit_enable="NO" # sysrc sendmail_outbound_enable="NO" # sysrc sendmail_msp_queue_enable="NO" .... To only disable man:sendmail[8]'s incoming mail service execute the following command: [source,shell] .... # sysrc sendmail_enable="NO" .... Then stop the man:sendmail[8] service: [source,shell] .... # service sendmail onestop .... Some extra configuration is needed as man:sendmail[8] is so ubiquitous that some software assumes it is already installed and configured. Check [.filename]#/etc/periodic.conf# and make sure that these values are set to `NO`. If this file does not exist, create it with these entries: [.programlisting] .... daily_clean_hoststat_enable="NO" daily_status_mail_rejects_enable="NO" daily_status_include_submit_mailq="NO" daily_submit_queuerun="NO" .... The next step is to install another MTA, man:dma[8] will be used in this example. As pointed above, man:dma[8] is the default MTA in FreeBSD starting with version 14.0. Therefore, it is only necessary to install it from the ports if you are using a previous version. To install it execute the following command: [source,shell] .... # pkg install dma .... Perform the configuration as indicated in <>. Then change all the entries in the file [.filename]#/etc/mail/mailer.conf# to man:dma[8]: [.programlisting] .... # $FreeBSD$ # # Execute the "real" sendmail program, named /usr/libexec/sendmail/sendmail # # If dma(8) is installed, an example mailer.conf that uses dma(8) instead can # be found in /usr/share/examples/dma # sendmail /usr/local/libexec/dma mailq /usr/local/libexec/dma newaliases /usr/local/libexec/dma .... [NOTE] ==== When using the version of man:dma[8] included in the base system, the paths will change to [.filename]#/usr/libexec/dma#. ==== To ensure that anything in the queue is flushed at boot or before shutdown, execute the following command: [source,shell] .... # sysrc dma_flushq_enable="YES" .... Once everything is configured, it is recommended to reboot the system. Rebooting provides the opportunity to ensure that the system is correctly configured to start the new MTA automatically on boot. [[replace-dma]] === Replacing DragonFly Mail Agent (DMA) with Other MTA As noted above, starting with FreeBSD version 14.0, the default MTA is DMA. In this example, package:mail/postfix[] will be used as the alternative MTA. Before installing package:mail/postfix[] some extra configuration is needed. Check [.filename]#/etc/periodic.conf# and make sure that these values are set to `NO`. If this file does not exist, create it with these entries: [.programlisting] .... daily_clean_hoststat_enable="NO" daily_status_mail_rejects_enable="NO" daily_status_include_submit_mailq="NO" daily_submit_queuerun="NO" .... Then install package:mail/postfix[]: [source,shell] .... # pkg install postfix .... To start package:mail/postfix[] at system boot execute the following command: [source,shell] .... # sysrc postfix_enable="YES" .... [TIP] ==== It is good practice to read the installation message after installing an application. Provides useful information about settings, etc. ==== If postfix is *not* already activated in [.filename]#/usr/local/etc/mail/mailer.conf# execute the following commands: [source,shell] .... mv /usr/local/etc/mail/mailer.conf /usr/local/etc/mail/mailer.conf.old install -d /usr/local/etc/mail install -m 0644 /usr/local/share/postfix/mailer.conf.postfix /usr/local/etc/mail/mailer.conf .... When employing SASL, ensure that postfix has access to read the sasldb file. This is accomplished by adding postfix to group mail and making the [.filename]#/usr/local/etc/sasldb*# file(s) readable by group mail (this should be the default for new installs). Once everything is configured, it is recommended to reboot the system. Rebooting provides the opportunity to ensure that the system is correctly configured to start the new MTA automatically on boot. [[mail-agents]] == Mail User Agents A MUA is an application that is used to send and receive email. As email "evolves" and becomes more complex, MUAs are becoming increasingly powerful and provide users increased functionality and flexibility. The `mail` category of the FreeBSD Ports Collection contains numerous MUAs. These include graphical email clients such as Evolution or Balsa and console based clients such as mutt or alpine. [[mail-command]] === mail man:mail[1] is the default MUA installed with FreeBSD. It is a console based MUA that offers the basic functionality required to send and receive text-based email. It provides limited attachment support and can only access local mailboxes. Although man:mail[1] does not natively support interaction with POP or IMAP servers, these mailboxes may be downloaded to a local `mbox` using an application such as fetchmail or getmail. In order to send and receive email, run man:mail[1]: [source,shell] .... % mail .... The contents of the user's mailbox in [.filename]#/var/mail# are automatically read by man:mail[1]. Should the mailbox be empty, the utility exits with a message indicating that no mail could be found. If mail exists, the application interface starts, and a list of messages will be displayed. Messages are automatically numbered, as can be seen in the following example: [.programlisting] .... Mail version 8.1 6/6/93. Type ? for help. "/var/mail/username": 3 messages 3 new >N 1 root@localhost Mon Mar 8 14:05 14/510 "test" N 2 root@localhost Mon Mar 8 14:05 14/509 "user account" N 3 root@localhost Mon Mar 8 14:05 14/509 "sample" .... Messages can now be read by typing kbd:[t] followed by the message number. This example reads the first email: [.programlisting] .... & t 1 Message 1: From root@localhost Mon Mar 8 14:05:52 2004 X-Original-To: username@localhost Delivered-To: username@localhost To: username@localhost Subject: test Date: Mon, 8 Mar 2004 14:05:52 +0200 (SAST) From: root@localhost (Charlie Root) This is a test message, please reply if you receive it. .... As seen in this example, the message will be displayed with full headers. To display the list of messages again, press kbd:[h]. If the email requires a reply, press either kbd:[R] or kbd:[r] man:mail[1] keys. kbd:[R] instructs man:mail[1] to reply only to the sender of the email, while kbd:[r] replies to all other recipients of the message. These commands can be suffixed with the mail number of the message to reply to. After typing the response, the end of the message should be marked by a single kbd:[.] on its own line. An example can be seen below: [.programlisting] .... & R 1 To: root@localhost Subject: Re: test Thank you, I did get your email. . EOT .... In order to send a new email, press kbd:[m], followed by the recipient email address. Multiple recipients may be specified by separating each address with the kbd:[,] delimiter. The subject of the message may then be entered, followed by the message contents. The end of the message should be specified by putting a single kbd:[.] on its own line. [.programlisting] .... & mail root@localhost Subject: I mastered mail Now I can send and receive email using mail ... :) . EOT .... While using man:mail[1], press kbd:[?] to display help at any time. Refer to man:mail[1] for more help on how to use man:mail[1]. [NOTE] ==== man:mail[1] was not designed to handle attachments and thus deals with them poorly. Newer MUAs handle attachments in a more intelligent way. ==== [[mutt-command]] === Mutt Mutt is a powerful MUA, with many features, including: * The ability to thread messages. * PGP support for digital signing and encryption of email. * MIME support. * Maildir support. * Highly customizable. Refer to link:http://www.mutt.org[http://www.mutt.org] for more information on Mutt. [TIP] ==== A Mutt fork called NeoMutt is worth mentioning, which brings added features. See more on the link:https://neomutt.org/about.html[NeoMutt website]. If NeoMutt was chosen, replace the following command examples from `mutt` to `neomutt`. ==== Mutt may be installed using the package:mail/mutt[] port. After the port has been installed, Mutt can be started by issuing the following command: [source,shell] .... % mutt .... Mutt will automatically read and display the contents of the user mailbox in [.filename]#/var/mail#. If no mails are found, Mutt will wait for commands from the user. The example below shows Mutt displaying a list of messages: image::mutt1.png[Mutt email client showing a list of messages] To read an email, select it using the cursor keys and press kbd:[Enter]. An example of Mutt displaying email can be seen below: image::mutt2.png[Mutt email client displaying an email] Similar to man:mail[1], Mutt can be used to reply only to the sender of the message as well as to all recipients. To reply only to the sender of the email, press kbd:[r]. To send a group reply to the original sender as well as all the message recipients, press kbd:[g]. [NOTE] ==== By default, Mutt uses the man:vi[1] editor for creating and replying to emails. Each user can customize this by creating or editing the [.filename]#.muttrc# in their home directory and setting the `editor` variable or by setting the `EDITOR` environment variable. Refer to link:http://www.mutt.org/[http://www.mutt.org/] for more information about configuring Mutt. ==== To compose a new mail message, press kbd:[m]. After a valid subject has been given, Mutt will start man:vi[1] so the email can be written. Once the contents of the email are complete, save and quit from `vi`. Mutt will resume, displaying a summary screen of the mail that is to be delivered. In order to send the mail, press kbd:[y]. An example of the summary screen can be seen below: image::mutt3.png[Mutt email client showing the summary screen] Mutt contains extensive help which can be accessed from most of the menus by pressing kbd:[?]. The top line also displays the keyboard shortcuts where appropriate. [[alpine-command]] === alpine alpine is aimed at a beginner user, but also includes some advanced features. [WARNING] ==== alpine has had several remote vulnerabilities discovered in the past, which allowed remote attackers to execute arbitrary code as users on the local system, by the action of sending a specially-prepared email. While _known_ problems have been fixed, alpine code is written in an insecure style and the FreeBSD Security Officer believes there are likely to be other undiscovered vulnerabilities. Users install alpine at their own risk. ==== The current version of alpine may be installed using the package:mail/alpine[] port. Once the port has installed, alpine can be started by issuing the following command: [source,shell] .... % alpine .... The first time alpine runs, it displays a greeting page with a brief introduction, as well as a request from the alpine development team to send an anonymous email message allowing them to judge how many users are using their client. To send this anonymous message, press kbd:[Enter]. Alternatively, press kbd:[E] to exit the greeting without sending an anonymous message. An example of the greeting page is shown below: image::pine1.png[alpine email client showing the greeting page] The main menu is then presented, which can be navigated using the cursor keys. This main menu provides shortcuts for the composing new mails, browsing mail directories, and administering address book entries. Below the main menu, relevant keyboard shortcuts to perform functions specific to the task at hand are shown. The default directory opened by alpine is [.filename]#inbox#. To view the message index, press kbd:[I], or select the [.guimenuitem]#MESSAGE INDEX# option shown below: image::pine2.png[alpine email client showing the default directory] The message index shows messages in the current directory and can be navigated by using the cursor keys. Highlighted messages can be read by pressing kbd:[Enter]. image::pine3.png[alpine email client showing the message index] In the screenshot below, a sample message is displayed by alpine. Contextual keyboard shortcuts are displayed at the bottom of the screen. An example of one of a shortcut is kbd:[r], which tells the MUA to reply to the current message being displayed. image::pine4.png[alpine email client showing an email] Replying to an email in alpine is done using the pico editor, which is installed by default with alpine. pico makes it easy to navigate the message and is easier for novice users to use than man:vi[1] or man:mail[1]. Once the reply is complete, the message can be sent by pressing kbd:[Ctrl+X]. alpine will ask for confirmation before sending the message. image::pine5.png[alpine email client showing the message compose window] alpine can be customized using the [.guimenuitem]#SETUP# option from the main menu. [[mail-advanced]] == Advanced Topics This section covers more involved topics such as mail configuration and setting up mail for an entire domain. [[mail-config]] === Basic Configuration Out of the box, one can send email to external hosts as long as [.filename]#/etc/resolv.conf# is configured or the network has access to a configured DNS server. To have email delivered to the MTA on the FreeBSD host, do one of the following: * Run a DNS server for the domain. * Get mail delivered directly to the FQDN for the machine. In order to have mail delivered directly to a host, it must have a permanent static IP address, not a dynamic IP address. If the system is behind a firewall, it must be configured to allow SMTP traffic. To receive mail directly at a host, one of these two must be configured: * Make sure that the lowest-numbered MX record in DNS points to the host's static IP address. * Make sure there is no MX entry in the DNS for the host. Either of the above will allow mail to be received directly at the host. Try this: [source,shell] .... # hostname .... The output should be similar to the following: [.programlisting] .... example.FreeBSD.org .... [source,shell] .... # host example.FreeBSD.org .... The output should be similar to the following: [.programlisting] .... example.FreeBSD.org has address 204.216.27.XX .... In this example, mail sent directly to mailto:yourlogin@example.FreeBSD.org[yourlogin@example.FreeBSD.org] should work without problems, assuming a full-featured MTA is running correctly on `example.FreeBSD.org`. Note that man:dma[8] does not listen on port 25 for incoming connections and cannot be used in this scenario. For this example: [source,shell] .... # host example.FreeBSD.org .... The output should be similar to the following: [.programlisting] .... example.FreeBSD.org has address 204.216.27.XX example.FreeBSD.org mail is handled (pri=10) by nevdull.FreeBSD.org .... All mail sent to `example.FreeBSD.org` will be collected on `nevdull` under the same username instead of being sent directly to your host. The above information is handled by the DNS server. The DNS record that carries mail routing information is the link:https://en.wikipedia.org/wiki/MX_record[mail exchanger record (MX record)]. If no MX record exists, mail will be delivered directly to the host by way of its IP address. The MX entry for `freefall.FreeBSD.org` at one time looked like this: [.programlisting] .... freefall MX 30 mail.crl.net freefall MX 40 agora.rdrop.com freefall MX 10 freefall.FreeBSD.org freefall MX 20 who.cdrom.com .... `freefall` had many MX entries. The lowest MX number is the host that receives mail directly, if available. If it is not accessible for some reason, the next lower-numbered host will accept messages temporarily, and pass it along when a lower-numbered host becomes available. Alternate MX sites should have separate Internet connections in order to be most useful. Your ISP can provide this service. [[mail-domain]] === Mail for a Domain When configuring an MTA for a network, any mail sent to hosts in its domain should be diverted to the MTA so that users can receive their mail on the master mail server. To make life easiest, a user account with the same _username_ should exist on both the MTA and the system with the MUA. Use man:adduser[8] to create the user accounts. [TIP] ==== In addition to adding local users to the host, there are alternative methods known as virtual users. Programs like link:https://www.cyrusimap.org/[Cyrus] and link:https://www.dovecot.org/[Dovecot] can be integrated into MTAs to handle users, mail storage, and also provide access via POP3 and IMAP. ==== The MTA must be the designated mail exchanger for each workstation on the network. This is done in the DNS configuration with an MX record: [.programlisting] .... example.FreeBSD.org A 204.216.27.XX ; Workstation MX 10 nevdull.FreeBSD.org ; Mailhost .... This will redirect mail for the workstation to the MTA no matter where the A record points. The mail is sent to the MX host. This must be configured on a DNS server. If the network does not run its own DNS server, talk to the ISP or DNS provider. The following is an example of virtual email hosting. Consider a customer with the domain `customer1.org`, where all the mail for `customer1.org` should be sent to `mail.myhost.com`. The DNS entry should look like this: [.programlisting] .... customer1.org MX 10 mail.myhost.com .... An `A` record is _not_ needed for `customer1.org` in order to only handle email for that domain. However, running `ping` against `customer1.org` will not work unless an `A` record exists for it. Tell the MTA which domains and/or hostnames it should accept mail for. Either of the following will work for Sendmail: * Add the hosts to [.filename]#/etc/mail/local-host-names# when using the `FEATURE(use_cw_file)`. * Add a `Cwyour.host.com` line to [.filename]#/etc/sendmail.cf#. [[outgoing-only]] === Setting Up to Send Only There are many instances where one may only want to send mail through a relay. Some examples are: * The computer is a desktop machine that needs to use programs such as man:mail[1], using the ISP's mail relay. * The computer is a server that does not handle mail locally, but needs to pass off all mail to a relay for processing. While any MTA is capable of filling this particular niche, it can be difficult to properly configure a full-featured MTA just to handle offloading mail. Programs such as Sendmail and Postfix are overkill for this use. Additionally, a typical Internet access service agreement may forbid one from running a "mail server". The easiest way to fulfill those needs is to use the man:dma[8] MTA included in the <>. For systems up to 13.2, need be to installed from ports. In addition to man:dma[8], third-party software can be used to achieve the same, like package:mail/ssmtp[]. [source,shell] .... # cd /usr/ports/mail/ssmtp # make install replace clean .... Once installed, package:mail/ssmtp[] can be configured with [.filename]#/usr/local/etc/ssmtp/ssmtp.conf#: [.programlisting] .... root=yourrealemail@example.com mailhub=mail.example.com rewriteDomain=example.com hostname=_HOSTNAME_ .... Use the real email address for `root`. Enter the ISP's outgoing mail relay in place of `mail.example.com`. Some ISPs call this the "outgoing mail server" or "SMTP server". Make sure to disable Sendmail, including the outgoing mail service. See <> for details. package:mail/ssmtp[] has some other options available. Refer to the examples in [.filename]#/usr/local/etc/ssmtp# or the manual page of ssmtp for more information. Setting up ssmtp in this manner allows any software on the computer that needs to send mail to function properly, while not violating the ISP's usage policy or allowing the computer to be hijacked for spamming. [[SMTP-Auth]] === SMTP Authentication in Sendmail Configuring SMTP authentication on the MTA provides a number of benefits. SMTP authentication adds a layer of security to Sendmail, and provides mobile users who switch hosts the ability to use the same MTA without the need to reconfigure their mail client's settings each time. Install package:security/cyrus-sasl2[] from the Ports Collection. This port supports a number of compile-time options. For the SMTP authentication method demonstrated in this example, make sure that `LOGIN` is not disabled. After installing package:security/cyrus-sasl2[], edit [.filename]#/usr/local/lib/sasl2/Sendmail.conf#, or create it if it does not exist, and add the following line: [.programlisting] .... pwcheck_method: saslauthd .... Next, install package:security/cyrus-sasl2-saslauthd[] and add execute the following command: [source,shell] .... # sysrc saslauthd_enable="YES" .... Finally, start the saslauthd daemon: [source,shell] .... # service saslauthd start .... This daemon serves as a broker for Sendmail to authenticate against the FreeBSD man:passwd[5] database. This saves the trouble of creating a new set of usernames and passwords for each user that needs to use SMTP authentication, and keeps the login and mail password the same. Next, edit [.filename]#/etc/make.conf# and add the following lines: [.programlisting] .... SENDMAIL_CFLAGS=-I/usr/local/include/sasl -DSASL SENDMAIL_LDADD=/usr/local/lib/libsasl2.so .... These lines provide Sendmail the proper configuration options for linking to package:cyrus-sasl2[] at compile time. Make sure that package:cyrus-sasl2[] has been installed before recompiling Sendmail. Recompile Sendmail by executing the following commands: [source,shell] .... # cd /usr/src/lib/libsmutil # make cleandir && make obj && make # cd /usr/src/lib/libsm # make cleandir && make obj && make # cd /usr/src/usr.sbin/sendmail # make cleandir && make obj && make && make install .... This compile should not have any problems if [.filename]#/usr/src# has not changed extensively and the shared libraries it needs are available. After Sendmail has been compiled and reinstalled, edit [.filename]#/etc/mail/freebsd.mc# or the local [.filename]#.mc#. Many administrators choose to use the output from man:hostname[1] as the name of [.filename]#.mc# for uniqueness. Add these lines: [.programlisting] .... dnl set SASL options TRUST_AUTH_MECH(`GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl define(`confAUTH_MECHANISMS', `GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl .... These options configure the different methods available to Sendmail for authenticating users. To use a method other than pwcheck, refer to the Sendmail documentation. Finally, run man:make[1] while in [.filename]#/etc/mail#. That will run the new [.filename]#.mc# and create a [.filename]#.cf# named either [.filename]#freebsd.cf# or the name used for the local [.filename]#.mc#. Then, run `make install restart`, which will copy the file to [.filename]#sendmail.cf#, and properly restart Sendmail. For more information about this process, refer to [.filename]#/etc/mail/Makefile#. To test the configuration, use a MUA to send a test message. For further investigation, set the `LogLevel` of Sendmail to `13` and watch [.filename]#/var/log/maillog# for any errors. For more information, refer to http://www.sendmail.org/~ca/email/auth.html[SMTP authentication]. diff --git a/documentation/content/en/books/handbook/network-servers/_index.adoc b/documentation/content/en/books/handbook/network-servers/_index.adoc index c0ac490c5b..daf764ed0c 100644 --- a/documentation/content/en/books/handbook/network-servers/_index.adoc +++ b/documentation/content/en/books/handbook/network-servers/_index.adoc @@ -1,3019 +1,3019 @@ --- title: Chapter 32. Network Servers part: IV. Network Communication prev: books/handbook/mail next: books/handbook/firewalls description: This chapter covers some of the more frequently used network services on UNIX systems tags: ["network", "servers", "inetd", "NFS", "NIS", "LDAP", "DHCP", "DNS", "Apache HTTP", "FTP", "Samba", "NTP", "iSCSI"] showBookMenu: true weight: 37 path: "/books/handbook/" --- [[network-servers]] = Network Servers :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 32 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/network-servers/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[network-servers-synopsis]] == Synopsis This chapter covers some of the more frequently used network services on UNIX(R) systems. This includes installing, configuring, testing, and maintaining many different types of network services. Example configuration files are included throughout this chapter for reference. By the end of this chapter, readers will know: * How to manage the inetd daemon. * How to set up the Network File System (NFS). * How to set up the Network Information Server (NIS) for centralizing and sharing user accounts. * How to set FreeBSD up to act as an LDAP server or client * How to set up automatic network settings using DHCP. * How to set up a Domain Name Server (DNS). * How to set up the Apache HTTP Server. * How to set up a File Transfer Protocol (FTP) server. * How to set up a file and print server for Windows(R) clients using Samba. * How to synchronize the time and date, and set up a time server using the Network Time Protocol (NTP). * How to set up iSCSI. This chapter assumes a basic knowledge of: * [.filename]#/etc/rc# scripts. * Network terminology. * Installation of additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [[network-inetd]] == The inetd Super-Server The man:inetd[8] daemon is sometimes referred to as a Super-Server because it manages connections for many services. Instead of starting multiple applications, only the inetd service needs to be started. When a connection is received for a service that is managed by inetd, it determines which program the connection is destined for, spawns a process for that program, and delegates the program a socket. Using inetd for services that are not heavily used can reduce system load, when compared to running each daemon individually in stand-alone mode. Primarily, inetd is used to spawn other daemons, but several trivial protocols are handled internally, such as chargen, auth, time, echo, discard, and daytime. This section covers the basics of configuring inetd. [[network-inetd-conf]] === Configuration File Configuration of inetd is done by editing [.filename]#/etc/inetd.conf#. Each line of this configuration file represents an application which can be started by inetd. By default, every line starts with a comment (`+#+`), meaning that inetd is not listening for any applications. To configure inetd to listen for an application's connections, remove the `+#+` at the beginning of the line for that application. After saving your edits, configure inetd to start at system boot by editing [.filename]#/etc/rc.conf#: [.programlisting] .... inetd_enable="YES" .... To start inetd now, so that it listens for the service you configured, type: [source,shell] .... # service inetd start .... Once inetd is started, it needs to be notified whenever a modification is made to [.filename]#/etc/inetd.conf#: [[network-inetd-reread]] .Reloading the inetd Configuration File [example] ==== [source,shell] .... # service inetd reload .... ==== Typically, the default entry for an application does not need to be edited beyond removing the `+#+`. In some situations, it may be appropriate to edit the default entry. As an example, this is the default entry for man:ftpd[8] over IPv4: [.programlisting] .... ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l .... The seven columns in an entry are as follows: [.programlisting] .... service-name socket-type protocol {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]] user[:group][/login-class] server-program server-program-arguments .... where: service-name:: The service name of the daemon to start. It must correspond to a service listed in [.filename]#/etc/services#. This determines which port inetd listens on for incoming connections to that service. When using a custom service, it must first be added to [.filename]#/etc/services#. socket-type:: Either `stream`, `dgram`, `raw`, or `seqpacket`. Use `stream` for TCP connections and `dgram` for UDP services. protocol:: Use one of the following protocol names: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Protocol Name | Explanation |tcp or tcp4 |TCP IPv4 |udp or udp4 |UDP IPv4 |tcp6 |TCP IPv6 |udp6 |UDP IPv6 |tcp46 |Both TCP IPv4 and IPv6 |udp46 |Both UDP IPv4 and IPv6 |=== {wait|nowait}[/max-child[/max-connections-per-ip-per-minute[/max-child-per-ip]]]:: In this field, `wait` or `nowait` must be specified. `max-child`, `max-connections-per-ip-per-minute` and `max-child-per-ip` are optional. + `wait|nowait` indicates whether or not the service is able to handle its own socket. `dgram` socket types must use `wait` while `stream` daemons, which are usually multi-threaded, should use `nowait`. `wait` usually hands off multiple sockets to a single daemon, while `nowait` spawns a child daemon for each new socket. + The maximum number of child daemons inetd may spawn is set by `max-child`. For example, to limit ten instances of the daemon, place a `/10` after `nowait`. Specifying `/0` allows an unlimited number of children. + `max-connections-per-ip-per-minute` limits the number of connections from any particular IP address per minute. Once the limit is reached, further connections from this IP address will be dropped until the end of the minute. For example, a value of `/10` would limit any particular IP address to ten connection attempts per minute. `max-child-per-ip` limits the number of child processes that can be started on behalf on any single IP address at any moment. These options can limit excessive resource consumption and help to prevent Denial of Service attacks. + An example can be seen in the default settings for man:fingerd[8]: + [.programlisting] .... finger stream tcp nowait/3/10 nobody /usr/libexec/fingerd fingerd -k -s .... user:: The username the daemon will run as. Daemons typically run as `root`, `daemon`, or `nobody`. server-program:: The full path to the daemon. If the daemon is a service provided by inetd internally, use `internal`. server-program-arguments:: Used to specify any command arguments to be passed to the daemon on invocation. If the daemon is an internal service, use `internal`. [[network-inetd-cmdline]] === Command-Line Options Like most server daemons, inetd has a number of options that can be used to modify its behavior. By default, inetd is started with `-wW -C 60`. These options enable TCP wrappers for all services, including internal services, and prevent any IP address from requesting any service more than 60 times per minute. To change the default options which are passed to inetd, add an entry for `inetd_flags` in [.filename]#/etc/rc.conf#. If inetd is already running, restart it with `service inetd restart`. The available rate limiting options are: -c maximum:: Specify the default maximum number of simultaneous invocations of each service, where the default is unlimited. May be overridden on a per-service basis by using `max-child` in [.filename]#/etc/inetd.conf#. -C rate:: Specify the default maximum number of times a service can be invoked from a single IP address per minute. May be overridden on a per-service basis by using `max-connections-per-ip-per-minute` in [.filename]#/etc/inetd.conf#. -R rate:: Specify the maximum number of times a service can be invoked in one minute, where the default is `256`. A rate of `0` allows an unlimited number. -s maximum:: Specify the maximum number of times a service can be invoked from a single IP address at any one time, where the default is unlimited. May be overridden on a per-service basis by using `max-child-per-ip` in [.filename]#/etc/inetd.conf#. Additional options are available. Refer to man:inetd[8] for the full list of options. [[network-inetd-security]] === Security Considerations Many of the daemons which can be managed by inetd are not security-conscious. Some daemons, such as fingerd, can provide information that may be useful to an attacker. Only enable the services which are needed and monitor the system for excessive connection attempts. `max-connections-per-ip-per-minute`, `max-child` and `max-child-per-ip` can be used to limit such attacks. By default, TCP wrappers are enabled. Consult man:hosts_access[5] for more information on placing TCP restrictions on various inetd invoked daemons. [[network-nfs]] == Network File System (NFS) FreeBSD supports the Network File System (NFS), which allows a server to share directories and files with clients over a network. With NFS, users and programs can access files on remote systems as if they were stored locally. NFS has many practical uses. Some of the more common uses include: * Data that would otherwise be duplicated on each client can be kept in a single location and accessed by clients on the network. * Several clients may need access to the [.filename]#/usr/ports/distfiles# directory. Sharing that directory allows for quick access to the source files without having to download them to each client. * On large networks, it is often more convenient to configure a central NFS server on which all user home directories are stored. Users can log into a client anywhere on the network and have access to their home directories. * Administration of NFS exports is simplified. For example, there is only one file system where security or backup policies must be set. * Removable media storage devices can be used by other machines on the network. This reduces the number of devices throughout the network and provides a centralized location to manage their security. It is often more convenient to install software on multiple machines from a centralized installation media. NFS consists of a server and one or more clients. The client remotely accesses the data that is stored on the server machine. In order for this to function properly, a few processes have to be configured and running. These daemons must be running on the server: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Daemon | Description |nfsd |The NFS daemon which services requests from NFS clients. |mountd |The NFS mount daemon which carries out requests received from nfsd. |rpcbind | This daemon allows NFS clients to discover which port the NFS server is using. |=== Running man:nfsiod[8] on the client can improve performance, but is not required. [[network-configuring-nfs]] === Configuring the Server The file systems which the NFS server will share are specified in [.filename]#/etc/exports#. Each line in this file specifies a file system to be exported, which clients have access to that file system, and any access options. When adding entries to this file, each exported file system, its properties, and allowed hosts must occur on a single line. If no clients are listed in the entry, then any client on the network can mount that file system. The following [.filename]#/etc/exports# entries demonstrate how to export file systems. The examples can be modified to match the file systems and client names on the reader's network. There are many options that can be used in this file, but only a few will be mentioned here. See man:exports[5] for the full list of options. This example shows how to export [.filename]#/cdrom# to three hosts named _alpha_, _bravo_, and _charlie_: [.programlisting] .... /cdrom -ro alpha bravo charlie .... The `-ro` flag makes the file system read-only, preventing clients from making any changes to the exported file system. This example assumes that the host names are either in DNS or in [.filename]#/etc/hosts#. Refer to man:hosts[5] if the network does not have a DNS server. The next example exports [.filename]#/home# to three clients by IP address. This can be useful for networks without DNS or [.filename]#/etc/hosts# entries. The `-alldirs` flag allows subdirectories to be mount points. In other words, it will not automatically mount the subdirectories, but will permit the client to mount the directories that are required as needed. [.programlisting] .... /usr/home -alldirs 10.0.0.2 10.0.0.3 10.0.0.4 .... This next example exports [.filename]#/a# so that two clients from different domains may access that file system. The `-maproot=root` allows `root` on the remote system to write data on the exported file system as `root`. If `-maproot=root` is not specified, the client's `root` user will be mapped to the server's `nobody` account and will be subject to the access limitations defined for `nobody`. [.programlisting] .... /a -maproot=root host.example.com box.example.org .... A client can only be specified once per file system. For example, if [.filename]#/usr# is a single file system, these entries would be invalid as both entries specify the same host: [.programlisting] .... # Invalid when /usr is one file system /usr/src client /usr/ports client .... The correct format for this situation is to use one entry: [.programlisting] .... /usr/src /usr/ports client .... The following is an example of a valid export list, where [.filename]#/usr# and [.filename]#/exports# are local file systems: [.programlisting] .... # Export src and ports to client01 and client02, but only # client01 has root privileges on it /usr/src /usr/ports -maproot=root client01 /usr/src /usr/ports client02 # The client machines have root and can mount anywhere # on /exports. Anyone in the world can mount /exports/obj read-only /exports -alldirs -maproot=root client01 client02 /exports/obj -ro .... To enable the processes required by the NFS server at boot time, add these options to [.filename]#/etc/rc.conf#: [.programlisting] .... rpcbind_enable="YES" nfs_server_enable="YES" mountd_enable="YES" .... The server can be started now by running this command: [source,shell] .... # service nfsd start .... Whenever the NFS server is started, mountd also starts automatically. However, mountd only reads [.filename]#/etc/exports# when it is started. To make subsequent [.filename]#/etc/exports# edits take effect immediately, force mountd to reread it: [source,shell] .... # service mountd reload .... Refer to man:nfsv4[4] for a description of an NFS Version 4 setup. === Configuring the Client To enable NFS clients, set this option in each client's [.filename]#/etc/rc.conf#: [.programlisting] .... nfs_client_enable="YES" .... Then, run this command on each NFS client: [source,shell] .... # service nfsclient start .... The client now has everything it needs to mount a remote file system. In these examples, the server's name is `server` and the client's name is `client`. To mount [.filename]#/home# on `server` to the [.filename]#/mnt# mount point on `client`: [source,shell] .... # mount server:/home /mnt .... The files and directories in [.filename]#/home# will now be available on `client`, in the [.filename]#/mnt# directory. To mount a remote file system each time the client boots, add it to [.filename]#/etc/fstab#: [.programlisting] .... server:/home /mnt nfs rw 0 0 .... Refer to man:fstab[5] for a description of all available options. === Locking Some applications require file locking to operate correctly. To enable locking, execute the following command on both the client and server: [source,shell] .... # sysrc rpc_lockd_enable="YES" .... Then start the service: [source,shell] .... # service lockd start .... If locking is not required on the server, the NFS client can be configured to lock locally by including `-L` when running mount. Refer to man:mount_nfs[8] for further details. [[network-autofs]] === Automating Mounts with man:autofs[5] [NOTE] ==== The man:autofs[5] automount facility is supported starting with FreeBSD 10.1-RELEASE. To use the automounter functionality in older versions of FreeBSD, use man:amd[8] instead. This chapter only describes the man:autofs[5] automounter. ==== The man:autofs[5] facility is a common name for several components that, together, allow for automatic mounting of remote and local filesystems whenever a file or directory within that file system is accessed. It consists of the kernel component, man:autofs[5], and several userspace applications: man:automount[8], man:automountd[8] and man:autounmountd[8]. It serves as an alternative for man:amd[8] from previous FreeBSD releases. amd is still provided for backward compatibility purposes, as the two use different map formats; the one used by autofs is the same as with other SVR4 automounters, such as the ones in Solaris, MacOS X, and Linux. The man:autofs[5] virtual filesystem is mounted on specified mountpoints by man:automount[8], usually invoked during boot. Whenever a process attempts to access a file within the man:autofs[5] mountpoint, the kernel will notify man:automountd[8] daemon and pause the triggering process. The man:automountd[8] daemon will handle kernel requests by finding the proper map and mounting the filesystem according to it, then signal the kernel to release blocked process. The man:autounmountd[8] daemon automatically unmounts automounted filesystems after some time, unless they are still being used. The primary autofs configuration file is [.filename]#/etc/auto_master#. It assigns individual maps to top-level mounts. For an explanation of [.filename]#auto_master# and the map syntax, refer to man:auto_master[5]. There is a special automounter map mounted on [.filename]#/net#. When a file is accessed within this directory, man:autofs[5] looks up the corresponding remote mount and automatically mounts it. For instance, an attempt to access a file within [.filename]#/net/foobar/usr# would tell man:automountd[8] to mount the [.filename]#/usr# export from the host `foobar`. .Mounting an Export with man:autofs[5] [example] ==== In this example, `showmount -e` shows the exported file systems that can be mounted from the NFS server, `foobar`: [source,shell] .... % showmount -e foobar Exports list on foobar: /usr 10.10.10.0 /a 10.10.10.0 % cd /net/foobar/usr .... ==== The output from `showmount` shows [.filename]#/usr# as an export. When changing directories to [.filename]#/host/foobar/usr#, man:automountd[8] intercepts the request and attempts to resolve the hostname `foobar`. If successful, man:automountd[8] automatically mounts the source export. To enable man:autofs[5] at boot time, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... autofs_enable="YES" .... Then man:autofs[5] can be started by running: [source,shell] .... # service automount start # service automountd start # service autounmountd start .... The man:autofs[5] map format is the same as in other operating systems. Information about this format from other sources can be useful, like the http://web.archive.org/web/20160813071113/http://images.apple.com/business/docs/Autofs.pdf[Mac OS X document]. Consult the man:automount[8], man:automountd[8], man:autounmountd[8], and man:auto_master[5] manual pages for more information. [[network-nis]] == Network Information System (NIS) Network Information System (NIS) is designed to centralize administration of UNIX(R)-like systems such as Solaris(TM), HP-UX, AIX(R), Linux, NetBSD, OpenBSD, and FreeBSD. NIS was originally known as Yellow Pages but the name was changed due to trademark issues. This is the reason why NIS commands begin with `yp`. NIS is a Remote Procedure Call (RPC)-based client/server system that allows a group of machines within an NIS domain to share a common set of configuration files. This permits a system administrator to set up NIS client systems with only minimal configuration data and to add, remove, or modify configuration data from a single location. FreeBSD uses version 2 of the NIS protocol. === NIS Terms and Processes Table 28.1 summarizes the terms and important processes used by NIS: .NIS Terminology [cols="1,1", frame="none", options="header"] |=== | Term | Description |NIS domain name |NIS servers and clients share an NIS domain name. Typically, this name does not have anything to do with DNS. |man:rpcbind[8] |This service enables RPC and must be running in order to run an NIS server or act as an NIS client. |man:ypbind[8] |This service binds an NIS client to its NIS server. It will take the NIS domain name and use RPC to connect to the server. It is the core of client/server communication in an NIS environment. If this service is not running on a client machine, it will not be able to access the NIS server. |man:ypserv[8] |This is the process for the NIS server. If this service stops running, the server will no longer be able to respond to NIS requests so hopefully, there is a slave server to take over. Some non-FreeBSD clients will not try to reconnect using a slave server and the ypbind process may need to be restarted on these clients. |man:rpc.yppasswdd[8] |This process only runs on NIS master servers. This daemon allows NIS clients to change their NIS passwords. If this daemon is not running, users will have to login to the NIS master server and change their passwords there. |=== === Machine Types There are three types of hosts in an NIS environment: * NIS master server + This server acts as a central repository for host configuration information and maintains the authoritative copy of the files used by all of the NIS clients. The [.filename]#passwd#, [.filename]#group#, and other various files used by NIS clients are stored on the master server. While it is possible for one machine to be an NIS master server for more than one NIS domain, this type of configuration will not be covered in this chapter as it assumes a relatively small-scale NIS environment. * NIS slave servers + NIS slave servers maintain copies of the NIS master's data files in order to provide redundancy. Slave servers also help to balance the load of the master server as NIS clients always attach to the NIS server which responds first. * NIS clients + NIS clients authenticate against the NIS server during log on. Information in many files can be shared using NIS. The [.filename]#master.passwd#, [.filename]#group#, and [.filename]#hosts# files are commonly shared via NIS. Whenever a process on a client needs information that would normally be found in these files locally, it makes a query to the NIS server that it is bound to instead. === Planning Considerations This section describes a sample NIS environment which consists of 15 FreeBSD machines with no centralized point of administration. Each machine has its own [.filename]#/etc/passwd# and [.filename]#/etc/master.passwd#. These files are kept in sync with each other only through manual intervention. Currently, when a user is added to the lab, the process must be repeated on all 15 machines. The configuration of the lab will be as follows: [.informaltable] [cols="1,1,1", frame="none", options="header"] |=== | Machine name | IP address | Machine role |`ellington` |`10.0.0.2` |NIS master |`coltrane` |`10.0.0.3` |NIS slave |`basie` |`10.0.0.4` |Faculty workstation |`bird` |`10.0.0.5` |Client machine |`cli[1-11]` |`10.0.0.[6-17]` |Other client machines |=== If this is the first time an NIS scheme is being developed, it should be thoroughly planned ahead of time. Regardless of network size, several decisions need to be made as part of the planning process. ==== Choosing a NIS Domain Name When a client broadcasts its requests for info, it includes the name of the NIS domain that it is part of. This is how multiple servers on one network can tell which server should answer which request. Think of the NIS domain name as the name for a group of hosts. Some organizations choose to use their Internet domain name for their NIS domain name. This is not recommended as it can cause confusion when trying to debug network problems. The NIS domain name should be unique within the network and it is helpful if it describes the group of machines it represents. For example, the Art department at Acme Inc. might be in the "acme-art" NIS domain. This example will use the domain name `test-domain`. However, some non-FreeBSD operating systems require the NIS domain name to be the same as the Internet domain name. If one or more machines on the network have this restriction, the Internet domain name _must_ be used as the NIS domain name. ==== Physical Server Requirements There are several things to keep in mind when choosing a machine to use as a NIS server. Since NIS clients depend upon the availability of the server, choose a machine that is not rebooted frequently. The NIS server should ideally be a stand alone machine whose sole purpose is to be an NIS server. If the network is not heavily used, it is acceptable to put the NIS server on a machine running other services. However, if the NIS server becomes unavailable, it will adversely affect all NIS clients. === Configuring the NIS Master Server The canonical copies of all NIS files are stored on the master server. The databases used to store the information are called NIS maps. In FreeBSD, these maps are stored in [.filename]#/var/yp/[domainname]# where [.filename]#[domainname]# is the name of the NIS domain. Since multiple domains are supported, it is possible to have several directories, one for each domain. Each domain will have its own independent set of maps. NIS master and slave servers handle all NIS requests through man:ypserv[8]. This daemon is responsible for receiving incoming requests from NIS clients, translating the requested domain and map name to a path to the corresponding database file, and transmitting data from the database back to the client. Setting up a master NIS server can be relatively straight forward, depending on environmental needs. Since FreeBSD provides built-in NIS support, it only needs to be enabled by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nisdomainname="test-domain" <.> nis_server_enable="YES" <.> nis_yppasswdd_enable="YES" <.> .... <.> This line sets the NIS domain name to `test-domain`. <.> This automates the start up of the NIS server processes when the system boots. <.> This enables the man:rpc.yppasswdd[8] daemon so that users can change their NIS password from a client machine. Care must be taken in a multi-server domain where the server machines are also NIS clients. It is generally a good idea to force the servers to bind to themselves rather than allowing them to broadcast bind requests and possibly become bound to each other. Strange failure modes can result if one server goes down and others are dependent upon it. Eventually, all the clients will time out and attempt to bind to other servers, but the delay involved can be considerable and the failure mode is still present since the servers might bind to each other all over again. A server that is also a client can be forced to bind to a particular server by adding these additional lines to [.filename]#/etc/rc.conf#: [.programlisting] .... nis_client_enable="YES" <.> nis_client_flags="-S test-domain,server" <.> .... <.> This enables running client stuff as well. <.> This line sets the NIS domain name to `test-domain` and bind to itself. After saving the edits, type `/etc/netstart` to restart the network and apply the values defined in [.filename]#/etc/rc.conf#. Before initializing the NIS maps, start man:ypserv[8]: [source,shell] .... # service ypserv start .... ==== Initializing the NIS Maps NIS maps are generated from the configuration files in [.filename]#/etc# on the NIS master, with one exception: [.filename]#/etc/master.passwd#. This is to prevent the propagation of passwords to all the servers in the NIS domain. Therefore, before the NIS maps are initialized, configure the primary password files: [source,shell] .... # cp /etc/master.passwd /var/yp/master.passwd # cd /var/yp # vi master.passwd .... It is advisable to remove all entries for system accounts as well as any user accounts that do not need to be propagated to the NIS clients, such as the `root` and any other administrative accounts. [NOTE] ==== Ensure that the [.filename]#/var/yp/master.passwd# is neither group or world readable by setting its permissions to `600`. ==== After completing this task, initialize the NIS maps. FreeBSD includes the man:ypinit[8] script to do this. When generating maps for the master server, include `-m` and specify the NIS domain name: [source,shell] .... ellington# ypinit -m test-domain Server Type: MASTER Domain: test-domain Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. At this point, we have to construct a list of this domains YP servers. rod.darktech.org is already known as master server. Please continue to add any slave servers, one per line. When you are done with the list, type a . master server : ellington next host to add: coltrane next host to add: ^D The current list of NIS servers looks like this: ellington coltrane Is this correct? [y/n: y] y [..output from map generation..] NIS Map update completed. ellington has been setup as an YP master server without any errors. .... This will create [.filename]#/var/yp/Makefile# from [.filename]#/var/yp/Makefile.dist#. By default, this file assumes that the environment has a single NIS server with only FreeBSD clients. Since `test-domain` has a slave server, edit this line in [.filename]#/var/yp/Makefile# so that it begins with a comment (`+#+`): [.programlisting] .... NOPUSH = "True" .... ==== Adding New Users Every time a new user is created, the user account must be added to the master NIS server and the NIS maps rebuilt. Until this occurs, the new user will not be able to login anywhere except on the NIS master. For example, to add the new user `jsmith` to the `test-domain` domain, run these commands on the master server: [source,shell] .... # pw useradd jsmith # cd /var/yp # make test-domain .... The user could also be added using `adduser jsmith` instead of `pw useradd smith`. === Setting up a NIS Slave Server To set up an NIS slave server, log on to the slave server and edit [.filename]#/etc/rc.conf# as for the master server. Do not generate any NIS maps, as these already exist on the master server. When running `ypinit` on the slave server, use `-s` (for slave) instead of `-m` (for master). This option requires the name of the NIS master in addition to the domain name, as seen in this example: [source,shell] .... coltrane# ypinit -s ellington test-domain Server Type: SLAVE Domain: test-domain Master: ellington Creating an YP server will require that you answer a few questions. Questions will all be asked at the beginning of the procedure. Do you want this procedure to quit on non-fatal errors? [y/n: n] n Ok, please remember to go back and redo manually whatever fails. If not, something might not work. There will be no further questions. The remainder of the procedure should take a few minutes, to copy the databases from ellington. Transferring netgroup... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byuser... ypxfr: Exiting: Map successfully transferred Transferring netgroup.byhost... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byuid... ypxfr: Exiting: Map successfully transferred Transferring passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring group.bygid... ypxfr: Exiting: Map successfully transferred Transferring group.byname... ypxfr: Exiting: Map successfully transferred Transferring services.byname... ypxfr: Exiting: Map successfully transferred Transferring rpc.bynumber... ypxfr: Exiting: Map successfully transferred Transferring rpc.byname... ypxfr: Exiting: Map successfully transferred Transferring protocols.byname... ypxfr: Exiting: Map successfully transferred Transferring master.passwd.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byname... ypxfr: Exiting: Map successfully transferred Transferring networks.byaddr... ypxfr: Exiting: Map successfully transferred Transferring netid.byname... ypxfr: Exiting: Map successfully transferred Transferring hosts.byaddr... ypxfr: Exiting: Map successfully transferred Transferring protocols.bynumber... ypxfr: Exiting: Map successfully transferred Transferring ypservers... ypxfr: Exiting: Map successfully transferred Transferring hosts.byname... ypxfr: Exiting: Map successfully transferred coltrane has been setup as an YP slave server without any errors. Remember to update map ypservers on ellington. .... This will generate a directory on the slave server called [.filename]#/var/yp/test-domain# which contains copies of the NIS master server's maps. Adding these [.filename]#/etc/crontab# entries on each slave server will force the slaves to sync their maps with the maps on the master server: [.programlisting] .... 20 * * * * root /usr/libexec/ypxfr passwd.byname 21 * * * * root /usr/libexec/ypxfr passwd.byuid .... These entries are not mandatory because the master server automatically attempts to push any map changes to its slaves. However, since clients may depend upon the slave server to provide correct password information, it is recommended to force frequent password map updates. This is especially important on busy networks where map updates might not always complete. To finish the configuration, run `/etc/netstart` on the slave server in order to start the NIS services. === Setting Up an NIS Client An NIS client binds to an NIS server using man:ypbind[8]. This daemon broadcasts RPC requests on the local network. These requests specify the domain name configured on the client. If an NIS server in the same domain receives one of the broadcasts, it will respond to ypbind, which will record the server's address. If there are several servers available, the client will use the address of the first server to respond and will direct all of its NIS requests to that server. The client will automatically ping the server on a regular basis to make sure it is still available. If it fails to receive a reply within a reasonable amount of time, ypbind will mark the domain as unbound and begin broadcasting again in the hopes of locating another server. To configure a FreeBSD machine to be an NIS client: [.procedure] ==== . Edit [.filename]#/etc/rc.conf# and add the following lines in order to set the NIS domain name and start man:ypbind[8] during network startup: + [.programlisting] .... nisdomainname="test-domain" nis_client_enable="YES" .... . To import all possible password entries from the NIS server, use `vipw` to remove all user accounts except one from [.filename]#/etc/master.passwd#. When removing the accounts, keep in mind that at least one local account should remain and this account should be a member of `wheel`. If there is a problem with NIS, this local account can be used to log in remotely, become the superuser, and fix the problem. Before saving the edits, add the following line to the end of the file: + [.programlisting] .... +::::::::: .... + This line configures the client to provide anyone with a valid account in the NIS server's password maps an account on the client. There are many ways to configure the NIS client by modifying this line. One method is described in <>. For more detailed reading, refer to the book `Managing NFS and NIS`, published by O'Reilly Media. . To import all possible group entries from the NIS server, add this line to [.filename]#/etc/group#: + [.programlisting] .... +:*:: .... ==== To start the NIS client immediately, execute the following commands as the superuser: [source,shell] .... # /etc/netstart # service ypbind start .... After completing these steps, running `ypcat passwd` on the client should show the server's [.filename]#passwd# map. === NIS Security Since RPC is a broadcast-based service, any system running ypbind within the same domain can retrieve the contents of the NIS maps. To prevent unauthorized transactions, man:ypserv[8] supports a feature called "securenets" which can be used to restrict access to a given set of hosts. By default, this information is stored in [.filename]#/var/yp/securenets#, unless man:ypserv[8] is started with `-p` and an alternate path. This file contains entries that consist of a network specification and a network mask separated by white space. Lines starting with `+"#"+` are considered to be comments. A sample [.filename]#securenets# might look like this: [.programlisting] .... # allow connections from local host -- mandatory 127.0.0.1 255.255.255.255 # allow connections from any host # on the 192.168.128.0 network 192.168.128.0 255.255.255.0 # allow connections from any host # between 10.0.0.0 to 10.0.15.255 # this includes the machines in the testlab 10.0.0.0 255.255.240.0 .... If man:ypserv[8] receives a request from an address that matches one of these rules, it will process the request normally. If the address fails to match a rule, the request will be ignored and a warning message will be logged. If the [.filename]#securenets# does not exist, `ypserv` will allow connections from any host. crossref:security[tcpwrappers,"TCP Wrapper"] is an alternate mechanism for providing access control instead of [.filename]#securenets#. While either access control mechanism adds some security, they are both vulnerable to "IP spoofing" attacks. All NIS-related traffic should be blocked at the firewall. Servers using [.filename]#securenets# may fail to serve legitimate NIS clients with archaic TCP/IP implementations. Some of these implementations set all host bits to zero when doing broadcasts or fail to observe the subnet mask when calculating the broadcast address. While some of these problems can be fixed by changing the client configuration, other problems may force the retirement of these client systems or the abandonment of [.filename]#securenets#. The use of TCP Wrapper increases the latency of the NIS server. The additional delay may be long enough to cause timeouts in client programs, especially in busy networks with slow NIS servers. If one or more clients suffer from latency, convert those clients into NIS slave servers and force them to bind to themselves. ==== Barring Some Users In this example, the `basie` system is a faculty workstation within the NIS domain. The [.filename]#passwd# map on the master NIS server contains accounts for both faculty and students. This section demonstrates how to allow faculty logins on this system while refusing student logins. To prevent specified users from logging on to a system, even if they are present in the NIS database, use `vipw` to add `-_username_` with the correct number of colons towards the end of [.filename]#/etc/master.passwd# on the client, where _username_ is the username of a user to bar from logging in. The line with the blocked user must be before the `+` line that allows NIS users. In this example, `bill` is barred from logging on to `basie`: [source,shell] .... basie# cat /etc/master.passwd root:[password]:0:0::0:0:The super-user:/root:/bin/csh toor:[password]:0:0::0:0:The other super-user:/root:/bin/sh daemon:*:1:1::0:0:Owner of many system processes:/root:/usr/sbin/nologin operator:*:2:5::0:0:System &:/:/usr/sbin/nologin bin:*:3:7::0:0:Binaries Commands and Source,,,:/:/usr/sbin/nologin tty:*:4:65533::0:0:Tty Sandbox:/:/usr/sbin/nologin kmem:*:5:65533::0:0:KMem Sandbox:/:/usr/sbin/nologin games:*:7:13::0:0:Games pseudo-user:/usr/games:/usr/sbin/nologin news:*:8:8::0:0:News Subsystem:/:/usr/sbin/nologin man:*:9:9::0:0:Mister Man Pages:/usr/share/man:/usr/sbin/nologin bind:*:53:53::0:0:Bind Sandbox:/:/usr/sbin/nologin uucp:*:66:66::0:0:UUCP pseudo-user:/var/spool/uucppublic:/usr/libexec/uucp/uucico xten:*:67:67::0:0:X-10 daemon:/usr/local/xten:/usr/sbin/nologin pop:*:68:6::0:0:Post Office Owner:/nonexistent:/usr/sbin/nologin nobody:*:65534:65534::0:0:Unprivileged user:/nonexistent:/usr/sbin/nologin -bill::::::::: +::::::::: basie# .... [[network-netgroups]] === Using Netgroups Barring specified users from logging on to individual systems becomes unscaleable on larger networks and quickly loses the main benefit of NIS: _centralized_ administration. Netgroups were developed to handle large, complex networks with hundreds of users and machines. Their use is comparable to UNIX(R) groups, where the main difference is the lack of a numeric ID and the ability to define a netgroup by including both user accounts and other netgroups. To expand on the example used in this chapter, the NIS domain will be extended to add the users and systems shown in Tables 28.2 and 28.3: .Additional Users [cols="1,1", frame="none", options="header"] |=== | User Name(s) | Description |`alpha`, `beta` |IT department employees |`charlie`, `delta` |IT department apprentices |`echo`, `foxtrott`, `golf`, ... |employees |`able`, `baker`, ... |interns |=== .Additional Systems [cols="1,1", frame="none", options="header"] |=== | Machine Name(s) | Description |`war`, `death`, `famine`, `pollution` |Only IT employees are allowed to log onto these servers. |`pride`, `greed`, `envy`, `wrath`, `lust`, `sloth` |All members of the IT department are allowed to login onto these servers. |`one`, `two`, `three`, `four`, ... |Ordinary workstations used by employees. |`trashcan` |A very old machine without any critical data. Even interns are allowed to use this system. |=== When using netgroups to configure this scenario, each user is assigned to one or more netgroups and logins are then allowed or forbidden for all members of the netgroup. When adding a new machine, login restrictions must be defined for all netgroups. When a new user is added, the account must be added to one or more netgroups. If the NIS setup is planned carefully, only one central configuration file needs modification to grant or deny access to machines. The first step is the initialization of the NIS`netgroup` map. In FreeBSD, this map is not created by default. On the NIS master server, use an editor to create a map named [.filename]#/var/yp/netgroup#. This example creates four netgroups to represent IT employees, IT apprentices, employees, and interns: [.programlisting] .... IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) USERS (,echo,test-domain) (,foxtrott,test-domain) \ (,golf,test-domain) INTERNS (,able,test-domain) (,baker,test-domain) .... Each entry configures a netgroup. The first column in an entry is the name of the netgroup. Each set of parentheses represents either a group of one or more users or the name of another netgroup. When specifying a user, the three comma-delimited fields inside each group represent: . The name of the host(s) where the other fields representing the user are valid. If a hostname is not specified, the entry is valid on all hosts. . The name of the account that belongs to this netgroup. . The NIS domain for the account. Accounts may be imported from other NIS domains into a netgroup. If a group contains multiple users, separate each user with whitespace. Additionally, each field may contain wildcards. See man:netgroup[5] for details. Netgroup names longer than 8 characters should not be used. The names are case sensitive and using capital letters for netgroup names is an easy way to distinguish between user, machine and netgroup names. Some non-FreeBSD NIS clients cannot handle netgroups containing more than 15 entries. This limit may be circumvented by creating several sub-netgroups with 15 users or fewer and a real netgroup consisting of the sub-netgroups, as seen in this example: [.programlisting] .... BIGGRP1 (,joe1,domain) (,joe2,domain) (,joe3,domain) [...] BIGGRP2 (,joe16,domain) (,joe17,domain) [...] BIGGRP3 (,joe31,domain) (,joe32,domain) BIGGROUP BIGGRP1 BIGGRP2 BIGGRP3 .... Repeat this process if more than 225 (15 times 15) users exist within a single netgroup. To activate and distribute the new NIS map: [source,shell] .... ellington# cd /var/yp ellington# make .... This will generate the three NIS maps [.filename]#netgroup#, [.filename]#netgroup.byhost# and [.filename]#netgroup.byuser#. Use the map key option of man:ypcat[1] to check if the new NIS maps are available: [source,shell] .... ellington% ypcat -k netgroup ellington% ypcat -k netgroup.byhost ellington% ypcat -k netgroup.byuser .... The output of the first command should resemble the contents of [.filename]#/var/yp/netgroup#. The second command only produces output if host-specific netgroups were created. The third command is used to get the list of netgroups for a user. To configure a client, use man:vipw[8] to specify the name of the netgroup. For example, on the server named `war`, replace this line: [.programlisting] .... +::::::::: .... with [.programlisting] .... +@IT_EMP::::::::: .... This specifies that only the users defined in the netgroup `IT_EMP` will be imported into this system's password database and only those users are allowed to login to this system. This configuration also applies to the `~` function of the shell and all routines which convert between user names and numerical user IDs. In other words, `cd ~_user_` will not work, `ls -l` will show the numerical ID instead of the username, and `find . -user joe -print` will fail with the message `No such user`. To fix this, import all user entries without allowing them to login into the servers. This can be achieved by adding an extra line: [.programlisting] .... +:::::::::/usr/sbin/nologin .... This line configures the client to import all entries but to replace the shell in those entries with [.filename]#/usr/sbin/nologin#. Make sure that extra line is placed _after_ `+@IT_EMP:::::::::`. Otherwise, all user accounts imported from NIS will have [.filename]#/usr/sbin/nologin# as their login shell and no one will be able to login to the system. To configure the less important servers, replace the old `+:::::::::` on the servers with these lines: [.programlisting] .... +@IT_EMP::::::::: +@IT_APP::::::::: +:::::::::/usr/sbin/nologin .... The corresponding lines for the workstations would be: [.programlisting] .... +@IT_EMP::::::::: +@USERS::::::::: +:::::::::/usr/sbin/nologin .... NIS supports the creation of netgroups from other netgroups which can be useful if the policy regarding user access changes. One possibility is the creation of role-based netgroups. For example, one might create a netgroup called `BIGSRV` to define the login restrictions for the important servers, another netgroup called `SMALLSRV` for the less important servers, and a third netgroup called `USERBOX` for the workstations. Each of these netgroups contains the netgroups that are allowed to login onto these machines. The new entries for the NIS`netgroup` map would look like this: [.programlisting] .... BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS .... This method of defining login restrictions works reasonably well when it is possible to define groups of machines with identical restrictions. Unfortunately, this is the exception and not the rule. Most of the time, the ability to define login restrictions on a per-machine basis is required. Machine-specific netgroup definitions are another possibility to deal with the policy changes. In this scenario, the [.filename]#/etc/master.passwd# of each system contains two lines starting with "+". The first line adds a netgroup with the accounts allowed to login onto this machine and the second line adds all other accounts with [.filename]#/usr/sbin/nologin# as shell. It is recommended to use the "ALL-CAPS" version of the hostname as the name of the netgroup: [.programlisting] .... +@BOXNAME::::::::: +:::::::::/usr/sbin/nologin .... Once this task is completed on all the machines, there is no longer a need to modify the local versions of [.filename]#/etc/master.passwd# ever again. All further changes can be handled by modifying the NIS map. Here is an example of a possible `netgroup` map for this scenario: [.programlisting] .... # Define groups of users first IT_EMP (,alpha,test-domain) (,beta,test-domain) IT_APP (,charlie,test-domain) (,delta,test-domain) DEPT1 (,echo,test-domain) (,foxtrott,test-domain) DEPT2 (,golf,test-domain) (,hotel,test-domain) DEPT3 (,india,test-domain) (,juliet,test-domain) ITINTERN (,kilo,test-domain) (,lima,test-domain) D_INTERNS (,able,test-domain) (,baker,test-domain) # # Now, define some groups based on roles USERS DEPT1 DEPT2 DEPT3 BIGSRV IT_EMP IT_APP SMALLSRV IT_EMP IT_APP ITINTERN USERBOX IT_EMP ITINTERN USERS # # And a groups for a special tasks # Allow echo and golf to access our anti-virus-machine SECURITY IT_EMP (,echo,test-domain) (,golf,test-domain) # # machine-based netgroups # Our main servers WAR BIGSRV FAMINE BIGSRV # User india needs access to this server POLLUTION BIGSRV (,india,test-domain) # # This one is really important and needs more access restrictions DEATH IT_EMP # # The anti-virus-machine mentioned above ONE SECURITY # # Restrict a machine to a single user TWO (,hotel,test-domain) # [...more groups to follow] .... It may not always be advisable to use machine-based netgroups. When deploying a couple of dozen or hundreds of systems, role-based netgroups instead of machine-based netgroups may be used to keep the size of the NIS map within reasonable limits. === Password Formats NIS requires that all hosts within an NIS domain use the same format for encrypting passwords. If users have trouble authenticating on an NIS client, it may be due to a differing password format. In a heterogeneous network, the format must be supported by all operating systems, where DES is the lowest common standard. To check which format a server or client is using, look at this section of [.filename]#/etc/login.conf#: [.programlisting] .... default:\ :passwd_format=des:\ :copyright=/etc/COPYRIGHT:\ [Further entries elided] .... In this example, the system is using the DES format for password hashing. Other possible values include `blf` for Blowfish, `md5` for MD5, `sha256` and `sha512` for SHA-256 and SHA-512 respectively. For more information and the up to date list of what is available on your system, consult the man:crypt[3] manpage. If the format on a host needs to be edited to match the one being used in the NIS domain, the login capability database must be rebuilt after saving the change: [source,shell] .... # cap_mkdb /etc/login.conf .... [NOTE] ==== The format of passwords for existing user accounts will not be updated until each user changes their password _after_ the login capability database is rebuilt. ==== [[network-ldap]] == Lightweight Directory Access Protocol (LDAP) The Lightweight Directory Access Protocol (LDAP) is an application layer protocol used to access, modify, and authenticate objects using a distributed directory information service. Think of it as a phone or record book which stores several levels of hierarchical, homogeneous information. It is used in Active Directory and OpenLDAP networks and allows users to access to several levels of internal information utilizing a single account. For example, email authentication, pulling employee contact information, and internal website authentication might all make use of a single user account in the LDAP server's record base. This section provides a quick start guide for configuring an LDAP server on a FreeBSD system. It assumes that the administrator already has a design plan which includes the type of information to store, what that information will be used for, which users should have access to that information, and how to secure this information from unauthorized access. === LDAP Terminology and Structure LDAP uses several terms which should be understood before starting the configuration. All directory entries consist of a group of _attributes_. Each of these attribute sets contains a unique identifier known as a _Distinguished Name_ (DN) which is normally built from several other attributes such as the common or _Relative Distinguished Name_ (RDN). Similar to how directories have absolute and relative paths, consider a DN as an absolute path and the RDN as the relative path. An example LDAP entry looks like the following. This example searches for the entry for the specified user account (`uid`), organizational unit (`ou`), and organization (`o`): [source,shell] .... % ldapsearch -xb "uid=trhodes,ou=users,o=example.com" # extended LDIF # # LDAPv3 # base with scope subtree # filter: (objectclass=*) # requesting: ALL # # trhodes, users, example.com dn: uid=trhodes,ou=users,o=example.com mail: trhodes@example.com cn: Tom Rhodes uid: trhodes telephoneNumber: (123) 456-7890 # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... This example entry shows the values for the `dn`, `mail`, `cn`, `uid`, and `telephoneNumber` attributes. The cn attribute is the RDN. More information about LDAP and its terminology can be found at http://www.openldap.org/doc/admin24/intro.html[http://www.openldap.org/doc/admin24/intro.html]. [[ldap-config]] === Configuring an LDAP Server FreeBSD does not provide a built-in LDAP server. Begin the configuration by installing package:net/openldap-server[] package or port: [source,shell] .... # pkg install openldap-server .... There is a large set of default options enabled in the extref:{linux-users}[package, software]. Review them by running `pkg info openldap-server`. If they are not sufficient (for example if SQL support is needed), please consider recompiling the port using the appropriate crossref:ports[ports-using,framework]. The installation creates the directory [.filename]#/var/db/openldap-data# to hold the data. The directory to store the certificates must be created: [source,shell] .... # mkdir /usr/local/etc/openldap/private .... The next phase is to configure the Certificate Authority. The following commands must be executed from [.filename]#/usr/local/etc/openldap/private#. This is important as the file permissions need to be restrictive and users should not have access to these files. More detailed information about certificates and their parameters can be found in crossref:security[openssl,"OpenSSL"]. To create the Certificate Authority, start with this command and follow the prompts: [source,shell] .... # openssl req -days 365 -nodes -new -x509 -keyout ca.key -out ../ca.crt .... The entries for the prompts may be generic _except_ for the `Common Name`. This entry must be _different_ than the system hostname. If this will be a self signed certificate, prefix the hostname with `CA` for Certificate Authority. The next task is to create a certificate signing request and a private key. Input this command and follow the prompts: [source,shell] .... # openssl req -days 365 -nodes -new -keyout server.key -out server.csr .... During the certificate generation process, be sure to correctly set the `Common Name` attribute. The Certificate Signing Request must be signed with the Certificate Authority in order to be used as a valid certificate: [source,shell] .... # openssl x509 -req -days 365 -in server.csr -out ../server.crt -CA ../ca.crt -CAkey ca.key -CAcreateserial .... The final part of the certificate generation process is to generate and sign the client certificates: [source,shell] .... # openssl req -days 365 -nodes -new -keyout client.key -out client.csr # openssl x509 -req -days 3650 -in client.csr -out ../client.crt -CA ../ca.crt -CAkey ca.key .... Remember to use the same `Common Name` attribute when prompted. When finished, ensure that a total of eight (8) new files have been generated through the proceeding commands. The daemon running the OpenLDAP server is [.filename]#slapd#. Its configuration is performed through [.filename]#slapd.ldif#: the old [.filename]#slapd.conf# has been deprecated by OpenLDAP. http://www.openldap.org/doc/admin24/slapdconf2.html[Configuration examples] for [.filename]#slapd.ldif# are available and can also be found in [.filename]#/usr/local/etc/openldap/slapd.ldif.sample#. Options are documented in slapd-config(5). Each section of [.filename]#slapd.ldif#, like all the other LDAP attribute sets, is uniquely identified through a DN. Be sure that no blank lines are left between the `dn:` statement and the desired end of the section. In the following example, TLS will be used to implement a secure channel. The first section represents the global configuration: [.programlisting] .... # # See slapd-config(5) for details on configuration options. # This file should NOT be world readable. # dn: cn=config objectClass: olcGlobal cn: config # # # Define global ACLs to disable default read access. # olcArgsFile: /var/run/openldap/slapd.args olcPidFile: /var/run/openldap/slapd.pid olcTLSCertificateFile: /usr/local/etc/openldap/server.crt olcTLSCertificateKeyFile: /usr/local/etc/openldap/private/server.key olcTLSCACertificateFile: /usr/local/etc/openldap/ca.crt #olcTLSCipherSuite: HIGH olcTLSProtocolMin: 3.1 olcTLSVerifyClient: never .... The Certificate Authority, server certificate and server private key files must be specified here. It is recommended to let the clients choose the security cipher and omit option `olcTLSCipherSuite` (incompatible with TLS clients other than [.filename]#openssl#). Option `olcTLSProtocolMin` lets the server require a minimum security level: it is recommended. While verification is mandatory for the server, it is not for the client: `olcTLSVerifyClient: never`. The second section is about the backend modules and can be configured as follows: [.programlisting] .... # # Load dynamic backend modules: # dn: cn=module,cn=config objectClass: olcModuleList cn: module olcModulepath: /usr/local/libexec/openldap olcModuleload: back_mdb.la #olcModuleload: back_bdb.la #olcModuleload: back_hdb.la #olcModuleload: back_ldap.la #olcModuleload: back_passwd.la #olcModuleload: back_shell.la .... The third section is devoted to load the needed `ldif` schemas to be used by the databases: they are essential. [.programlisting] .... dn: cn=schema,cn=config objectClass: olcSchemaConfig cn: schema include: file:///usr/local/etc/openldap/schema/core.ldif include: file:///usr/local/etc/openldap/schema/cosine.ldif include: file:///usr/local/etc/openldap/schema/inetorgperson.ldif include: file:///usr/local/etc/openldap/schema/nis.ldif .... Next, the frontend configuration section: [.programlisting] .... # Frontend settings # dn: olcDatabase={-1}frontend,cn=config objectClass: olcDatabaseConfig objectClass: olcFrontendConfig olcDatabase: {-1}frontend olcAccess: to * by * read # # Sample global access control policy: # Root DSE: allow anyone to read it # Subschema (sub)entry DSE: allow anyone to read it # Other DSEs: # Allow self write access # Allow authenticated users read access # Allow anonymous users to authenticate # #olcAccess: to dn.base="" by * read #olcAccess: to dn.base="cn=Subschema" by * read #olcAccess: to * # by self write # by users read # by anonymous auth # # if no access controls are present, the default policy # allows anyone and everyone to read anything but restricts # updates to rootdn. (e.g., "access to * by * read") # # rootdn can always read and write EVERYTHING! # olcPasswordHash: {SSHA} # {SSHA} is already the default for olcPasswordHash .... Another section is devoted to the _configuration backend_, the only way to later access the OpenLDAP server configuration is as a global super-user. [.programlisting] .... dn: olcDatabase={0}config,cn=config objectClass: olcDatabaseConfig olcDatabase: {0}config olcAccess: to * by * none olcRootPW: {SSHA}iae+lrQZILpiUdf16Z9KmDmSwT77Dj4U .... The default administrator username is `cn=config`. Type [.filename]#slappasswd# in a shell, choose a password and use its hash in `olcRootPW`. If this option is not specified now, before [.filename]#slapd.ldif# is imported, no one will be later able to modify the _global configuration_ section. The last section is about the database backend: [.programlisting] .... ####################################################################### # LMDB database definitions ####################################################################### # dn: olcDatabase=mdb,cn=config objectClass: olcDatabaseConfig objectClass: olcMdbConfig olcDatabase: mdb olcDbMaxSize: 1073741824 olcSuffix: dc=domain,dc=example olcRootDN: cn=mdbadmin,dc=domain,dc=example # Cleartext passwords, especially for the rootdn, should # be avoided. See slappasswd(8) and slapd-config(5) for details. # Use of strong authentication encouraged. olcRootPW: {SSHA}X2wHvIWDk6G76CQyCMS1vDCvtICWgn0+ # The database directory MUST exist prior to running slapd AND # should only be accessible by the slapd and slap tools. # Mode 700 recommended. olcDbDirectory: /var/db/openldap-data # Indices to maintain olcDbIndex: objectClass eq .... This database hosts the _actual contents_ of the LDAP directory. Types other than `mdb` are available. Its super-user, not to be confused with the global one, is configured here: a (possibly custom) username in `olcRootDN` and the password hash in `olcRootPW`; [.filename]#slappasswd# can be used as before. This http://www.openldap.org/devel/gitweb.cgi?p=openldap.git;a=tree;f=tests/data/regressions/its8444;h=8a5e808e63b0de3d2bdaf2cf34fecca8577ca7fd;hb=HEAD[repository] contains four examples of [.filename]#slapd.ldif#. To convert an existing [.filename]#slapd.conf# into [.filename]#slapd.ldif#, refer to http://www.openldap.org/doc/admin24/slapdconf2.html[this page] (please note that this may introduce some unuseful options). When the configuration is completed, [.filename]#slapd.ldif# must be placed in an empty directory. It is recommended to create it as: [source,shell] .... # mkdir /usr/local/etc/openldap/slapd.d/ .... Import the configuration database: [source,shell] .... # /usr/local/sbin/slapadd -n0 -F /usr/local/etc/openldap/slapd.d/ -l /usr/local/etc/openldap/slapd.ldif .... Start the [.filename]#slapd# daemon: [source,shell] .... # /usr/local/libexec/slapd -F /usr/local/etc/openldap/slapd.d/ .... Option `-d` can be used for debugging, as specified in slapd(8). To verify that the server is running and working: [source,shell] .... # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts # extended LDIF # # LDAPv3 # base <> with scope baseObject # filter: (objectclass=*) # requesting: namingContexts # # dn: namingContexts: dc=domain,dc=example # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 .... The server must still be trusted. If that has never been done before, follow these instructions. Install the OpenSSL package or port: [source,shell] .... # pkg install openssl .... From the directory where [.filename]#ca.crt# is stored (in this example, [.filename]#/usr/local/etc/openldap#), run: [source,shell] .... # c_rehash . .... Both the CA and the server certificate are now correctly recognized in their respective roles. To verify this, run this command from the [.filename]#server.crt# directory: [source,shell] .... # openssl verify -verbose -CApath . server.crt .... If [.filename]#slapd# was running, restart it. As stated in [.filename]#/usr/local/etc/rc.d/slapd#, to properly run [.filename]#slapd# at boot the following lines must be added to [.filename]#/etc/rc.conf#: [.programlisting] .... slapd_enable="YES" slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://0.0.0.0/"' slapd_sockets="/var/run/openldap/ldapi" slapd_cn_config="YES" .... [.filename]#slapd# does not provide debugging at boot. Check [.filename]#/var/log/debug.log#, [.filename]#dmesg -a# and [.filename]#/var/log/messages# for this purpose. The following example adds the group `team` and the user `john` to the `domain.example` LDAP database, which is still empty. First, create the file [.filename]#domain.ldif#: [source,shell] .... # cat domain.ldif dn: dc=domain,dc=example objectClass: dcObject objectClass: organization o: domain.example dc: domain dn: ou=groups,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: groups dn: ou=users,dc=domain,dc=example objectClass: top objectClass: organizationalunit ou: users dn: cn=team,ou=groups,dc=domain,dc=example objectClass: top objectClass: posixGroup cn: team gidNumber: 10001 dn: uid=john,ou=users,dc=domain,dc=example objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: John McUser uid: john uidNumber: 10001 gidNumber: 10001 homeDirectory: /home/john/ loginShell: /usr/bin/bash userPassword: secret .... See the OpenLDAP documentation for more details. Use [.filename]#slappasswd# to replace the plain text password `secret` with a hash in `userPassword`. The path specified as `loginShell` must exist in all the systems where `john` is allowed to login. Finally, use the `mdb` administrator to modify the database: [source,shell] .... # ldapadd -W -D "cn=mdbadmin,dc=domain,dc=example" -f domain.ldif .... Modifications to the _global configuration_ section can only be performed by the global super-user. For example, assume that the option `olcTLSCipherSuite: HIGH:MEDIUM:SSLv3` was initially specified and must now be deleted. First, create a file that contains the following: [source,shell] .... # cat global_mod dn: cn=config changetype: modify delete: olcTLSCipherSuite .... Then, apply the modifications: [source,shell] .... # ldapmodify -f global_mod -x -D "cn=config" -W .... When asked, provide the password chosen in the _configuration backend_ section. The username is not required: here, `cn=config` represents the DN of the database section to be modified. Alternatively, use `ldapmodify` to delete a single line of the database, `ldapdelete` to delete a whole entry. If something goes wrong, or if the global super-user cannot access the configuration backend, it is possible to delete and re-write the whole configuration: [source,shell] .... # rm -rf /usr/local/etc/openldap/slapd.d/ .... [.filename]#slapd.ldif# can then be edited and imported again. Please, follow this procedure only when no other solution is available. This is the configuration of the server only. The same machine can also host an LDAP client, with its own separate configuration. [[network-dhcp]] == Dynamic Host Configuration Protocol (DHCP) The Dynamic Host Configuration Protocol (DHCP) allows a system to connect to a network in order to be assigned the necessary addressing information for communication on that network. FreeBSD includes the OpenBSD version of `dhclient` which is used by the client to obtain the addressing information. FreeBSD does not install a DHCP server, but several servers are available in the FreeBSD Ports Collection. The DHCP protocol is fully described in http://www.freesoft.org/CIE/RFC/2131/[RFC 2131]. Informational resources are also available at http://www.isc.org/downloads/dhcp/[isc.org/downloads/dhcp/]. This section describes how to use the built-in DHCP client. It then describes how to install and configure a DHCP server. [NOTE] ==== In FreeBSD, the man:bpf[4] device is needed by both the DHCP server and DHCP client. This device is included in the [.filename]#GENERIC# kernel that is installed with FreeBSD. Users who prefer to create a custom kernel need to keep this device if DHCP is used. It should be noted that [.filename]#bpf# also allows privileged users to run network packet sniffers on that system. ==== === Configuring a DHCP Client DHCP client support is included in the FreeBSD installer, making it easy to configure a newly installed system to automatically receive its networking addressing information from an existing DHCP server. Refer to crossref:bsdinstall[bsdinstall-post,"Accounts, Time Zone, Services and Hardening"] for examples of network configuration. When `dhclient` is executed on the client machine, it begins broadcasting requests for configuration information. By default, these requests use UDP port 68. The server replies on UDP port 67, giving the client an IP address and other relevant network information such as a subnet mask, default gateway, and DNS server addresses. This information is in the form of a DHCP "lease" and is valid for a configurable time. This allows stale IP addresses for clients no longer connected to the network to automatically be reused. DHCP clients can obtain a great deal of information from the server. An exhaustive list may be found in man:dhcp-options[5]. By default, when a FreeBSD system boots, its DHCP client runs in the background, or _asynchronously_. Other startup scripts continue to run while the DHCP process completes, which speeds up system startup. Background DHCP works well when the DHCP server responds quickly to the client's requests. However, DHCP may take a long time to complete on some systems. If network services attempt to run before DHCP has assigned the network addressing information, they will fail. Using DHCP in _synchronous_ mode prevents this problem as it pauses startup until the DHCP configuration has completed. This line in [.filename]#/etc/rc.conf# is used to configure background or asynchronous mode: [.programlisting] .... ifconfig_fxp0="DHCP" .... This line may already exist if the system was configured to use DHCP during installation. Replace the _fxp0_ shown in these examples with the name of the interface to be dynamically configured, as described in crossref:config[config-network-setup,“Setting Up Network Interface Cards”]. To instead configure the system to use synchronous mode, and to pause during startup while DHCP completes, use "`SYNCDHCP`": [.programlisting] .... ifconfig_fxp0="SYNCDHCP" .... Additional client options are available. Search for `dhclient` in man:rc.conf[5] for details. The DHCP client uses the following files: * [.filename]#/etc/dhclient.conf# + The configuration file used by `dhclient`. Typically, this file contains only comments as the defaults are suitable for most clients. This configuration file is described in man:dhclient.conf[5]. * [.filename]#/sbin/dhclient# + More information about the command itself can be found in man:dhclient[8]. * [.filename]#/sbin/dhclient-script# + The FreeBSD-specific DHCP client configuration script. It is described in man:dhclient-script[8], but should not need any user modification to function properly. * [.filename]#/var/db/dhclient.leases.interface# + The DHCP client keeps a database of valid leases in this file, which is written as a log and is described in man:dhclient.leases[5]. [[network-dhcp-server]] === Installing and Configuring a DHCP Server This section demonstrates how to configure a FreeBSD system to act as a DHCP server using the Internet Systems Consortium (ISC) implementation of the DHCP server. This implementation and its documentation can be installed using the package:net/isc-dhcp44-server[] package or port. The installation of package:net/isc-dhcp44-server[] installs a sample configuration file. Copy [.filename]#/usr/local/etc/dhcpd.conf.example# to [.filename]#/usr/local/etc/dhcpd.conf# and make any edits to this new file. The configuration file is comprised of declarations for subnets and hosts which define the information that is provided to DHCP clients. For example, these lines configure the following: [.programlisting] .... option domain-name "example.org";<.> option domain-name-servers ns1.example.org;<.> option subnet-mask 255.255.255.0;<.> default-lease-time 600;<.> max-lease-time 72400;<.> ddns-update-style none;<.> subnet 10.254.239.0 netmask 255.255.255.224 { range 10.254.239.10 10.254.239.20;<.> option routers rtr-239-0-1.example.org, rtr-239-0-2.example.org;<.> } host fantasia { hardware ethernet 08:00:07:26:c0:a5;<.> fixed-address fantasia.fugue.com;<.> } .... <.> This option specifies the default search domain that will be provided to clients. Refer to man:resolv.conf[5] for more information. <.> This option specifies a comma separated list of DNS servers that the client should use. They can be listed by their Fully Qualified Domain Names (FQDN), as seen in the example, or by their IP addresses. <.> The subnet mask that will be provided to clients. <.> The default lease expiry time in seconds. A client can be configured to override this value. <.> The maximum allowed length of time, in seconds, for a lease. Should a client request a longer lease, a lease will still be issued, but it will only be valid for `max-lease-time`. <.> The default of `none` disables dynamic DNS updates. Changing this to `interim` configures the DHCP server to update a DNS server whenever it hands out a lease so that the DNS server knows which IP addresses are associated with which computers in the network. Do not change the default setting unless the DNS server has been configured to support dynamic DNS. <.> This line creates a pool of available IP addresses which are reserved for allocation to DHCP clients. The range of addresses must be valid for the network or subnet specified in the previous line. <.> Declares the default gateway that is valid for the network or subnet specified before the opening `{` bracket. <.> Specifies the hardware MAC address of a client so that the DHCP server can recognize the client when it makes a request. <.> Specifies that this host should always be given the same IP address. Using the hostname is correct, since the DHCP server will resolve the hostname before returning the lease information. This configuration file supports many more options. Refer to dhcpd.conf(5), installed with the server, for details and examples. Once the configuration of [.filename]#dhcpd.conf# is complete, enable the DHCP server in [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" dhcpd_ifaces="dc0" .... Replace the `dc0` with the interface (or interfaces, separated by whitespace) that the DHCP server should listen on for DHCP client requests. Start the server by issuing the following command: [source,shell] .... # service isc-dhcpd start .... Any future changes to the configuration of the server will require the dhcpd service to be stopped and then started using man:service[8]. The DHCP server uses the following files. Note that the manual pages are installed with the server software. * [.filename]#/usr/local/sbin/dhcpd# + More information about the dhcpd server can be found in dhcpd(8). * [.filename]#/usr/local/etc/dhcpd.conf# + The server configuration file needs to contain all the information that should be provided to clients, along with information regarding the operation of the server. This configuration file is described in dhcpd.conf(5). * [.filename]#/var/db/dhcpd.leases# + The DHCP server keeps a database of leases it has issued in this file, which is written as a log. Refer to dhcpd.leases(5), which gives a slightly longer description. * [.filename]#/usr/local/sbin/dhcrelay# + This daemon is used in advanced environments where one DHCP server forwards a request from a client to another DHCP server on a separate network. If this functionality is required, install the package:net/isc-dhcp44-relay[] package or port. The installation includes dhcrelay(8) which provides more detail. [[network-dns]] == Domain Name System (DNS) Domain Name System (DNS) is the protocol through which domain names are mapped to IP addresses, and vice versa. DNS is coordinated across the Internet through a somewhat complex system of authoritative root, Top Level Domain (TLD), and other smaller-scale name servers, which host and cache individual domain information. It is not necessary to run a name server to perform DNS lookups on a system. The following table describes some of the terms associated with DNS: .DNS Terminology [cols="1,1", frame="none", options="header"] |=== | Term | Definition |Forward DNS |Mapping of hostnames to IP addresses. |Origin |Refers to the domain covered in a particular zone file. |Resolver |A system process through which a machine queries a name server for zone information. |Reverse DNS |Mapping of IP addresses to hostnames. |Root zone |The beginning of the Internet zone hierarchy. All zones fall under the root zone, similar to how all files in a file system fall under the root directory. |Zone |An individual domain, subdomain, or portion of the DNS administered by the same authority. |=== Examples of zones: * `.` is how the root zone is usually referred to in documentation. * `org.` is a Top Level Domain (TLD) under the root zone. * `example.org.` is a zone under the `org.`TLD. * `1.168.192.in-addr.arpa` is a zone referencing all IP addresses which fall under the `192.168.1.*`IP address space. As one can see, the more specific part of a hostname appears to its left. For example, `example.org.` is more specific than `org.`, as `org.` is more specific than the root zone. The layout of each part of a hostname is much like a file system: the [.filename]#/dev# directory falls within the root, and so on. === Reasons to Run a Name Server Name servers generally come in two forms: authoritative name servers, and caching (also known as resolving) name servers. An authoritative name server is needed when: * One wants to serve DNS information to the world, replying authoritatively to queries. * A domain, such as `example.org`, is registered and IP addresses need to be assigned to hostnames under it. * An IP address block requires reverse DNS entries (IP to hostname). * A backup or second name server, called a slave, will reply to queries. A caching name server is needed when: * A local DNS server may cache and respond more quickly than querying an outside name server. When one queries for `www.FreeBSD.org`, the resolver usually queries the uplink ISP's name server, and retrieves the reply. With a local, caching DNS server, the query only has to be made once to the outside world by the caching DNS server. Additional queries will not have to go outside the local network, since the information is cached locally. === DNS Server Configuration Unbound is provided in the FreeBSD base system. By default, it will provide DNS resolution to the local machine only. While the base system package can be configured to provide resolution services beyond the local machine, it is recommended that such requirements be addressed by installing Unbound from the FreeBSD Ports Collection. To enable Unbound, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... local_unbound_enable="YES" .... Any existing nameservers in [.filename]#/etc/resolv.conf# will be configured as forwarders in the new Unbound configuration. [NOTE] ==== If any of the listed nameservers do not support DNSSEC, local DNS resolution will fail. Be sure to test each nameserver and remove any that fail the test. The following command will show the trust tree or a failure for a nameserver running on `192.168.1.1`: [source,shell] .... % drill -S FreeBSD.org @192.168.1.1 .... ==== Once each nameserver is confirmed to support DNSSEC, start Unbound: [source,shell] .... # service local_unbound onestart .... This will take care of updating [.filename]#/etc/resolv.conf# so that queries for DNSSEC secured domains will now work. For example, run the following to validate the FreeBSD.org DNSSEC trust tree: [source,shell] .... % drill -S FreeBSD.org ;; Number of trusted keys: 1 ;; Chasing: freebsd.org. A DNSSEC Trust tree: freebsd.org. (A) |---freebsd.org. (DNSKEY keytag: 36786 alg: 8 flags: 256) |---freebsd.org. (DNSKEY keytag: 32659 alg: 8 flags: 257) |---freebsd.org. (DS keytag: 32659 digest type: 2) |---org. (DNSKEY keytag: 49587 alg: 7 flags: 256) |---org. (DNSKEY keytag: 9795 alg: 7 flags: 257) |---org. (DNSKEY keytag: 21366 alg: 7 flags: 257) |---org. (DS keytag: 21366 digest type: 1) | |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) | |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) |---org. (DS keytag: 21366 digest type: 2) |---. (DNSKEY keytag: 40926 alg: 8 flags: 256) |---. (DNSKEY keytag: 19036 alg: 8 flags: 257) ;; Chase successful .... === Authoritative Name Server Configuration FreeBSD does not provide authoritative name server software in the base system. Users are encouraged to install third party applications, like package:dns/nsd[] or package:dns/bind918[] package or port. [[network-apache]] == Apache HTTP Server The open source Apache HTTP Server is the most widely used web server. FreeBSD does not install this web server by default, but it can be installed from the package:www/apache24[] package or port. This section summarizes how to configure and start version 2._x_ of the Apache HTTP Server on FreeBSD. For more detailed information about Apache 2.X and its configuration directives, refer to http://httpd.apache.org/[httpd.apache.org]. === Configuring and Starting Apache In FreeBSD, the main Apache HTTP Server configuration file is installed as [.filename]#/usr/local/etc/apache2x/httpd.conf#, where _x_ represents the version number. This ASCII text file begins comment lines with a `+#+`. The most frequently modified directives are: `ServerRoot "/usr/local"`:: Specifies the default directory hierarchy for the Apache installation. Binaries are stored in the [.filename]#bin# and [.filename]#sbin# subdirectories of the server root and configuration files are stored in the [.filename]#etc/apache2x# subdirectory. `ServerAdmin you@example.com`:: Change this to the email address to receive problems with the server. This address also appears on some server-generated pages, such as error documents. `ServerName www.example.com:80`:: Allows an administrator to set a hostname which is sent back to clients for the server. For example, `www` can be used instead of the actual hostname. If the system does not have a registered DNS name, enter its IP address instead. If the server will listen on an alternate report, change `80` to the alternate port number. `DocumentRoot "/usr/local/www/apache2_x_/data"`:: The directory where documents will be served from. By default, all requests are taken from this directory, but symbolic links and aliases may be used to point to other locations. It is always a good idea to make a backup copy of the default Apache configuration file before making changes. When the configuration of Apache is complete, save the file and verify the configuration using `apachectl`. Running `apachectl configtest` should return `Syntax OK`. To launch Apache at system startup, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... apache24_enable="YES" .... If Apache should be started with non-default options, the following line may be added to [.filename]#/etc/rc.conf# to specify the needed flags: [.programlisting] .... apache24_flags="" .... If apachectl does not report configuration errors, start `httpd` now: [source,shell] .... # service apache24 start .... The `httpd` service can be tested by entering `http://_localhost_` in a web browser, replacing _localhost_ with the fully-qualified domain name of the machine running `httpd`. The default web page that is displayed is [.filename]#/usr/local/www/apache24/data/index.html#. The Apache configuration can be tested for errors after making subsequent configuration changes while `httpd` is running using the following command: [source,shell] .... # service apache24 configtest .... [NOTE] ==== It is important to note that `configtest` is not an man:rc[8] standard, and should not be expected to work for all startup scripts. ==== === Virtual Hosting Virtual hosting allows multiple websites to run on one Apache server. The virtual hosts can be _IP-based_ or _name-based_. IP-based virtual hosting uses a different IP address for each website. Name-based virtual hosting uses the clients HTTP/1.1 headers to figure out the hostname, which allows the websites to share the same IP address. To setup Apache to use name-based virtual hosting, add a `VirtualHost` block for each website. For example, for the webserver named `www.domain.tld` with a virtual domain of `www.someotherdomain.tld`, add the following entries to [.filename]#httpd.conf#: [.programlisting] .... ServerName www.domain.tld DocumentRoot /www/domain.tld ServerName www.someotherdomain.tld DocumentRoot /www/someotherdomain.tld .... For each virtual host, replace the values for `ServerName` and `DocumentRoot` with the values to be used. For more information about setting up virtual hosts, consult the official Apache documentation at: http://httpd.apache.org/docs/vhosts/[http://httpd.apache.org/docs/vhosts/]. === Apache Modules Apache uses modules to augment the functionality provided by the basic server. Refer to http://httpd.apache.org/docs/current/mod/[http://httpd.apache.org/docs/current/mod/] for a complete listing of and the configuration details for the available modules. In FreeBSD, some modules can be compiled with the package:www/apache24[] port. Type `make config` within [.filename]#/usr/ports/www/apache24# to see which modules are available and which are enabled by default. If the module is not compiled with the port, the FreeBSD Ports Collection provides an easy way to install many modules. This section describes three of the most commonly used modules. ==== SSL support At one in point in time, support for SSL inside of Apache required a secondary module called [.filename]#mod_ssl#. This is no longer the case and the default install of Apache comes with SSL built into the web server. An example of how to enable support for SSL websites is available in the installed file, [.filename]#httpd-ssl.conf# inside of the [.filename]#/usr/local/etc/apache24/extra# directory Inside this directory is also a sample file called named [.filename]#ssl.conf-sample#. It is recommended that both files be evaluated to properly set up secure websites in the Apache web server. After the configuration of SSL is complete, the following line must be uncommented in the main [.filename]#http.conf# to activate the changes on the next restart or reload of Apache: [.programlisting] .... #Include etc/apache24/extra/httpd-ssl.conf .... [WARNING] ==== SSL version two and version three have known vulnerability issues. It is highly recommended TLS version 1.2 and 1.3 be enabled in place of the older SSL options. This can be accomplished by setting the following options in the [.filename]#ssl.conf#: ==== [.programlisting] .... SSLProtocol all -SSLv3 -SSLv2 +TLSv1.2 +TLSv1.3 SSLProxyProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 .... To complete the configuration of SSL in the web server, uncomment the following line to ensure that the configuration will be pulled into Apache during restart or reload: [.programlisting] .... # Secure (SSL/TLS) connections Include etc/apache24/extra/httpd-ssl.conf .... The following lines must also be uncommented in the [.filename]#httpd.conf# to fully support SSL in Apache: [.programlisting] .... LoadModule authn_socache_module libexec/apache24/mod_authn_socache.so LoadModule socache_shmcb_module libexec/apache24/mod_socache_shmcb.so LoadModule ssl_module libexec/apache24/mod_ssl.so .... The next step is to work with a certificate authority to have the appropriate certificates installed on the system. This will set up a chain of trust for the site and prevent any warnings of self-signed certificates. ==== [.filename]#mod_perl# The [.filename]#mod_perl# module makes it possible to write Apache modules in Perl. In addition, the persistent interpreter embedded in the server avoids the overhead of starting an external interpreter and the penalty of Perl start-up time. The [.filename]#mod_perl# can be installed using the package:www/mod_perl2[] package or port. Documentation for using this module can be found at http://perl.apache.org/docs/2.0/index.html[http://perl.apache.org/docs/2.0/index.html]. ==== [.filename]#mod_php# _PHP: Hypertext Preprocessor_ (PHP) is a general-purpose scripting language that is especially suited for web development. Capable of being embedded into HTML, its syntax draws upon C, Java(TM), and Perl with the intention of allowing web developers to write dynamically generated webpages quickly. Support for PHP for Apache and any other feature written in the language, can be added by installing the appropriate port. For all supported versions, search the package database using `pkg`: [source,shell] .... # pkg search php .... A list will be displayed including the versions and additional features they provide. The components are completely modular, meaning features are enabled by installing the appropriate port. To install PHP version 7.4 for Apache, issue the following command: [source,shell] .... # pkg install mod_php74 .... If any dependency packages need to be installed, they will be installed as well. By default, PHP will not be enabled. The following lines will need to be added to the Apache configuration file located in [.filename]#/usr/local/etc/apache24# to make it active: [.programlisting] .... SetHandler application/x-httpd-php SetHandler application/x-httpd-php-source .... In addition, the `DirectoryIndex` in the configuration file will also need to be updated and Apache will either need to be restarted or reloaded for the changes to take effect. Support for many of the PHP features may also be installed by using `pkg`. For example, to install support for XML or SSL, install their respective ports: [source,shell] .... # pkg install php74-xml php74-openssl .... As before, the Apache configuration will need to be reloaded for the changes to take effect, even in cases where it was just a module install. To perform a graceful restart to reload the configuration, issue the following command: [source,shell] .... # apachectl graceful .... Once the install is complete, there are two methods of obtaining the installed PHP support modules and the environmental information of the build. The first is to install the full PHP binary and running the command to gain the information: [source,shell] .... # pkg install php74 .... [source,shell] .... # php -i |less .... It is necessary to pass the output to a pager, such as the `more` or `less` to easier digest the amount of output. Finally, to make any changes to the global configuration of PHP there is a well documented file installed into [.filename]#/usr/local/etc/php.ini#. At the time of install, this file will not exist because there are two versions to choose from, one is [.filename]#php.ini-development# and the other is [.filename]#php.ini-production#. These are starting points to assist administrators in their deployment. ==== HTTP2 Support Apache support for the HTTP2 protocol is included by default when installing the port with `pkg`. The new version of HTTP includes many improvements over the previous version, including utilizing a single connection to a website, reducing overall roundtrips of TCP connections. Also, packet header data is compressed and HTTP2 requires encryption by default. When Apache is configured to only use HTTP2, web browsers will require secure, encrypted HTTPS connections. When Apache is configured to use both versions, HTTP1.1 will be considered a fall back option if any issues arise during the connection. While this change does require administrators to make changes, they are positive and equate to a more secure Internet for everyone. The changes are only required for sites not currently implementing SSL and TLS. [NOTE] ==== This configuration depends on the previous sections, including TLS support. It is recommended those instructions be followed before continuing with this configuration. ==== Start the process by enabling the http2 module by uncommenting the line in [.filename]#/usr/local/etc/apache24/httpd.conf# and replace the mpm_prefork module with mpm_event as the former does not support HTTP2. [.programlisting] .... LoadModule http2_module libexec/apache24/mod_http2.so LoadModule mpm_event_module libexec/apache24/mod_mpm_event.so .... [NOTE] ==== There is a separate [.filename]#mod_http2# port that is available. It exists to deliver security and bug fixes quicker than the module installed with the bundled [.filename]#apache24# port. It is not required for HTTP2 support but is available. When installed, the [.filename]#mod_h2.so# should be used in place of [.filename]#mod_http2.so# in the Apache configuration. ==== There are two methods to implement HTTP2 in Apache; one way is globally for all sites and each VirtualHost running on the system. To enable HTTP2 globally, add the following line under the ServerName directive: [.programlisting] .... Protocols h2 http/1.1 .... [NOTE] ==== To enable HTTP2 over plaintext, use h2h2chttp/1.1 in the [.filename]#httpd.conf#. ==== Having the h2c here will allow plaintext HTTP2 data to pass on the system but is not recommended. In addition, using the http/1.1 here will allow fallback to the HTTP1.1 version of the protocol should it be needed by the system. To enable HTTP2 for individual VirtualHosts, add the same line within the VirtualHost directive in either [.filename]#httpd.conf# or [.filename]#httpd-ssl.conf#. Reload the configuration using the `apachectl`[parameter]#reload# command and test the configuration either by using either of the following methods after visiting one of the hosted pages: [source,shell] .... # grep "HTTP/2.0" /var/log/httpd-access.log .... This should return something similar to the following: [.programlisting] .... 192.168.1.205 - - [18/Oct/2020:18:34:36 -0400] "GET / HTTP/2.0" 304 - 192.0.2.205 - - [18/Oct/2020:19:19:57 -0400] "GET / HTTP/2.0" 304 - 192.0.0.205 - - [18/Oct/2020:19:20:52 -0400] "GET / HTTP/2.0" 304 - 192.0.2.205 - - [18/Oct/2020:19:23:10 -0400] "GET / HTTP/2.0" 304 - .... The other method is using the web browser's built in site debugger or `tcpdump`; however, using either method is beyond the scope of this document. Support for HTTP2 reverse proxy connections by using the [.filename]#mod_proxy_http2.so# module. When configuring the ProxyPass or RewriteRules [P] statements, they should use h2:// for the connection. === Dynamic Websites In addition to mod_perl and mod_php, other languages are available for creating dynamic web content. These include Django and Ruby on Rails. ==== Django Django is a BSD-licensed framework designed to allow developers to write high performance, elegant web applications quickly. It provides an object-relational mapper so that data types are developed as Python objects. A rich dynamic database-access API is provided for those objects without the developer ever having to write SQL. It also provides an extensible template system so that the logic of the application is separated from the HTML presentation. Django depends on [.filename]#mod_python#, and an SQL database engine. In FreeBSD, the package:www/py-django[] port automatically installs [.filename]#mod_python# and supports the PostgreSQL, MySQL, or SQLite databases, with the default being SQLite. To change the database engine, type `make config` within [.filename]#/usr/ports/www/py-django#, then install the port. Once Django is installed, the application will need a project directory along with the Apache configuration in order to use the embedded Python interpreter. This interpreter is used to call the application for specific URLs on the site. To configure Apache to pass requests for certain URLs to the web application, add the following to [.filename]#httpd.conf#, specifying the full path to the project directory: [.programlisting] .... SetHandler python-program PythonPath "['/dir/to/the/django/packages/'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonAutoReload On PythonDebug On .... Refer to https://docs.djangoproject.com[https://docs.djangoproject.com] for more information on how to use Django. ==== Ruby on Rails Ruby on Rails is another open source web framework that provides a full development stack. It is optimized to make web developers more productive and capable of writing powerful applications quickly. On FreeBSD, it can be installed using the package:www/rubygem-rails[] package or port. Refer to http://guides.rubyonrails.org[http://guides.rubyonrails.org] for more information on how to use Ruby on Rails. [[network-ftp]] == File Transfer Protocol (FTP) The File Transfer Protocol (FTP) provides users with a simple way to transfer files to and from an FTP server. FreeBSD includes FTP server software, ftpd, in the base system. FreeBSD provides several configuration files for controlling access to the FTP server. This section summarizes these files. Refer to man:ftpd[8] for more details about the built-in FTP server. === Configuration The most important configuration step is deciding which accounts will be allowed access to the FTP server. A FreeBSD system has a number of system accounts which should not be allowed FTP access. The list of users disallowed any FTP access can be found in [.filename]#/etc/ftpusers#. By default, it includes system accounts. Additional users that should not be allowed access to FTP can be added. In some cases it may be desirable to restrict the access of some users without preventing them completely from using FTP. This can be accomplished be creating [.filename]#/etc/ftpchroot# as described in man:ftpchroot[5]. This file lists users and groups subject to FTP access restrictions. To enable anonymous FTP access to the server, create a user named `ftp` on the FreeBSD system. Users will then be able to log on to the FTP server with a username of `ftp` or `anonymous`. When prompted for the password, any input will be accepted, but by convention, an email address should be used as the password. The FTP server will call man:chroot[2] when an anonymous user logs in, to restrict access to only the home directory of the `ftp` user. There are two text files that can be created to specify welcome messages to be displayed to FTP clients. The contents of [.filename]#/etc/ftpwelcome# will be displayed to users before they reach the login prompt. After a successful login, the contents of [.filename]#/etc/ftpmotd# will be displayed. Note that the path to this file is relative to the login environment, so the contents of [.filename]#~ftp/etc/ftpmotd# would be displayed for anonymous users. Once the FTP server has been configured, set the appropriate variable in [.filename]#/etc/rc.conf# to start the service during boot: [.programlisting] .... ftpd_enable="YES" .... To start the service now: [source,shell] .... # service ftpd start .... Test the connection to the FTP server by typing: [source,shell] .... % ftp localhost .... The ftpd daemon uses man:syslog[3] to log messages. By default, the system log daemon will write messages related to FTP in [.filename]#/var/log/xferlog#. The location of the FTP log can be modified by changing the following line in [.filename]#/etc/syslog.conf#: [.programlisting] .... ftp.info /var/log/xferlog .... [NOTE] ==== Be aware of the potential problems involved with running an anonymous FTP server. In particular, think twice about allowing anonymous users to upload files. It may turn out that the FTP site becomes a forum for the trade of unlicensed commercial software or worse. If anonymous FTP uploads are required, then verify the permissions so that these files cannot be read by other anonymous users until they have been reviewed by an administrator. ==== [[network-samba]] == File and Print Services for Microsoft(R) Windows(R) Clients (Samba) Samba is a popular open source software package that provides file and print services using the SMB/CIFS protocol. This protocol is built into Microsoft(R) Windows(R) systems. It can be added to non-Microsoft(R) Windows(R) systems by installing the Samba client libraries. The protocol allows clients to access shared data and printers. These shares can be mapped as a local disk drive and shared printers can be used as if they were local printers. On FreeBSD, the Samba client libraries can be installed using the package:net/samba413[] port or package. The client provides the ability for a FreeBSD system to access SMB/CIFS shares in a Microsoft(R) Windows(R) network. A FreeBSD system can also be configured to act as a Samba server by installing the same package:net/samba413[] port or package. This allows the administrator to create SMB/CIFS shares on the FreeBSD system which can be accessed by clients running Microsoft(R) Windows(R) or the Samba client libraries. === Server Configuration Samba is configured in [.filename]#/usr/local/etc/smb4.conf#. This file must be created before Samba can be used. A simple [.filename]#smb4.conf# to share directories and printers with Windows(R) clients in a workgroup is shown here. For more complex setups involving LDAP or Active Directory, it is easier to use man:samba-tool[8] to create the initial [.filename]#smb4.conf#. [.programlisting] .... [global] workgroup = WORKGROUP server string = Samba Server Version %v netbios name = ExampleMachine wins support = Yes security = user passdb backend = tdbsam # Example: share /usr/src accessible only to 'developer' user [src] path = /usr/src valid users = developer writable = yes browsable = yes read only = no guest ok = no public = no create mask = 0666 directory mask = 0755 .... ==== Global Settings Settings that describe the network are added in [.filename]#/usr/local/etc/smb4.conf#: `workgroup`:: The name of the workgroup to be served. `netbios name`:: The NetBIOS name by which a Samba server is known. By default, it is the same as the first component of the host's DNS name. `server string`:: The string that will be displayed in the output of `net view` and some other networking tools that seek to display descriptive text about the server. `wins support`:: Whether Samba will act as a WINS server. Do not enable support for WINS on more than one server on the network. ==== Security Settings The most important settings in [.filename]#/usr/local/etc/smb4.conf# are the security model and the backend password format. These directives control the options: `security`:: The most common settings are `security = share` and `security = user`. If the clients use usernames that are the same as their usernames on the FreeBSD machine, user level security should be used. This is the default security policy and it requires clients to first log on before they can access shared resources. + In share level security, clients do not need to log onto the server with a valid username and password before attempting to connect to a shared resource. This was the default security model for older versions of Samba. `passdb backend`:: Samba has several different backend authentication models. Clients may be authenticated with LDAP, NIS+, an SQL database, or a modified password file. The recommended authentication method, `tdbsam`, is ideal for simple networks and is covered here. For larger or more complex networks, `ldapsam` is recommended. `smbpasswd` was the former default and is now obsolete. ==== Samba Users FreeBSD user accounts must be mapped to the `SambaSAMAccount` database for Windows(R) clients to access the share. Map existing FreeBSD user accounts using man:pdbedit[8]: [source,shell] .... # pdbedit -a -u username .... This section has only mentioned the most commonly used settings. Refer to the https://wiki.samba.org[Official Samba Wiki] for additional information about the available configuration options. === Starting Samba To enable Samba at boot time, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... samba_server_enable="YES" .... To start Samba now: [source,shell] .... # service samba_server start Performing sanity check on Samba configuration: OK Starting nmbd. Starting smbd. .... Samba consists of three separate daemons. Both the nmbd and smbd daemons are started by `samba_enable`. If winbind name resolution is also required, set: [.programlisting] .... winbindd_enable="YES" .... Samba can be stopped at any time by typing: [source,shell] .... # service samba_server stop .... Samba is a complex software suite with functionality that allows broad integration with Microsoft(R) Windows(R) networks. For more information about functionality beyond the basic configuration described here, refer to https://www.samba.org[https://www.samba.org]. [[network-ntp]] == Clock Synchronization with NTP Over time, a computer's clock is prone to drift. This is problematic as many network services require the computers on a network to share the same accurate time. Accurate time is also needed to ensure that file timestamps stay consistent. The Network Time Protocol (NTP) is one way to provide clock accuracy in a network. FreeBSD includes man:ntpd[8] which can be configured to query other NTP servers to synchronize the clock on that machine or to provide time services to other computers in the network. This section describes how to configure ntpd on FreeBSD. Further documentation can be found in [.filename]#/usr/share/doc/ntp/# in HTML format. === NTP Configuration On FreeBSD, the built-in ntpd can be used to synchronize a system's clock. ntpd is configured using man:rc.conf[5] variables and [.filename]#/etc/ntp.conf#, as detailed in the following sections. ntpd communicates with its network peers using UDP packets. Any firewalls between your machine and its NTP peers must be configured to allow UDP packets in and out on port 123. ==== The [.filename]#/etc/ntp.conf# file ntpd reads [.filename]#/etc/ntp.conf# to determine which NTP servers to query. Choosing several NTP servers is recommended in case one of the servers becomes unreachable or its clock proves unreliable. As ntpd receives responses, it favors reliable servers over the less reliable ones. The servers which are queried can be local to the network, provided by an ISP, or selected from an http://support.ntp.org/bin/view/Servers/WebHome[ online list of publicly accessible NTP servers]. When choosing a public NTP server, select one that is geographically close and review its usage policy. The `pool` configuration keyword selects one or more servers from a pool of servers. An http://support.ntp.org/bin/view/Servers/NTPPoolServers[ online list of publicly accessible NTP pools] is available, organized by geographic area. In addition, FreeBSD provides a project-sponsored pool, `0.freebsd.pool.ntp.org`. .Sample [.filename]#/etc/ntp.conf# [example] ==== This is a simple example of an [.filename]#ntp.conf# file. It can safely be used as-is; it contains the recommended `restrict` options for operation on a publicly-accessible network connection. [.programlisting] .... # Disallow ntpq control/query access. Allow peers to be added only # based on pool and server statements in this file. restrict default limited kod nomodify notrap noquery nopeer restrict source limited kod nomodify notrap noquery # Allow unrestricted access from localhost for queries and control. restrict 127.0.0.1 restrict ::1 # Add a specific server. server ntplocal.example.com iburst # Add FreeBSD pool servers until 3-6 good servers are available. tos minclock 3 maxclock 6 pool 0.freebsd.pool.ntp.org iburst # Use a local leap-seconds file. leapfile "/var/db/ntpd.leap-seconds.list" .... ==== The format of this file is described in man:ntp.conf[5]. The descriptions below provide a quick overview of just the keywords used in the sample file above. By default, an NTP server is accessible to any network host. The `restrict` keyword controls which systems can access the server. Multiple `restrict` entries are supported, each one refining the restrictions given in previous statements. The values shown in the example grant the local system full query and control access, while allowing remote systems only the ability to query the time. For more details, refer to the `Access Control Support` subsection of man:ntp.conf[5]. The `server` keyword specifies a single server to query. The file can contain multiple server keywords, with one server listed on each line. The `pool` keyword specifies a pool of servers. ntpd will add one or more servers from this pool as needed to reach the number of peers specified using the `tos minclock` value. The `iburst` keyword directs ntpd to perform a burst of eight quick packet exchanges with a server when contact is first established, to help quickly synchronize system time. The `leapfile` keyword specifies the location of a file containing information about leap seconds. The file is updated automatically by man:periodic[8]. The file location specified by this keyword must match the location set in the `ntp_db_leapfile` variable in [.filename]#/etc/rc.conf#. ==== NTP entries in [.filename]#/etc/rc.conf# Set `ntpd_enable=YES` to start ntpd at boot time. Once `ntpd_enable=YES` has been added to [.filename]#/etc/rc.conf#, ntpd can be started immediately without rebooting the system by typing: [source,shell] .... # service ntpd start .... Only `ntpd_enable` must be set to use ntpd. The [.filename]#rc.conf# variables listed below may also be set as needed. Set `ntpd_sync_on_start=YES` to allow ntpd to step the clock any amount, one time at startup. Normally ntpd will log an error message and exit if the clock is off by more than 1000 seconds. This option is especially useful on systems without a battery-backed realtime clock. Set `ntpd_oomprotect=YES` to protect the ntpd daemon from being killed by the system attempting to recover from an Out Of Memory (OOM) condition. Set `ntpd_config=` to the location of an alternate [.filename]#ntp.conf# file. Set `ntpd_flags=` to contain any other ntpd flags as needed, but avoid using these flags which are managed internally by [.filename]#/etc/rc.d/ntpd#: * `-p` (pid file location) * `-c` (set `ntpd_config=` instead) ==== ntpd and the unpriveleged `ntpd` user ntpd on FreeBSD can start and run as an unpriveleged user. Doing so requires the man:mac_ntpd[4] policy module. The [.filename]#/etc/rc.d/ntpd# startup script first examines the NTP configuration. If possible, it loads the `mac_ntpd` module, then starts ntpd as unpriveleged user `ntpd` (user id 123). To avoid problems with file and directory access, the startup script will not automatically start ntpd as `ntpd` when the configuration contains any file-related options. The presence of any of the following in `ntpd_flags` requires manual configuration as described below to run as the `ntpd` user: * -f or --driftfile * -i or --jaildir * -k or --keyfile * -l or --logfile * -s or --statsdir The presence of any of the following keywords in [.filename]#ntp.conf# requires manual configuration as described below to run as the `ntpd` user: * crypto * driftfile * key * logdir * statsdir To manually configure ntpd to run as user `ntpd` you must: * Ensure that the `ntpd` user has access to all the files and directories specified in the configuration. * Arrange for the `mac_ntpd` module to be loaded or compiled into the kernel. See man:mac_ntpd[4] for details. * Set `ntpd_user="ntpd"` in [.filename]#/etc/rc.conf# === Using NTP with a PPP Connection ntpd does not need a permanent connection to the Internet to function properly. However, if a PPP connection is configured to dial out on demand, NTP traffic should be prevented from triggering a dial out or keeping the connection alive. This can be configured with `filter` directives in [.filename]#/etc/ppp/ppp.conf#. For example: [.programlisting] .... set filter dial 0 deny udp src eq 123 # Prevent NTP traffic from initiating dial out set filter dial 1 permit 0 0 set filter alive 0 deny udp src eq 123 # Prevent incoming NTP traffic from keeping the connection open set filter alive 1 deny udp dst eq 123 # Prevent outgoing NTP traffic from keeping the connection open set filter alive 2 permit 0/0 0/0 .... For more details, refer to the `PACKET FILTERING` section in man:ppp[8] and the examples in [.filename]#/usr/share/examples/ppp/#. [NOTE] ==== Some Internet access providers block low-numbered ports, preventing NTP from functioning since replies never reach the machine. ==== [[network-iscsi]] == iSCSI Initiator and Target Configuration iSCSI is a way to share storage over a network. Unlike NFS, which works at the file system level, iSCSI works at the block device level. In iSCSI terminology, the system that shares the storage is known as the _target_. The storage can be a physical disk, or an area representing multiple disks or a portion of a physical disk. For example, if the disk(s) are formatted with ZFS, a zvol can be created to use as the iSCSI storage. The clients which access the iSCSI storage are called _initiators_. To initiators, the storage available through iSCSI appears as a raw, unformatted disk known as a LUN. Device nodes for the disk appear in [.filename]#/dev/# and the device must be separately formatted and mounted. FreeBSD provides a native, kernel-based iSCSI target and initiator. This section describes how to configure a FreeBSD system as a target or an initiator. [[network-iscsi-target]] === Configuring an iSCSI Target To configure an iSCSI target, create the [.filename]#/etc/ctl.conf# configuration file, add a line to [.filename]#/etc/rc.conf# to make sure the man:ctld[8] daemon is automatically started at boot, and then start the daemon. The following is an example of a simple [.filename]#/etc/ctl.conf# configuration file. -Refer to man:ctl.conf[5] for a more complete description of this file's available options. +Refer to man:ctl.conf[5] for a complete description of this file's available options. [.programlisting] .... portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group no-authentication portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The first entry defines the `pg0` portal group. Portal groups define which network addresses the man:ctld[8] daemon will listen on. The `discovery-auth-group no-authentication` entry indicates that any initiator is allowed to perform iSCSI target discovery without authentication. Lines three and four configure man:ctld[8] to listen on all IPv4 (`listen 0.0.0.0`) and IPv6 (`listen [::]`) addresses on the default port of 3260. It is not necessary to define a portal group as there is a built-in portal group called `default`. In this case, the difference between `default` and `pg0` is that with `default`, target discovery is always denied, while with `pg0`, it is always allowed. The second entry defines a single target. Target has two possible meanings: a machine serving iSCSI or a named group of LUNs. This example uses the latter meaning, where `iqn.2012-06.com.example:target0` is the target name. This target name is suitable for testing purposes. For actual use, change `com.example` to the real domain name, reversed. The `2012-06` represents the year and month of acquiring control of that domain name, and `target0` can be any value. Any number of targets can be defined in this configuration file. The `auth-group no-authentication` line allows all initiators to connect to the specified target and `portal-group pg0` makes the target reachable through the `pg0` portal group. The next section defines the LUN. To the initiator, each LUN will be visible as a separate disk device. Multiple LUNs can be defined for each target. Each LUN is identified by a number, where LUN 0 is mandatory. The `path /data/target0-0` line defines the full path to a file or zvol backing the LUN. That path must exist before starting man:ctld[8]. The second line is optional and specifies the size of the LUN. Next, to make sure the man:ctld[8] daemon is started at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... ctld_enable="YES" .... To start man:ctld[8] now, run this command: [source,shell] .... # service ctld start .... As the man:ctld[8] daemon is started, it reads [.filename]#/etc/ctl.conf#. If this file is edited after the daemon starts, use this command so that the changes take effect immediately: [source,shell] .... # service ctld reload .... ==== Authentication The previous example is inherently insecure as it uses no authentication, granting anyone full access to all targets. To require a username and password to access targets, modify the configuration as follows: [.programlisting] .... auth-group ag0 { chap username1 secretsecret chap username2 anothersecret } portal-group pg0 { discovery-auth-group no-authentication listen 0.0.0.0 listen [::] } target iqn.2012-06.com.example:target0 { auth-group ag0 portal-group pg0 lun 0 { path /data/target0-0 size 4G } } .... The `auth-group` section defines username and password pairs. An initiator trying to connect to `iqn.2012-06.com.example:target0` must first specify a defined username and secret. However, target discovery is still permitted without authentication. To require target discovery authentication, set `discovery-auth-group` to a defined `auth-group` name instead of `no-authentication`. It is common to define a single exported target for every initiator. As a shorthand for the syntax above, the username and password can be specified directly in the target entry: [.programlisting] .... target iqn.2012-06.com.example:target0 { portal-group pg0 chap username1 secretsecret lun 0 { path /data/target0-0 size 4G } } .... [[network-iscsi-initiator]] === Configuring an iSCSI Initiator [NOTE] ==== The iSCSI initiator described in this section is supported starting with FreeBSD 10.0-RELEASE. To use the iSCSI initiator available in older versions, refer to man:iscontrol[8]. ==== The iSCSI initiator requires that the man:iscsid[8] daemon is running. This daemon does not use a configuration file. To start it automatically at boot, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsid_enable="YES" .... To start man:iscsid[8] now, run this command: [source,shell] .... # service iscsid start .... Connecting to a target can be done with or without an [.filename]#/etc/iscsi.conf# configuration file. This section demonstrates both types of connections. ==== Connecting to a Target Without a Configuration File To connect an initiator to a single target, specify the IP address of the portal and the name of the target: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 .... To verify if the connection succeeded, run `iscsictl` without any arguments. The output should look similar to this: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Connected: da0 .... In this example, the iSCSI session was successfully established, with [.filename]#/dev/da0# representing the attached LUN. If the `iqn.2012-06.com.example:target0` target exports more than one LUN, multiple device nodes will be shown in that section of the output: [source,shell] .... Connected: da0 da1 da2. .... Any errors will be reported in the output, as well as the system logs. For example, this message usually means that the man:iscsid[8] daemon is not running: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Waiting for iscsid(8) .... The following message suggests a networking problem, such as a wrong IP address or port: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.11 Connection refused .... This message means that the specified target name is wrong: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Not found .... This message means that the target requires authentication: [.programlisting] .... Target name Target portal State iqn.2012-06.com.example:target0 10.10.10.10 Authentication failed .... To specify a CHAP username and secret, use this syntax: [source,shell] .... # iscsictl -A -p 10.10.10.10 -t iqn.2012-06.com.example:target0 -u user -s secretsecret .... ==== Connecting to a Target with a Configuration File To connect using a configuration file, create [.filename]#/etc/iscsi.conf# with contents like this: [.programlisting] .... t0 { TargetAddress = 10.10.10.10 TargetName = iqn.2012-06.com.example:target0 AuthMethod = CHAP chapIName = user chapSecret = secretsecret } .... The `t0` specifies a nickname for the configuration file section. It will be used by the initiator to specify which configuration to use. The other lines specify the parameters to use during connection. The `TargetAddress` and `TargetName` are mandatory, whereas the other options are optional. In this example, the CHAP username and secret are shown. To connect to the defined target, specify the nickname: [source,shell] .... # iscsictl -An t0 .... Alternately, to connect to all targets defined in the configuration file, use: [source,shell] .... # iscsictl -Aa .... To make the initiator automatically connect to all targets in [.filename]#/etc/iscsi.conf#, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... iscsictl_enable="YES" iscsictl_flags="-Aa" .... diff --git a/documentation/content/en/books/handbook/security/_index.adoc b/documentation/content/en/books/handbook/security/_index.adoc index 252f417fc7..bfd486a4cc 100644 --- a/documentation/content/en/books/handbook/security/_index.adoc +++ b/documentation/content/en/books/handbook/security/_index.adoc @@ -1,2187 +1,2187 @@ --- title: Chapter 16. Security part: Part III. System Administration prev: books/handbook/boot next: books/handbook/jails description: Hundreds of standard practices have been authored about how to secure systems and networks, and as a user of FreeBSD, understanding how to protect against attacks and intruders is a must tags: ["security", "TCP Wrappers", "Kerberos", "OpenSSL", "OpenSSH", "ACL", "NFSv4 ACLs", "advisories", "sudo", "doas", "capsicum", "monitoring"] showBookMenu: true weight: 20 path: "/books/handbook/" --- [[security]] = Security :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 16 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/security/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[security-synopsis]] == Synopsis Hundreds of standard practices have been authored about how to secure systems and networks, and as a user of FreeBSD, understanding how to protect against attacks and intruders is a must. In this chapter, several fundamentals and techniques will be discussed. The FreeBSD system comes with multiple layers of security, and many more third party utilities may be added to enhance security. This chapter covers: * Basic FreeBSD system security concepts. * The various crypt mechanisms available in FreeBSD. * How to configure TCP Wrappers for use with man:inetd[8]. * How to set up Kerberos on FreeBSD. * How to configure and use OpenSSH on FreeBSD. * How to use OpenSSL on FreeBSD. * How to use file system ACLs. * How to use pkg to audit third party software packages installed from the Ports Collection. * How to utilize FreeBSD security advisories. * What Process Accounting is and how to enable it on FreeBSD. * How to control user resources using login classes or the resource limits database. * What is Capsicum and a basic example. Certain topics due to their complexity are found in dedicated chapters such as crossref:firewalls[firewalls,Firewalls], crossref:mac[mac,Mandatory Access Control] and articles like extref:{vpn-ipsec}[VPN over IPsec]. [[security-intro]] == 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. One of the core principles of information security is the CIA triad, which stands for the Confidentiality, Integrity, and Availability of information systems. The CIA triad is a bedrock concept of computer security as customers and users expect their data to be protected. For example, a customer expects that their credit card information is securely stored (confidentiality), that their orders are not changed behind the scenes (integrity), and that they have access to their order information at all times (availability). To provide 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. For example, a system administrator cannot simply turn on a firewall and consider the network or system secure. One must also audit accounts, check the integrity of binaries, and ensure malicious tools are not installed. To implement an effective security strategy, one must understand threats and how to defend against them. What is a threat as it pertains to computer security? Threats are not limited to remote attackers who attempt to access a system without permission from a remote location. Threats also include employees, malicious software, unauthorized network devices, natural disasters, security vulnerabilities, and even competing corporations. Systems and networks can be accessed without permission, sometimes by accident, or by remote attackers, and in some cases, via corporate espionage or former employees. As a user, it is important to prepare for and admit when a mistake has led 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. When applying security to systems, it is recommended to start by securing the basic accounts and system configuration, and then to secure the network layer so that it adheres to the system policy and the organization's security procedures. Many organizations already have a security policy that covers the configuration of technology devices. The policy should include the security configuration of workstations, desktops, mobile devices, phones, production servers, and development servers. In many cases, standard operating procedures (SOPs) already exist. When in doubt, ask the security team. [[sec-accounts]] == Securing Accounts Maintaining secure accounts in FreeBSD is crucial for data confidentiality, system integrity, and privilege separation, as it prevents unauthorized access, malware, and data breaches while ensuring compliance and protecting an organization's reputation. [[security-accounts]] === Preventing Logins In securing a system, a good starting point is an audit of accounts. Disable any accounts that do not need login access. [TIP] ==== Ensure that `root` has a strong password and that this password is not shared. ==== To deny login access to accounts, two methods exist. The first is to lock the account, this example shows how to lock the `imani` account: [source,shell] .... # pw lock imani .... The second method is to prevent login access by changing the shell to [.filename]#/usr/sbin/nologin#. The man:nologin[8] shell prevents the system from assigning a shell to the user when they attempt to login. Only the superuser can change the shell for other users: [source,shell] .... # chsh -s /usr/sbin/nologin imani .... [[security-passwords]] === Password Hashes Passwords are a necessary evil of technology. When they must be used, they should be complex and a powerful hash mechanism should be used to encrypt the version that is stored in the password database. FreeBSD supports several algorithms, including SHA256, SHA512 and Blowfish hash algorithms in its `crypt()` library, see man:crypt[3] for details. The default of SHA512 should not be changed to a less secure hashing algorithm, but can be changed to the more secure Blowfish algorithm. [NOTE] ==== Blowfish is not part of AES and is not considered compliant with any Federal Information Processing Standards (FIPS). Its use may not be permitted in some environments. ==== To determine which hash algorithm is used to encrypt a user's password, the superuser can view the hash for the user in the FreeBSD password database. Each hash starts with a symbol which indicates the type of hash mechanism used to encrypt the password. If DES is used, there is no beginning symbol. For MD5, the symbol is `$`. For SHA256 and SHA512, the symbol is `$6$`. For Blowfish, the symbol is `$2a$`. In this example, the password for `imani` is hashed using the default SHA512 algorithm as the hash starts with `$6$`. Note that the encrypted hash, not the password itself, is stored in the password database: [source,shell] .... # grep imani /etc/master.passwd .... The output should be similar to the following: [.programlisting] .... imani:$6$pzIjSvCAn.PBYQBA$PXpSeWPx3g5kscj3IMiM7tUEUSPmGexxta.8Lt9TGSi2lNQqYGKszsBPuGME0:1001:1001::0:0:imani:/usr/home/imani:/bin/sh .... The hash mechanism is set in the user's login class. The following command can be run to check which hash mechanism is currently being used: [source,shell] .... # grep user /etc/master.passwd .... The output should be similar to the following: [.programlisting] .... :passwd_format=sha512:\ .... For example, to change the algorithm to Blowfish, modify that line to look like this: [.programlisting] .... :passwd_format=blf:\ .... Then, man:cap_mkdb[1] must be executed to upgrade the login.conf database: [source,shell] .... # cap_mkdb /etc/login.conf .... Note that this change will not affect any existing password hashes. This means that all passwords should be re-hashed by asking users to run `passwd` in order to change their password. [[security-pwpolicy]] === Password Policy Enforcement Enforcing a strong password policy for local accounts is a fundamental aspect of system security. In FreeBSD, password length, password strength, and password complexity can be implemented using built-in Pluggable Authentication Modules (PAM). This section demonstrates how to configure the minimum and maximum password length and the enforcement of mixed characters using the man:pam_passwdqc[8] module. This module is enforced when a user changes their password. To configure this module, become the superuser and uncomment the line containing `pam_passwdqc.so` in [.filename]#/etc/pam.d/passwd#. Then, edit that line to match the password policy: [.programlisting] .... password requisite pam_passwdqc.so min=disabled,disabled,disabled,12,10 similar=deny retry=3 enforce=users .... The explanation of the parameters can be found in man:pam_passwdqc[8]. Once this file is saved, a user changing their password will see a message similar to the following: [source,shell] .... % passwd .... The output should be similar to the following: [.programlisting] .... Changing local password for user 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 no one else can see your terminal now, you can pick this as your password: "trait-useful&knob". Enter new password: .... If a password that does not match the policy is entered, it will be rejected with a warning and the user will have an opportunity to try again, up to the configured number of retries. If your organization's policy requires passwords to expire, FreeBSD supports the `passwordtime` in the user's login class in [.filename]#/etc/login.conf# The `default` login class contains an example: [.programlisting] .... # :passwordtime=90d:\ .... So, to set an expiry of 90 days for this login class, remove the comment symbol (#), save the edit, and execute the following command: [source,shell] .... # cap_mkdb /etc/login.conf .... To set the expiration on individual users, pass an expiration date or the number of days to expiry and a username to `pw`: [source,shell] .... # pw usermod -p 30-apr-2025 -n user .... As seen here, an expiration date is set in the form of day, month, and year. For more information, see man:pw[8]. [[security-sudo]] === Shared Administration with sudo System administrators often need the ability to grant enhanced permissions to users so they may perform privileged tasks. The idea that team members are provided access to a FreeBSD system to perform their specific tasks opens up unique challenges to every administrator. These team members only need a subset of access beyond normal end user levels; however, they almost always tell management they are unable to perform their tasks without superuser access. Thankfully, there is no reason to provide such access to end users because tools exist to manage this exact requirement. [TIP] ==== Even administrators should limit their privileges when not needed. ==== Up to this point, the security chapter has covered permitting access to authorized users and attempting to prevent unauthorized access. Another problem arises once authorized users have access to the system resources. In many cases, some users may need access to application startup scripts, or a team of administrators need to maintain the system. Traditionally, the standard users and groups, file permissions, and even the man:su[1] command would manage this access. And as applications required more access, as more users needed to use system resources, a better solution was required. The most used application is currently Sudo. Sudo allows administrators to configure more rigid access to system commands and provide for some advanced logging features. As a tool, it is available from the Ports Collection as package:security/sudo[] or by use of the man:pkg[8] utility. Execute the following command to install it: [source,shell] .... # pkg install sudo .... After the installation is complete, the installed `visudo` will open the configuration file with a text editor. Using `visudo` is highly recommended as it comes with a built in syntax checker to verify there are no errors before the file is saved. The configuration file is made up of several small sections which allow for extensive configuration. In the following example, web application maintainer, user1, needs to start, stop, and restart the web application known as _webservice_. To grant this user permission to perform these tasks, add this line to the end of [.filename]#/usr/local/etc/sudoers#: [.programlisting] .... user1 ALL=(ALL) /usr/sbin/service webservice * .... The user may now start _webservice_ using this command: [source,shell] .... % sudo /usr/sbin/service webservice start .... While this configuration allows a single user access to the webservice service; however, in most organizations, there is an entire web team in charge of managing the service. A single line can also give access to an entire group. These steps will create a web group, add a user to this group, and allow all members of the group to manage the service: [source,shell] .... # pw groupadd -g 6001 -n webteam .... Using the same man:pw[8] command, the user is added to the webteam group: [source,shell] .... # pw groupmod -m user1 -n webteam .... Finally, this line in [.filename]#/usr/local/etc/sudoers# allows any member of the webteam group to manage _webservice_: [.programlisting] .... %webteam ALL=(ALL) /usr/sbin/service webservice * .... Unlike man:su[1], man:sudo[8] only requires the end user password. This avoids sharing passwords, which is a poor practice. Users permitted to run applications with man:sudo[8] only enter their own passwords. This is more secure and gives better control than man:su[1], where the `root` password is entered and the user acquires all `root` permissions. [TIP] ==== Most organizations are moving or have moved toward a two factor authentication model. In these cases, the user may not have a password to enter. man:sudo[8] can be configured to permit two factor authentication model by using the `NOPASSWD` variable. Adding it to the configuration above will allow all members of the _webteam_ group to manage the service without the password requirement: [.programlisting] .... %webteam ALL=(ALL) NOPASSWD: /usr/sbin/service webservice * .... ==== [[security-doas]] === Shared Administration with Doas man:doas[1] is a command-line utility ported from OpenBSD. It serves as an alternative to the widely used man:sudo[8] command in Unix-like systems. With doas, users can execute commands with elevated privileges, typically as the root user, while maintaining a simplified and security-conscious approach. Unlike man:sudo[8], doas emphasizes simplicity and minimalism, focusing on streamlined privilege delegation without an overwhelming array of configuration options. Execute the following command to install it: [source,shell] .... # pkg install doas .... After the installation [.filename]#/usr/local/etc/doas.conf# must be configured to grant access for users for specific commands, or roles. The simpliest entry could be the following, which grants the user `local_user` with `root` permissions without asking for its password when executing the doas command. [.programlisting] .... permit nopass local_user as root .... After the installation and configuration of the `doas` utility, a command can now be executed with enhanced privileges, for example: [source,shell] .... $ doas vi /etc/rc.conf .... For more configuration examples, please read man:doas.conf[5]. [[security-ids]] == Intrusion Detection System (IDS) Verification of system files and binaries is important because it provides the system administration and security teams information about system changes. A software application that monitors the system for changes is called an Intrusion Detection System (IDS). FreeBSD provides native support for a basic IDS system called man:mtree[8]. While the nightly security emails will notify an administrator of changes, the information is stored locally and there is a chance that a malicious user could modify this information in order to hide their changes to the system. 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, on a removable USB disk or remote server. It is also recommended to run `freebsd-update IDS` after each update. [[security-ids-generate-spec-file]] === Generating the Specification File The built-in man:mtree[8] utility can be used to generate a specification of the contents of a directory. A seed, or a numeric constant, is used to generate the specification and is required to check that the specification has not changed. This makes it possible to determine if a file or binary has been modified. Since the seed value is unknown by an attacker, faking or checking the checksum values of files will be difficult to impossible. [TIP] ==== It is recommended to create specifications for the directories which contain binaries and configuration files, as well as any directories containing sensitive data. Typically, specifications are created for [.filename]#/bin#, [.filename]#/sbin#, [.filename]#/usr/bin#, [.filename]#/usr/sbin#, [.filename]#/usr/local/bin#, [.filename]#/etc#, and [.filename]#/usr/local/etc#. ==== The following example generates a set of `sha512` hashes, one for each system binary in [.filename]#/bin#, and saves those values to a hidden file in user's home directory, [.filename]#/home/user/.bin_chksum_mtree#: [source,shell] .... # mtree -s 123456789 -c -K cksum,sha512 -p /bin > /home/user/.bin_chksum_mtree .... The output should be similar to the following: [.programlisting] .... mtree: /bin checksum: 3427012225 .... [WARNING] ==== The `123456789` value represents the seed, and should be chosen randomly. This value should be remembered, *but not shared*. It is important to keep the seed value and the checksum output hidden from malicious users. ==== [[security-ids-spec-file-structure]] === The Specification File Structure The mtree format is a textual format that describes a collection of filesystem objects. Such files are typically used to create or verify directory hierarchies. An mtree file consists of a series of lines, each providing information about a single filesystem object. Leading whitespace is always ignored. The specification file created above will be used to explain the format and content: [.programlisting] .... # user: root <.> # machine: machinename <.> # tree: /bin <.> # date: Thu Aug 24 21:58:37 2023 <.> # . /set type=file uid=0 gid=0 mode=0555 nlink=1 flags=uarch <.> . type=dir mode=0755 nlink=2 time=1681388848.239523000 <.> \133 nlink=2 size=12520 time=1685991378.688509000 \ cksum=520880818 \ sha512=5c1374ce0e2ba1b3bc5a41b23f4bbdc1ec89ae82fa01237f376a5eeef41822e68f1d8f75ec46b7bceb65396c122a9d837d692740fdebdcc376a05275adbd3471 cat size=14600 time=1685991378.694601000 cksum=3672531848 \ <.> sha512=b30b96d155fdc4795432b523989a6581d71cdf69ba5f0ccb45d9b9e354b55a665899b16aee21982fffe20c4680d11da4e3ed9611232a775c69f926e5385d53a2 chflags size=8920 time=1685991378.700385000 cksum=1629328991 \ sha512=289a088cbbcbeb436dd9c1f74521a89b66643976abda696b99b9cc1fbfe8b76107c5b54d4a6a9b65332386ada73fc1bbb10e43c4e3065fa2161e7be269eaf86a chio size=20720 time=1685991378.706095000 cksum=1948751604 \ sha512=46f58277ff16c3495ea51e74129c73617f31351e250315c2b878a88708c2b8a7bb060e2dc8ff92f606450dbc7dd2816da4853e465ec61ee411723e8bf52709ee chmod size=9616 time=1685991378.712546000 cksum=4244658911 \ sha512=1769313ce08cba84ecdc2b9c07ef86d2b70a4206420dd71343867be7ab59659956f6f5a458c64e2531a1c736277a8e419c633a31a8d3c7ccc43e99dd4d71d630 .... <.> User who created the specification. <.> Machine's hostname. <.> Directory path. <.> The Date and time when the specification was created. <.> `/set` special commands, defines some settings obtained from the files analyzed. <.> Refers to the parsed directory and indicates things like what type it is, its mode, the number of hard links, and the time in UNIX format since it was modified. <.> Refers to the file and shows the size, time and a list of hashes to verify the integrity. [[security-ids-verify-specification-file]] === Verify the Specification file To verify that the binary signatures have not changed, compare the current contents of the directory to the previously generated specification, and save the results to a file. This command requires the seed that was used to generate the original specification: [source,shell] .... # mtree -s 123456789 -p /bin < /home/user/.bin_chksum_mtree >> /home/user/.bin_chksum_output .... This should produce the same checksum for [.filename]#/bin# that was produced when the specification was created. If no changes have occurred to the binaries in this directory, the [.filename]#/home/user/.bin_chksum_output# output file will be empty. To simulate a change, change the date on [.filename]#/bin/cat# using man:touch[1] and run the verification command again: [source,shell] .... # touch /bin/cat .... Run the verification command again: [source,shell] .... # mtree -s 123456789 -p /bin < /home/user/.bin_chksum_mtree >> /home/user/.bin_chksum_output .... And then check the content of the output file: [source,shell] .... # cat /root/.bin_chksum_output .... The output should be similar to the following: [.programlisting] .... cat: modification time (Fri Aug 25 13:30:17 2023, Fri Aug 25 13:34:20 2023) .... [WARNING] ==== This is just an example of what would be displayed when executing the command, to show the changes that would occur in the metadata. ==== [[security-secure-levels]] == Secure levels securelevel is a security mechanism implemented in the kernel. When the securelevel is positive, the kernel restricts certain tasks; not even the superuser (root) is allowed to do them. The securelevel mechanism limits the ability to: * Unset certain file flags, such as `schg` (the system immutable flag). * Write to kernel memory via [.filename]#/dev/mem# and [.filename]#/dev/kmem#. * Load kernel modules. * Alter firewall rules. [[security-secure-levels-definitions]] === Secure Levels Definitions The kernel runs with five different security levels. Any super-user process can raise the level, but no process can lower it. The security definitions are: -1:: *Permanently insecure mode* - always run the system in insecure mode. This is the default initial value. 0:: *Insecure mode* - immutable and append-only flags may be turned off. All devices may be read or written subject to their permissions. 1:: *Secure mode* - the system immutable and system append-only flags may not be turned off; disks for mounted file systems, [.filename]#/dev/mem# and [.filename]#/dev/kmem# may not be opened for writing; [.filename]#/dev/io# (if your platform has it) may not be opened at all; kernel modules (see man:kld[4]) may not be loaded or unloaded. The kernel debugger may not be entered using the debug.kdb.enter sysctl. A panic or trap cannot be forced using the debug.kdb.panic, debug.kdb.panic_str and other sysctl's. 2:: *Highly secure mode* - same as secure mode, plus disks may not be opened for writing (except by man:mount[2]) whether mounted or not. This level precludes tampering with file systems by unmounting them, but also inhibits running man:newfs[8] while the system is multiuser. 3:: *Network secure mode* - same as highly secure mode, plus IP packet filter rules (see man:ipfw[8], man:ipfirewall[4] and man:pfctl[8]) cannot be changed and man:dummynet[4] or man:pf[4] configuration cannot be adjusted. [TIP] ==== In summary, the key difference between `Permanently Insecure Mode` and `Insecure Mode` in FreeBSD secure levels is the degree of security they provide. `Permanently Insecure Mode` completely lifts all security restrictions, while `Insecure Mode` relaxes some restrictions but still maintains a level of control and security. ==== [[security-modify-secure-levels]] === Modify Secure Levels In order to change the securelevel of the system it is necessary to activate `kern_securelevel_enable` by executing the following command: [source,shell] .... # sysrc kern_securelevel_enable="YES" .... And set the value of `kern_securelevel` to the desired security level: [source,shell] .... # sysrc kern_securelevel=2 .... To check the status of the securelevel on a running system execute the following command: [source,shell] .... # sysctl -n kern.securelevel .... The output contains the current value of the securelevel. If it is greater than 0, at least some of the securelevel's protections are enabled. [.programlisting] .... -1 .... [[security-file-flags]] == File flags File flags allow users to attach additional metadata or attributes to files and directories beyond basic permissions and ownership. These flags provide a way to control various behaviors and properties of files without needing to resort to creating special directories or using extended attributes. File flags can be used to achieve different goals, such as preventing file deletion, making files append-only, synchronizing file updates, and more. Some commonly used file flags in FreeBSD include the "immutable" flag, which prevents modification or deletion of a file, and the "append-only" flag, which allows only data to be added to the end of a file but not modified or removed. These flags can be managed using the man:chflags[1] command in FreeBSD, providing administrators and users with greater control over the behavior and characteristics of their files and directories. It is important to note that file flags are typically managed by root or users with appropriate privileges, as they can influence how files are accessed and manipulated. Some flags are available for the use of the file's owner, as described in man:chflags[1]. [[security-work-file-flag]] === Work with File Flags In this example, a file named [.filename]#~/important.txt# in user's home directory want to be protected against deletions. Execute the following command to set the `schg` file flag: [source,shell] .... # chflags schg ~/important.txt .... When any user, including the `root` user, tries to delete the file, the system will display the message: [.programlisting] .... rm: important.txt: Operation not permitted .... To delete the file, it will be necessary to delete the file flags of that file by executing the following command: [source,shell] .... # chflags noschg ~/important.txt .... A list of supported file flags and their functionality can be found in man:chflags[1]. [[openssh]] == 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 eliminate eavesdropping, connection hijacking, and other network-level attacks. OpenSSH is maintained by the OpenBSD project and is installed by default in FreeBSD. 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 in the link:https://www.openssh.com/[web page]. This section provides an overview of the built-in client utilities to securely access other systems and securely transfer files from a FreeBSD system. It then describes how to configure a SSH server on a FreeBSD system. [TIP] ==== As stated, this chapter will cover the base system version of OpenSSH. A version of OpenSSH is also available in the package:security/openssh-portable[], which provides additional configuration options and is updated more regularly. ==== === Using the SSH Client Utilities To log into a SSH server, use man:ssh[1] 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: [source,shell] .... # ssh user@example.com .... The output should be similar to the following: [.programlisting] .... 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 [.filename]#~/.ssh/known_hosts# in the user's home directory. Future attempts to login are verified against the saved key and man:ssh[1] 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. [NOTE] ==== How to perform this check is outside the scope of this chapter. ==== 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: [source,shell] .... # scp user@example.com:/COPYRIGHT COPYRIGHT .... The output should be similar to the following: [.programlisting] .... Password for user@example.com: ******* COPYRIGHT 100% |*****************************| 4735 .... 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 man:scp[1] are similar to man:cp[1]. 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 `user@host:`. Be aware when copying directories recursively that man:scp[1] uses `-r`, whereas man:cp[1] uses `-R`. To open an interactive session for copying files, use man:sftp[1]. Refer to man:sftp[1] for a list of available commands while in an man:sftp[1] session. [[security-ssh-keygen]] === Key-based Authentication Instead of using passwords, a client can be configured to connect to the remote machine using keys. For security reasons, this is the preferred method. man:ssh-keygen[1] can be used to generate the authentication keys. 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. [source,shell] .... % ssh-keygen -t rsa -b 4096 .... The output should be similar to the following: [.programlisting] .... Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): Created directory '/home/user/.ssh/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_rsa. Your public key has been saved in /home/user/.ssh/id_rsa.pub. The key fingerprint is: SHA256:54Xm9Uvtv6H4NOo6yjP/YCfODryvUU7yWHzMqeXwhq8 user@host.example.com The key's randomart image is: +---[RSA 2048]----+ | | | | | | | . o.. | | .S*+*o | | . O=Oo . . | | = Oo= oo..| | .oB.* +.oo.| | =OE**.o..=| +----[SHA256]-----+ .... The private key is stored in [.filename]#~/.ssh/id_rsa# and the public key is stored in [.filename]#~/.ssh/id_rsa.pub#. The _public_ key must be copied to [.filename]#~/.ssh/authorized_keys# on the remote machine for key-based authentication to work. [WARNING] ==== Utilizing a passphrase for OpenSSH keys is a key security practice, providing an extra layer of protection against unauthorized access and enhancing overall cybersecurity. In case of loss or theft, this adds another layer of security. ==== [[security-ssh-tunneling]] === SSH Tunneling OpenSSH has the ability to create a tunnel to encapsulate another protocol in an encrypted session. The following command tells man:ssh[1] to create a tunnel: [source,shell] .... % ssh -D 8080 user@example.com .... This example uses the following options: -D:: Specifies a local "dynamic" application-level port forwarding. user@foo.example.com:: 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`. This method can be used to wrap any number of insecure TCP protocols such as SMTP, POP3, and FTP. === Enabling the SSH Server In addition to providing built-in SSH client utilities, a FreeBSD system can be configured as an SSH server, accepting connections from other SSH clients. [TIP] ==== As stated, this chapter will cover the base system version of OpenSSH. Please *not* confuse with package:security/openssh-portable[], the version of OpenSSH that ships with the FreeBSD ports. ==== In order to have the SSH Server enabled across reboots execute the following command: [source,shell] .... # sysrc sshd_enable="YES" .... Then execute the following command to enable the service: [source,shell] .... # service sshd start .... The first time sshd starts on a FreeBSD 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. +Refer to man:sshd[8] for the list of available options when starting sshd and a complete discussion about authentication, the login process, and the various configuration files. At this point, the sshd should be available to all users with a username and password on the system. [[config-publickey-auth]] === Configuring publickey auth method Configuring OpenSSH to use public key authentication enhances security by leveraging asymmetric cryptography for authentication. This method eliminates password-related risks, such as weak passwords or interception during transmission, while thwarting various password-based attacks. However, it's vital to ensure the private keys are well-protected to prevent unauthorized access. The first step will be to configure man:sshd[8] to use the required authentication method. Edit [.filename]#/etc/ssh/sshd_config# and uncomment the following configuration: [.programlisting] .... PubkeyAuthentication yes .... Once the configuration is done, the users will have to send the system administrator their *public key* and these keys will be added in [.filename]#.ssh/authorized_keys#. The process for generating the keys is described in <>. Then restart the server executing the following command: [source,shell] .... # service sshd reload .... It is strongly recommended to follow the security improvements indicated in <>. [[security-sshd-security-options]] === SSH Server Security Options While sshd is the most widely used remote administration facility for FreeBSD, brute force and drive by attacks are common to any system exposed to public networks. Several additional parameters are available to prevent the success of these attacks and will be described in this section. All configurations will be done in [.filename]#/etc/ssh/sshd_config# [TIP] ==== Do not confuse [.filename]#/etc/ssh/sshd_config# with [.filename]#/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. ==== By default, authentication can be done with both pubkey and password. To allow *only* pubkey authentication, *which is strongly recommended*, change the variable: [.programlisting] .... PasswordAuthentication no .... 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 `user` to log in from `192.168.1.32`, add this line to [.filename]#/etc/ssh/sshd_config#: [.programlisting] .... AllowUsers user@192.168.1.32 .... To allow `user` to log in from anywhere, list that user without specifying an IP address: [.programlisting] .... AllowUsers user .... Multiple users should be listed on the same line, like so: [.programlisting] .... AllowUsers root@192.168.1.32 user .... After making all the changes, and before restarting the service, it is recommended to verify that the configuration made is correct by executing the following command: [source,shell] .... # sshd -t .... If the configuration file is correct, no output will be shown. In case the configuration file is incorrect, it will show something like this: [.programlisting] .... /etc/ssh/sshd_config: line 3: Bad configuration option: sdadasdasdasads /etc/ssh/sshd_config: terminating, 1 bad configuration options .... After making the changes and checking that the configuration file is correct, tell sshd to reload its configuration file by running: [source,shell] .... # service sshd reload .... [[openssl]] == OpenSSL OpenSSL is a cryptography toolkit implementing the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) network protocols and many cryptography routines. The openssl program is a command line tool for using the various cryptography functions of OpenSSL's crypto library from the shell. It can be used for * Creation and management of private keys, public keys and parameters * Public key cryptographic operations * Creation of X.509 certificates, CSRs and CRLs * Calculation of Message Digests * Encryption and Decryption with Ciphers * SSL/TLS Client and Server Tests * Handling of S/MIME signed or encrypted mail * Time Stamp requests, generation and verification * Benchmarking the crypto routines For more information about OpenSSL, read the free https://www.feistyduck.com/books/openssl-cookbook/[OpenSSL Cookbook]. [[generating-certificates]] === Generating Certificates OpenSSL supports the generation of certificates both to be validated by a link:https://en.wikipedia.org/wiki/Certificate_authority[CA] and for own use. Run the command man:openssl[1] to generate a valid certificate for a link:https://en.wikipedia.org/wiki/Certificate_authority[CA] with the following arguments. This command will create two files in the current directory. The certificate request, [.filename]#req.pem#, can be sent to a link:https://en.wikipedia.org/wiki/Certificate_authority[CA] which, will validate the entered credentials, sign the request, and return the signed certificate. The second file, [.filename]#cert.key#, 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. Execute the following command to generate the certificate: [source,shell] .... # openssl req -new -nodes -out req.pem -keyout cert.key -sha3-512 -newkey rsa:4096 .... The output should be similar to the following: [.programlisting] .... Generating a RSA private key ..................................................................................................................................+++++ ......................................+++++ writing new private key to 'cert.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]:ES State or Province Name (full name) [Some-State]:Valencian Community Locality Name (eg, city) []:Valencia 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 []:user@FreeBSD.org Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []:123456789 An optional company name []:Another name .... Alternately, if a signature from a link:https://en.wikipedia.org/wiki/Certificate_authority[CA] is not required, a self-signed certificate can be created. This will create two new files in the current directory: a private key file [.filename]#cert.key#, and the certificate itself, [.filename]#cert.crt#. These should be placed in a directory, preferably under [.filename]#/etc/ssl/#, which is readable only by `root`. Permissions of `0700` are appropriate for these files and can be set using `chmod`. Execute the following command to generate the certificate: [source,shell] .... # openssl req -new -x509 -days 365 -sha3-512 -keyout /etc/ssl/private/cert.key -out /etc/ssl/certs/cert.crt .... The output should be similar to the following: [.programlisting] .... Generating a RSA private key ........................................+++++ ...........+++++ writing new private key to '/etc/ssl/private/cert.key' Enter PEM pass phrase: Verifying - Enter PEM pass phrase: ----- 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]:ES State or Province Name (full name) [Some-State]:Valencian Community Locality Name (eg, city) []:Valencia 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 []:user@FreeBSD.org .... [[fips-provider]] === Configuring the FIPS Provider With the import of OpenSSL 3 into the base system (on FreeBSD 14 and later), its new concept of provider modules was introduced in the system. Besides the default provider module built-in to the library, the _legacy_ module implements the now optional deprecated cryptography algorithms, while the _fips_ module restricts the OpenSSL implementation to the cryptography algorithms present in the link:https://en.wikipedia.org/wiki/Federal_Information_Processing_Standards[FIPS] set of standards. This part of OpenSSL receives link:https://www.openssl.org/docs/fips.html[particular care], including a link:https://www.openssl.org/news/fips-cve.html[list of relevant security issues], and is subject to the link:https://github.com/openssl/openssl/blob/master/README-FIPS.md[FIPS 140 validation process] on a regular basis. The link:https://www.openssl.org/source/[list of FIPS validated versions] is also available. This allows users to ensure FIPS compliance in their use of OpenSSL. Importantly, the man:fips_module[7] is protected by an additional security measure, preventing its use without passing an integrity check. This check can be setup by the local system administrator, allowing every user of OpenSSL 3 to load this module. When not configured correctly, the FIPS module is expected to fail as follows: [source,shell] .... # echo test | openssl aes-128-cbc -a -provider fips -pbkdf2 .... The ouput should be similar to the following: [.programlisting] .... aes-128-cbc: unable to load provider fips Hint: use -provider-path option or OPENSSL_MODULES environment variable. 00206124D94D0000:error:1C8000D5:Provider routines:SELF_TEST_post:missing config data:crypto/openssl/providers/fips/self_test.c:275: 00206124D94D0000:error:1C8000E0:Provider routines:ossl_set_error_state:fips module entering error state:crypto/openssl/providers/fips/self_test.c:373: 00206124D94D0000:error:1C8000D8:Provider routines:OSSL_provider_init_int:self test post failure:crypto/openssl/providers/fips/fipsprov.c:707: 00206124D94D0000:error:078C0105:common libcrypto routines:provider_init:init fail:crypto/openssl/crypto/provider_core.c:932:name=fips .... The check can be configured through the creation of a file in [.filename]#/etc/ssl/fipsmodule.cnf#, which will then be referenced in OpenSSL's main configuration file [.filename]#/etc/ssl/openssl.cnf#. OpenSSL provides the man:openssl-fipsinstall[1] utility to help with this process, which can be used as follows: [source,shell] .... # openssl fipsinstall -module /usr/lib/ossl-modules/fips.so -out /etc/ssl/fipsmodule.cnf .... The ouput should be similar to the following: [.programlisting] .... INSTALL PASSED .... The [.filename]#/etc/ssl/openssl.cnf# should then be modified, in order to: * Include the [.filename]#/etc/ssl/fipsmodule.cnf# file generated above, * Expose the FIPS module for possible use, * And explicitly activate the default module. [.programlisting] .... [...] # For FIPS # Optionally include a file that is generated by the OpenSSL fipsinstall # application. This file contains configuration data required by the OpenSSL # fips provider. It contains a named section e.g. [fips_sect] which is # referenced from the [provider_sect] below. # Refer to the OpenSSL security policy for more information. .include /etc/ssl/fipsmodule.cnf [...] # List of providers to load [provider_sect] default = default_sect # The fips section name should match the section name inside the # included fipsmodule.cnf. fips = fips_sect # If no providers are activated explicitly, the default one is activated implicitly. # See man 7 OSSL_PROVIDER-default for more details. # # If you add a section explicitly activating any other provider(s), you most # probably need to explicitly activate the default provider, otherwise it # becomes unavailable in openssl. As a consequence applications depending on # OpenSSL may not work correctly which could lead to significant system # problems including inability to remotely access the system. [default_sect] activate = 1 .... With this done, it should be possible to confirm that the FIPS module is effectively available and working: [source,shell] .... # echo test | openssl aes-128-cbc -a -provider fips -pbkdf2 .... The ouput should be similar to the following: [.programlisting] .... enter AES-128-CBC encryption password: Verifying - enter AES-128-CBC encryption password: U2FsdGVkX18idooW6e3LqWeeiKP76kufcOUClh57j8U= .... This procedure has to be repeated every time the FIPS module is modified, e.g., after performing system updates, or after applying security fixes affecting OpenSSL in the base system. [[kerberos5]] == Kerberos Kerberos is a network authentication protocol which was originally created by the Massachusetts Institute of Technology (MIT) as a way to securely provide authentication across a potentially hostile network. The Kerberos protocol uses strong cryptography so that both a client and server can prove their identity without sending any unencrypted secrets over the 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 and servers 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 4120. 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 subject to US export regulations. In FreeBSD, MITKerberos is available as the package:security/krb5[] package or port. The Heimdal Kerberos implementation was explicitly developed outside of the US to avoid export regulations. The Heimdal Kerberos distribution is included in the base FreeBSD installation, and another distribution with more configurable options is available as package:security/heimdal[] in the Ports Collection. In Kerberos users and services are identified as "principals" which are contained within an administrative grouping, called a "realm". A typical user principal would be of the form `_user_@_REALM_` (realms are traditionally uppercase). This section provides a guide on how to set up Kerberos using the Heimdal distribution included in FreeBSD. 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`. [NOTE] ==== 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 KDC The Key Distribution Center (KDC) is the centralized authentication service that Kerberos provides, the "trusted third party" of the system. It is the computer that issues Kerberos tickets, which are used for clients to authenticate to servers. As the KDC is considered trusted by all other computers in the Kerberos realm, it has heightened security concerns. Direct access to the KDC should be limited. While running a KDC requires few computing resources, a dedicated machine acting only as a KDC is recommended for security reasons. To begin, install the package:security/heimdal[] package as follows: [source,shell] .... # pkg install heimdal .... Next, update [.filename]#/etc/rc.conf# using `sysrc` as follows: [source,shell] .... # sysrc kdc_enable=yes # sysrc kadmind_enable=yes .... Next, edit [.filename]#/etc/krb5.conf# as follows: [.programlisting] .... [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`. The hostname of the KDC must be resolvable in the DNS. Kerberos can also use the DNS to locate KDCs, instead of a `[realms]` section in [.filename]#/etc/krb5.conf#. For large organizations that have their own DNS servers, the above example could be trimmed to: [.programlisting] .... [libdefaults] default_realm = EXAMPLE.ORG [domain_realm] .example.org = EXAMPLE.ORG .... With the following lines being included in the `example.org` zone file: [.programlisting] .... _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 .... [NOTE] ==== In order for clients to be able to find the Kerberos services, they _must_ have either a fully configured [.filename]#/etc/krb5.conf# or a minimally configured [.filename]#/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 [.filename]#/var/heimdal/m-key#; it would be reasonable to use a 45-character random password for this purpose. To create the master key, run `kstash` and enter a password: [source,shell] .... # kstash .... The output should be similar to the following: [.programlisting] .... Master key: xxxxxxxxxxxxxxxxxxxxxxx Verifying password - Master key: xxxxxxxxxxxxxxxxxxxxxxx .... Once the master key has been created, the database should be initialized. The Kerberos administrative tool man:kadmin[8] can be used on the KDC in a mode that operates directly on the database, without using the man:kadmind[8] network service, as `kadmin -l`. This resolves 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: [source,shell] .... # 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. [source,shell] .... kadmin> add tillman .... The output should be similar to the following: [.programlisting] .... Max ticket life [unlimited]: Max renewable life [unlimited]: Principal expiration time [never]: Password expiration time [never]: Attributes []: Password: xxxxxxxx Verifying password - Password: xxxxxxxx .... Next, start the KDC services by running: [source,shell] .... # service kdc start # 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 a ticket for the principal that was just created: [source,shell] .... % kinit tillman .... The output should be similar to the following: [.programlisting] .... tillman@EXAMPLE.ORG's Password: .... Confirm that a ticket was successfully obtained using `klist`: [source,shell] .... % klist .... The output should be similar to the following: [.programlisting] .... Credentials cache: FILE:/tmp/krb5cc_1001 Principal: tillman@EXAMPLE.ORG Issued Expires Principal Aug 27 15:37:58 2013 Aug 28 01:37:58 2013 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG .... The temporary ticket can be destroyed when the test is finished: [source,shell] .... % kdestroy .... === Configuring a Server to Use Kerberos The first step in configuring a server to use Kerberos authentication is to ensure that it has the correct configuration in [.filename]#/etc/krb5.conf#. The version from the KDC can be used as-is, or it can be regenerated on the new system. Next, create [.filename]#/etc/krb5.keytab# on the server. This is the main part of "Kerberizing" a service - it corresponds to generating a secret shared between the service and the KDC. The secret is a cryptographic key, stored in a "keytab". The keytab 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 [.filename]#keytab# is generated on an administrator's trusted machine using `kadmin`, then securely transferred to the server, e.g., with man:scp[1]; it can also be created directly on the server if that is consistent with the desired security policy. It is very important that the keytab is transmitted to the server in a secure fashion: if the key is known by some other party, that party can impersonate any user to the server! Using `kadmin` on the server directly is convenient, because the entry for the host principal in the KDC database is also created using `kadmin`. Of course, `kadmin` is a kerberized service; a Kerberos ticket is needed to authenticate to the network service, but to ensure that the user running `kadmin` is actually present (and their session has not been hijacked), `kadmin` will prompt for the password to get a fresh ticket. The principal authenticating to the kadmin service must be permitted to use the `kadmin` interface, as specified in [.filename]#/var/heimdal/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 could securely connect to the KDC via the local console or man:ssh[1], and perform administration locally using `kadmin -l`. After installing [.filename]#/etc/krb5.conf#, use `add --random-key` in `kadmin`. This adds the server's host principal to the database, but does not extract a copy of the host principal key to a keytab. To generate the keytab, use `ext` to extract the server's host principal key to its own keytab: [source,shell] .... # kadmin .... The output should be similar to the following: [.programlisting] .... kadmin> add --random-key host/myserver.example.org Max ticket life [unlimited]: Max renewable life [unlimited]: Principal expiration time [never]: Password expiration time [never]: Attributes []: kadmin> ext_keytab host/myserver.example.org kadmin> exit .... Note that `ext_keytab` stores the extracted key in [.filename]#/etc/krb5.keytab# by default. This is good when being run on the server being kerberized, but the `--keytab _path/to/file_` argument should be used when the keytab is being extracted elsewhere: [source,shell] .... # kadmin .... The output should be similar to the following: [.programlisting] .... kadmin> ext_keytab --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 inserting unneeded keys into the system's keytab. At this point, the server can read encrypted messages from the KDC using its shared key, stored in [.filename]#krb5.keytab#. It is now ready for the Kerberos-using services to be enabled. One of the most common such services is man:sshd[8], which supports Kerberos via the GSS-API. In [.filename]#/etc/ssh/sshd_config#, add the line: [.programlisting] .... GSSAPIAuthentication yes .... After making this change, man:sshd[8] must be restarted for the new configuration to take effect: `service sshd restart`. === Configuring a Client to Use Kerberos As it was for the server, the client requires configuration in [.filename]#/etc/krb5.conf#. Copy the file in place (securely) or re-enter it as needed. Test the client by using `kinit`, `klist`, and `kdestroy` from the client to obtain, show, and then delete a ticket for an existing 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. In the case of kerberized man:ssh[1], GSS-API is disabled by default, so test using `ssh -o GSSAPIAuthentication=yes _hostname_`. When testing a Kerberized application, try using a packet sniffer such as `tcpdump` to confirm that no sensitive information is sent in the clear. Various Kerberos client applications are available. With the advent of a bridge so that applications using SASL for authentication can use GSS-API mechanisms as well, large classes of client applications can use Kerberos for authentication, from Jabber clients to IMAP clients. 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 [.filename]#.k5login# and [.filename]#.k5users# files, placed in a user's home directory, can be used to solve this problem. For example, if the following [.filename]#.k5login# is placed in the home directory of `webdevelopers`, both principals listed will have access to that account without requiring a shared password: [.programlisting] .... tillman@example.org jdoe@example.org .... Refer to man:ksu[1] for more information about [.filename]#.k5users#. === MIT 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/[http://web.mit.edu/Kerberos/www/] is recommended. Be careful of path issues: the MIT port installs into [.filename]#/usr/local/# by default, and the FreeBSD system applications run instead of the MIT versions if `PATH` lists the system directories first. When using MIT Kerberos as a KDC on FreeBSD, execute the following commands to add the required configurations to [.filename]#/etc/rc.conf#: [source,shell] .... # sysrc kdc_program="/usr/local/sbin/kdc" # sysrc kadmind_program="/usr/local/sbin/kadmind" # sysrc kdc_flags="" # sysrc kdc_enable="YES" # sysrc kadmind_enable="YES" .... === Kerberos Tips, Tricks, and Troubleshooting When configuring and troubleshooting Kerberos, keep the following points in mind: * When using either Heimdal or MITKerberos from ports, ensure that the `PATH` lists the port's 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. crossref:network-servers[network-ntp,“Clock Synchronization with NTP”] 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 `HTTP/` principal used for Apache's package:www/mod_auth_kerb[]. * All hosts in the realm must be both forward and reverse resolvable in DNS or, at a minimum, exist in [.filename]#/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 MITKerberos, to allow a principal to have a ticket life longer than the default lifetime of 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. * 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 [.filename]#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 [.filename]#krb5.dict# is one string per line. Creating a symbolic link to [.filename]#/usr/share/dict/words# might be useful. === Mitigating Kerberos Limitations 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. 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 trojaned `kinit` could record all user names and passwords. File system integrity checking tools like package:security/tripwire[] can alleviate this. === Resources and Further Information * http://www.faqs.org/faqs/Kerberos-faq/general/preamble.html[The Kerberos FAQ] * http://web.mit.edu/Kerberos/www/dialogue.html[Designing an Authentication System: a Dialog in Four Scenes] * https://www.ietf.org/rfc/rfc4120.txt[RFC 4120, The Kerberos Network Authentication Service (V5)] * http://web.mit.edu/Kerberos/www/[MIT Kerberos home page] * https://github.com/heimdal/heimdal/wiki[Heimdal Kerberos project wiki page] [[tcpwrappers]] == TCP Wrappers TCP Wrappers is a host-based network access control system. By intercepting incoming network requests before they reach the actual network service, TCP Wrappers assess whether the source IP address is permitted or denied access based on predefined rules in configuration files. However, while TCP Wrappers provide basic access control, they should not be considered a substitute for more robust security measures. For comprehensive protection, it's recommended to use advanced technologies like firewalls, along with proper user authentication practices and intrusion detection systems. [[tcpwrappers-initial-configuration]] === Initial Configuration TCP Wrappers are enabled by default in man:inetd[8]. So the first step will be to enable man:inetd[8] executing the following commands: [source,shell] .... # sysrc inetd_enable="YES" # service inetd start .... Then, properly configure [.filename]#/etc/hosts.allow#. [WARNING] ==== Unlike other implementations of TCP Wrappers, the use of [.filename]#hosts.deny# is deprecated in FreeBSD. All configuration options should be placed in [.filename]#/etc/hosts.allow#. ==== In the simplest configuration, daemon connection policies are set to either permit or block, depending on the options in [.filename]#/etc/hosts.allow#. The default configuration in FreeBSD 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 Wrappers 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 package:mail/qpopper[] daemon, the following lines should be appended to [.filename]#/etc/hosts.allow#: [.programlisting] .... # This line is required for POP3 connections: qpopper : ALL : allow .... Whenever this file is edited, restart inetd: [source,shell] .... # service inetd restart .... [[tcpwrappers-advanced-config]] === Advanced Configuration TCP Wrappers 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. To learn more about wildcards and their associated functionality, refer to man:hosts_access[5]. [[fs-acl]] == Access Control Lists Access Control Lists (ACLs) extend traditional UNIX(R) file permissions by allowing fine-grained access control for users and groups on a per-file or per-directory basis. Each ACL entry defines a user or group and the associated permissions, such as read, write, and execute. FreeBSD provides commands like man:getfacl[1] and man:setfacl[1] to manage ACLs. ACLs are useful in scenarios requiring more specific access control than standard permissions, commonly used in multi-user environments or shared hosting. However, complexity may be unavoidable, but careful planning is required to ensure that the desired security properties are being provided [NOTE] ==== FreeBSD supports the implementation of NFSv4 ACLs in both UFS and OpenZFS. Please note that some arguments to the man:setfacl[1] command only work with POSIX ACLs and others in NFSv4 ACLs. ==== [[acl-enabling-support-ufs]] === Enabling ACL Support in UFS ACLs are enabled by the mount-time administrative flag, `acls`, which may be added to [.filename]#/etc/fstab#. Therefore it will be necessary to access [.filename]#/etc/fstab# and in the options section add the `acls` flag as follows: [.programlisting] .... # Device Mountpoint FStype Options Dump Pass# /dev/ada0s1a / ufs rw,acls 1 1 .... [[security-acl-info]] === Get ACLs information It is possible to check the ACLs of a file or a directory using man:getfacl[1]. For example, to view the ACL settings on [.filename]#~/test# file execute the following command: [source,shell] .... % getfacl test .... The output should be similar to the following in case of using NFSv4 ACLs: [.programlisting] .... # file: test # owner: freebsduser # group: freebsduser owner@:rw-p--aARWcCos:-------:allow group@:r-----a-R-c--s:-------:allow everyone@:r-----a-R-c--s:-------:allow .... And the output should be similar to the following in case of using POSIX.1e ACLs: [.programlisting] .... # file: test # owner: freebsduser # group: freebsduser user::rw- group::r-- other::r-- .... [[security-working-acls]] === Working with ACLs man:setfacl[1] can be used to add, modify or remove ACLs from a file or directory. As noted above, some arguments to man:setfacl[1] do not work with NFSv4 ACLs, and vice versa. This section covers how to execute the commands for POSIX ACLs and for NFSv4 ACLs and shows examples of both. For example, to set the mandatory elements of the POSIX.1e default ACL: [source,shell] .... % setfacl -d -m u::rwx,g::rx,o::rx,mask::rwx directory .... This other example sets read, write, and execute permissions for the file owner's POSIX.1e ACL entry and read and write permissions for group mail on file: [source,shell] .... % setfacl -m u::rwx,g:mail:rw file .... To do the same as in the previous example but in NFSv4 ACL: [source,shell] .... % setfacl -m owner@:rwxp::allow,g:mail:rwp::allow file .... To remove all ACL entries except for the three required from file in POSIX.1e ACL: [source,shell] .... % setfacl -bn file .... To remove all ACL entries in NFSv4 ACL: [source,shell] .... % setfacl -b file .... Refer to man:getfacl[1] and man:setfacl[1] for more information about the options available for these commands. [[capsicum]] == Capsicum Capsicum is a lightweight OS capability and sandbox framework implementing a hybrid capability system model. Capabilities are unforgeable tokens of authority that can be delegated and must be presented to perform an action. Capsicum makes file descriptors into capabilities. Capsicum can be used for application and library compartmentalisation, the decomposition of larger bodies of software into isolated (sandboxed) components in order to implement security policies and limit the impact of software vulnerabilities. [[security-accounting]] == 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. [NOTE] ==== If more fine-grained accounting is needed, refer to crossref:audit[audit,Security Event Auditing]. ==== === Enabling and Utilizing Process Accounting Before using process accounting, it must be enabled using the following commands: [source,shell] .... # sysrc accounting_enable=yes # service accounting start .... The accounting information is stored in files located in [.filename]#/var/account#, which is automatically created, if necessary, the first time the accounting service starts. These files contain sensitive information, including all the commands issued by all users. Write access to the files is limited to `root`, and read access is limited to `root` and members of the `wheel` group. To also prevent members of `wheel` from reading the files, change the mode of the [.filename]#/var/account# directory to allow access only by `root`. 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 man:sa[8]. If issued without any options, man:sa[8] 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: [source,shell] .... # lastcomm ls trhodes ttyp1 .... Many other useful options exist and are explained in man:lastcomm[1], man:acct[5], and man:sa[8]. [[security-resourcelimits]] == Resource Limits In FreeBSD, resource limits refer to the mechanisms that control and manage the allocation of various system resources to processes and users. These limits are designed to prevent a single process or user from consuming an excessive amount of resources, which could lead to performance degradation or system instability. Resource limits help ensure fair resource distribution among all active processes and users on the system. FreeBSD provides several methods for an administrator to limit the amount of system resources an individual may use. The traditional method defines login classes by editing [.filename]#/etc/login.conf#. While this method is still supported, any changes require a multi-step process of editing this file, rebuilding the resource database, making necessary changes to [.filename]#/etc/master.passwd#, and rebuilding the password database. This can become time consuming, depending upon the number of users to configure. man:rctl[8] can be used to provide a more fine-grained method for controlling resource limits. This command supports more than user limits as it can also be used to set resource constraints on processes and jails. This section demonstrates both methods for controlling resources, beginning with the traditional method. [[security-resource-limits-types]] === Types of Resources FreeBSD provides limits for various types of resources, including: .Resource types [options="header", cols="1,1"] |=== | Type | Description | CPU Time | Limits the amount of CPU time a process can consume | Memory | Controls the amount of physical memory a process can use | Open Files | Limits the number of files a process can have open simultaneously | Processes | Controls the number of processes a user or a process can create | File Size | Limits the maximum size of files that a process can create | Core Dumps | Controls whether processes are allowed to generate core dump files | Network Resources | Limits the amount of network resources (e.g., sockets) a process can use |=== For a full listing of types see man:login.conf[5] and man:rctl[8]. [[users-limiting]] === Configuring Login Classes In the traditional method, login classes and the resource limits to apply to a login class are defined in [.filename]#/etc/login.conf#. Each user account can be assigned to a login class, where `default` is the default login class. 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_. The first step to configure a resource limit will be to open [.filename]#/etc/login.conf# by executing the following command: [source,shell] .... # ee /etc/login.conf .... Then locate the section for the user class to be modified. In this example, let's assume the user class is named `limited`, create it in case it not exists. [.programlisting] .... limited:\ <.> :maxproc=50:\ <.> :tc=default: <.> .... <.> Name of the user class. <.> Sets the maximum number of processes (maxproc) to 50 for users in the `limited` class. <.> Indicates that this user class inherits the default settings from the "default" class. After modifying the [.filename]#/etc/login.conf# file, run man:cap_mkdb[1] to generate the database that FreeBSD uses to apply these settings: [source,shell] .... # cap_mkdb /etc/login.conf .... man:chpass[1] can be used to change the class to the desired user executint the following command: [source,shell] .... # chpass username .... This will open a text editor, add the new `limited` class there as follows: [.programlisting] .... #Changing user information for username. Login: username Password: $6$2H.419USdGaiJeqK$6kgcTnDadasdasd3YnlNZsOni5AMymibkAfRCPirc7ZFjjv DVsKyXx26daabdfqSdasdsmL/ZMUpdHiO0 Uid [#]: 1001 Gid [# or name]: 1001 Change [month day year]: Expire [month day year]: Class: limited Home directory: /home/username Shell: /bin/sh Full Name: User & Office Location: Office Phone: Home Phone: Other information: .... Now, the user assigned to the `limited` class will have a maximum process limit of 50. Remember that this is just one example of setting a resource limit using the [.filename]#/etc/login.conf# file. Keep in mind that after making changes to the [.filename]#/etc/login.conf# file, the user needs to log out and log back in for the changes to take effect. Additionally, always exercise caution when editing system configuration files, especially when using privileged access. [[security-rctl]] === Enabling and Configuring Resource Limits The man:rctl[8] system provides a more fine-grained way to set and manage resource limits for individual processes and users. It allows you to dynamically assign resource limits to specific processes or users, regardless of their user class. The first step to use man:rctl[8] will be to enable it adding the following line to [.filename]#/boot/loader.conf# and reboot the system: [.programlisting] .... kern.racct.enable=1 .... Then active the man:rctl[8] service and enable it executing by the following commands: [source,shell] .... # sysrc rctl_enable="YES" # service rctl start .... Then man:rctl[8] may be used to set rules for the system. Rule syntax (man:rctl.conf[5]) is controlled through the use of a subject, subject-id, resource, and action, as seen in this example rule: [.programlisting] .... subject:subject-id:resource:action=amount/per .... For example to constrained the user to add no more than 10 processes execute the following command: [source,shell] .... # rctl -a user:username:maxproc:deny=10/user .... To check the applied resource limits the man:rctl[8] command can be executed: [source,shell] .... # rctl .... The output should be similar to the following: [.programlisting] .... user:username:maxproc:deny=10 .... Rules will persist across reboots if they have been added to [.filename]#/etc/rctl.conf#. The format is a rule, without the preceding command. For example, the previous rule could be added as: [.programlisting] .... user:username:maxproc:deny=10 .... [[security-pkg]] == Monitoring Third Party Security Issues 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 FreeBSD releases advisories for the base system, doing so for every third party utility is beyond the FreeBSD Project's capability. There is a way to mitigate third party vulnerabilities and warn administrators of known security issues. A FreeBSD add on utility known as pkg includes options explicitly for this purpose. pkg polls a database for security issues. The database is updated and maintained by the FreeBSD Security Team and ports developers. Installation provides man:periodic[8] configuration files for maintaining the pkg audit database, and provides a programmatic method of keeping it updated. After installation, and to audit third party utilities as part of the Ports Collection at any time, an administrator may choose to update the database and view known vulnerabilities of installed packages by invoking: [source,shell] .... % pkg audit -F .... The output should be similar to the following: [.programlisting] .... vulnxml file up-to-date chromium-116.0.5845.96_1 is vulnerable: chromium -- multiple vulnerabilities CVE: CVE-2023-4431 CVE: CVE-2023-4427 CVE: CVE-2023-4428 CVE: CVE-2023-4429 CVE: CVE-2023-4430 WWW: https://vuxml.FreeBSD.org/freebsd/5fa332b9-4269-11ee-8290-a8a1599412c6.html samba413-4.13.17_5 is vulnerable: samba -- multiple vulnerabilities CVE: CVE-2023-3347 CVE: CVE-2023-34966 CVE: CVE-2023-34968 CVE: CVE-2022-2127 CVE: CVE-2023-34967 WWW: https://vuxml.FreeBSD.org/freebsd/441e1e1a-27a5-11ee-a156-080027f5fec9.html 2 problem(s) in 2 installed package(s) found. .... 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 FreeBSD port version, along with other web sites which may contain security advisories. [[security-advisories]] == FreeBSD Security Advisories Like many producers of quality operating systems, the FreeBSD Project has a security team which is responsible for determining the End-of-Life (EoL) date for each FreeBSD release and to provide security updates for supported releases which have not yet reached their EoL. More information about the FreeBSD security team and the supported releases is available on the link:https://www.FreeBSD.org/security[FreeBSD security page]. One task of the security team is to respond to reported security vulnerabilities in the FreeBSD 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 link:https://www.FreeBSD.org/security/advisories/[FreeBSD website] and mailed to the {freebsd-security-notifications}, {freebsd-security}, and {freebsd-announce}. === Format of a Security Advisory Here is an example of a FreeBSD security advisory: [.programlisting] .... -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 ============================================================================= FreeBSD-SA-23:07.bhyve Security Advisory The FreeBSD Project Topic: bhyve privileged guest escape via fwctl Category: core Module: bhyve Announced: 2023-08-01 Credits: Omri Ben Bassat and Vladimir Eli Tokarev from Microsoft Affects: FreeBSD 13.1 and 13.2 Corrected: 2023-08-01 19:48:53 UTC (stable/13, 13.2-STABLE) 2023-08-01 19:50:47 UTC (releng/13.2, 13.2-RELEASE-p2) 2023-08-01 19:48:26 UTC (releng/13.1, 13.1-RELEASE-p9) CVE Name: CVE-2023-3494 For general information regarding FreeBSD Security Advisories, including descriptions of the fields above, security branches, and the following sections, please visit . I. Background bhyve(8)'s fwctl interface provides a mechanism through which guest firmware can query the hypervisor for information about the virtual machine. The fwctl interface is available to guests when bhyve is run with the "-l bootrom" option, used for example when booting guests in UEFI mode. bhyve is currently only supported on the amd64 platform. II. Problem Description The fwctl driver implements a state machine which is executed when the guest accesses certain x86 I/O ports. The interface lets the guest copy a string into a buffer resident in the bhyve process' memory. A bug in the state machine implementation can result in a buffer overflowing when copying this string. III. Impact A malicious, privileged software running in a guest VM can exploit the buffer overflow to achieve code execution on the host in the bhyve userspace process, which typically runs as root. Note that bhyve runs in a Capsicum sandbox, so malicious code is constrained by the capabilities available to the bhyve process. IV. Workaround No workaround is available. bhyve guests that are executed without the "-l bootrom" option are unaffected. V. Solution Upgrade your vulnerable system to a supported FreeBSD stable or release / security branch (releng) dated after the correction date. Perform one of the following: 1) To update your vulnerable system via a binary patch: Systems running a RELEASE version of FreeBSD on the amd64, i386, or (on FreeBSD 13 and later) arm64 platforms can be updated via the freebsd-update(8) utility: # freebsd-update fetch # freebsd-update install Restart all affected virtual machines. 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 13.2] # fetch https://security.FreeBSD.org/patches/SA-23:07/bhyve.13.2.patch # fetch https://security.FreeBSD.org/patches/SA-23:07/bhyve.13.2.patch.asc # gpg --verify bhyve.13.2.patch.asc [FreeBSD 13.1] # fetch https://security.FreeBSD.org/patches/SA-23:07/bhyve.13.1.patch # fetch https://security.FreeBSD.org/patches/SA-23:07/bhyve.13.1.patch.asc # gpg --verify bhyve.13.1.patch.asc b) Apply the patch. Execute the following commands as root: # cd /usr/src # patch < /path/to/patch c) Recompile the operating system using buildworld and installworld as described in . Restart all affected virtual machines. VI. Correction details This issue is corrected by the corresponding Git commit hash or Subversion revision number in the following stable and release branches: Branch/path Hash Revision - ------------------------------------------------------------------------- stable/13/ 9fe302d78109 stable/13-n255918 releng/13.2/ 2bae613e0da3 releng/13.2-n254625 releng/13.1/ 87702e38a4b4 releng/13.1-n250190 - ------------------------------------------------------------------------- Run the following command to see which files were modified by a particular commit: # git show --stat Or visit the following URL, replacing NNNNNN with the hash: To determine the commit count in a working tree (for comparison against nNNNNNN in the table above), run: # git rev-list --count --first-parent HEAD VII. References The latest revision of this advisory is available at -----BEGIN PGP SIGNATURE----- iQIzBAEBCgAdFiEEthUnfoEIffdcgYM7bljekB8AGu8FAmTJdsIACgkQbljekB8A Gu8Q1Q/7BFw5Aa0cFxBzbdz+O5NAImj58MvKS6xw61bXcYr12jchyT6ENC7yiR+K qCqbe5TssRbtZ1gg/94gSGEXccz5OcJGxW+qozhcdPUh2L2nzBPkMCrclrYJfTtM cnmQKjg/wFZLUVr71GEM95ZFaktlZdXyXx9Z8eBzow5rXexpl1TTHQQ2kZZ41K4K KFhup91dzGCIj02cqbl+1h5BrXJe3s/oNJt5JKIh/GBh5THQu9n6AywQYl18HtjV fMb1qRTAS9WbiEP5QV2eEuOG86ucuhytqnEN5MnXJ2rLSjfb9izs9HzLo3ggy7yb hN3tlbfIPjMEwYexieuoyP3rzKkLeYfLXqJU4zKCRnIbBIkMRy4mcFkfcYmI+MhF NPh2R9kccemppKXeDhKJurH0vsetr8ti+AwOZ3pgO21+9w+mjE+EfaedIi+JWhip hwqeFv03bAQHJdacNYGV47NsJ91CY4ZgWC3ZOzBZ2Y5SDtKFjyc0bf83WTfU9A/0 drC0z3xaJribah9e6k5d7lmZ7L6aHCbQ70+aayuAEZQLr/N1doB0smNi0IHdrtY0 JdIqmVX+d1ihVhJ05prC460AS/Kolqiaysun1igxR+ZnctE9Xdo1BlLEbYu2KjT4 LpWvSuhRMSQaYkJU72SodQc0FM5mqqNN42Vx+X4EutOfvQuRGlI= =MlAY -----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 crossref:pgpkeys[pgpkeys,OpenPGP Keys]. * The name of the security advisory always begins with `FreeBSD-SA-` (for FreeBSD Security Advisory), followed by the year in two digit format (`23:`), followed by the advisory number for that year (`07.`), followed by the name of the affected application or subsystem (`bhyve`). * 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 FreeBSD operating system. The `contrib` category means that the vulnerability affects software included with FreeBSD, 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 `bhyve` 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 FreeBSD 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 FreeBSD are affected by this vulnerability. * The `Corrected` field indicates the date, time, time offset, and releases that were corrected. The section in parentheses shows each branch for which the fix has been merged, and the version number of the corresponding release from that branch. The release identifier itself includes the version number and, if appropriate, the patch level. The patch level is the letter `p` followed by a number, indicating the sequence number of the patch, allowing users to track which patches have already been applied to the system. * The `CVE Name` field lists the advisory number, if one exists, in the public http://cve.mitre.org[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 or Git branch with the revision number that contains the corrected code. * The `References` field offers sources of additional information regarding the vulnerability.