diff --git a/documentation/content/en/articles/fonts/_index.adoc b/documentation/content/en/articles/fonts/_index.adoc index 9ff3afd3c8..846046013f 100644 --- a/documentation/content/en/articles/fonts/_index.adoc +++ b/documentation/content/en/articles/fonts/_index.adoc @@ -1,516 +1,516 @@ --- title: Fonts and FreeBSD subtitle: A Tutorial authors: - author: Dave Bodenstab email: imdave@synet.net releaseinfo: "$FreeBSD$" trademarks: ["freebsd", "adobe", "apple", "linux", "microsoft", "opengroup", "general"] --- = Fonts and FreeBSD :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :source-highlighter: rouge :experimental: :sectnumlevels: 6 [.abstract-title] Abstract This document contains a description of the various font files that may be used with FreeBSD and the syscons driver, X11, Ghostscript and Groff. Cookbook examples are provided for switching the syscons display to 80x60 mode, and for using type 1 fonts with the above application programs. ''' toc::[] [[intro]] == Introduction There are many sources of fonts available, and one might ask how they might be used with FreeBSD. The answer can be found by carefully searching the documentation for the component that one would like to use. This is very time consuming, so this tutorial is an attempt to provide a shortcut for others who might be interested. [[terminology]] == Basic Terminology There are many different font formats and associated font file suffixes. A few that will be addressed here are: [.filename]#.pfa#, [.filename]#.pfb#:: PostScript(R) type 1 fonts. The [.filename]#.pfa# is the __A__scii form and [.filename]#.pfb# the __B__inary form. [.filename]#.afm#:: The font metrics associated with a type 1 font. [.filename]#.pfm#:: The printer font metrics associated with a type 1 font. [.filename]#.ttf#:: A TrueType(R) font [.filename]#.fot#:: An indirect reference to a TrueType font (not an actual font) [.filename]#.fon#, [.filename]#.fnt#:: Bitmapped screen fonts The [.filename]#.fot# is used by Windows(R) as sort of a symbolic link to the actual TrueType(R) font ([.filename]#.ttf#) file. The [.filename]#.fon# font files are also used by Windows. I know of no way to use this font format with FreeBSD. [[font-formats]] == What Font Formats Can I Use? Which font file format is useful depends on the application being used. FreeBSD by itself uses no fonts. Application programs and/or drivers may make use of the font files. Here is a small cross reference of application/driver to the font type suffixes: Driver:: vt::: [.filename]#.hex# syscons::: [.filename]#.fnt# Application:: Ghostscript::: [.filename]#.pfa#, [.filename]#.pfb#, [.filename]#.ttf# X11::: [.filename]#.pfa#, [.filename]#.pfb# Groff::: [.filename]#.pfa#, [.filename]#.afm# Povray::: [.filename]#.ttf# The [.filename]#.fnt# suffix is used quite frequently. I suspect that whenever someone wanted to create a specialized font file for their application, more often than not they chose this suffix. Therefore, it is likely that files with this suffix are not all the same format; specifically, the [.filename]#.fnt# files used by syscons under FreeBSD may not be the same format as a [.filename]#.fnt# one encounters in the MS-DOS(R)/Windows(R) environment. I have not made any attempt at using other [.filename]#.fnt# files other than those provided with FreeBSD. [[virtual-console]] == Setting a Virtual Console to 80x60 Line Mode First, an 8x8 font must be loaded. To do this, [.filename]#/etc/rc.conf# should contain the line (change the font name to an appropriate one for your locale): [.programlisting] .... -font8x8="iso-8x8" # font 8x8 from /usr/shared/syscons/fonts/* (or NO). +font8x8="iso-8x8" # font 8x8 from /usr/share/syscons/fonts/* (or NO). .... The command to actually switch the mode is man:vidcontrol[1]: [source,bash] .... % vidcontrol VGA_80x60 .... Various screen-oriented programs, such as man:vi[1], must be able to determine the current screen dimensions. As this is achieved this through `ioctl` calls to the console driver (such as man:syscons[4]) they will correctly determine the new screen dimensions. To make this more seamless, one can embed these commands in the startup scripts so it takes place when the system boots. To do this is add this line to [.filename]#/etc/rc.conf#. [.programlisting] .... allscreens_flags="VGA_80x60" # Set this vidcontrol mode for all virtual screens .... References: man:rc.conf[5], man:vidcontrol[1]. [[type1-fonts-x11]] == Using Type 1 Fonts with X11 X11 can use either the [.filename]#.pfa# or the [.filename]#.pfb# format fonts. The X11 fonts are located in various subdirectories under [.filename]#/usr/X11R6/lib/X11/fonts#. Each font file is cross referenced to its X11 name by the contents of [.filename]#fonts.dir# in each directory. There is already a directory named [.filename]#Type1#. The most straight forward way to add a new font is to put it into this directory. A better way is to keep all new fonts in a separate directory and use a symbolic link to the additional font. This allows one to more easily keep track of ones fonts without confusing them with the fonts that were originally provided. For example: [source,bash] .... Create a directory to contain the font files % mkdir -p /usr/local/shared/fonts/type1 % cd /usr/local/shared/fonts/type1 Place the .pfa, .pfb and .afm files here One might want to keep readme files, and other documentation for the fonts here also % cp /cdrom/fonts/atm/showboat/showboat.pfb . % cp /cdrom/fonts/atm/showboat/showboat.afm . Maintain an index to cross reference the fonts % echo showboat - InfoMagic CICA, Dec 1994, /fonts/atm/showboat >>INDEX .... Now, to use a new font with X11, one must make the font file available and update the font name files. The X11 font names look like: [.programlisting] .... -bitstream-charter-medium-r-normal-xxx-0-0-0-0-p-0-iso8859-1 | | | | | | | | | | | | \ \ | | | | | \ \ \ \ \ \ \ +----+- character set | | | | \ \ \ \ \ \ \ +- average width | | | | \ \ \ \ \ \ +- spacing | | | \ \ \ \ \ \ +- vertical res. | | | \ \ \ \ \ +- horizontal res. | | | \ \ \ \ +- points | | | \ \ \ +- pixels | | | \ \ \ foundry family weight slant width additional style .... A new name needs to be created for each new font. If you have some information from the documentation that accompanied the font, then it could serve as the basis for creating the name. If there is no information, then you can get some idea by using man:strings[1] on the font file. For example: [source,bash] .... % strings showboat.pfb | more %!FontType1-1.0: Showboat 001.001 %%CreationDate: 1/15/91 5:16:03 PM %%VMusage: 1024 45747 % Generated by Fontographer 3.1 % Showboat 1991 by David Rakowski. Alle Rechte Vorbehalten. FontDirectory/Showboat known{/Showboat findfont dup/UniqueID known{dup /UniqueID get 4962377 eq exch/FontType get 1 eq and}{pop false}ifelse {save true}{false}ifelse}{false}ifelse 12 dict begin /FontInfo 9 dict dup begin /version (001.001) readonly def /FullName (Showboat) readonly def /FamilyName (Showboat) readonly def /Weight (Medium) readonly def /ItalicAngle 0 def /isFixedPitch false def /UnderlinePosition -106 def /UnderlineThickness 16 def /Notice (Showboat 1991 by David Rakowski. Alle Rechte Vorbehalten.) readonly def end readonly def /FontName /Showboat def --stdin-- .... Using this information, a possible name might be: [source,bash] .... -type1-Showboat-medium-r-normal-decorative-0-0-0-0-p-0-iso8859-1 .... The components of our name are: Foundry:: Lets just name all the new fonts `type1`. Family:: The name of the font. Weight:: Normal, bold, medium, semibold, etc. From the man:strings[1] output above, it appears that this font has a weight of __medium__. Slant:: __r__oman, __i__talic, __o__blique, etc. Since the _ItalicAngle_ is zero, _roman_ will be used. Width:: Normal, wide, condensed, extended, etc. Until it can be examined, the assumption will be __normal__. Additional style:: Usually omitted, but this will indicate that the font contains decorative capital letters. Spacing:: proportional or monospaced. _Proportional_ is used since _isFixedPitch_ is false. All of these names are arbitrary, but one should strive to be compatible with the existing conventions. A font is referenced by name with possible wild cards by an X11 program, so the name chosen should make some sense. One might begin by simply using [source,bash] .... ...-normal-r-normal-...-p-... .... as the name, and then use man:xfontsel[1] to examine it and adjust the name based on the appearance of the font. So, to complete our example: [source,bash] .... Make the font accessible to X11 % cd /usr/X11R6/lib/X11/fonts/Type1 % ln -s /usr/local/shared/fonts/type1/showboat.pfb . Edit fonts.dir and fonts.scale, adding the line describing the font and incrementing the number of fonts which is found on the first line. % ex fonts.dir :1p 25 :1c 26 . :$a showboat.pfb -type1-showboat-medium-r-normal-decorative-0-0-0-0-p-0-iso8859-1 . :wq fonts.scale seems to be identical to fonts.dir... % cp fonts.dir fonts.scale Tell X11 that things have changed % xset fp rehash Examine the new font % xfontsel -pattern -type1-* .... References: man:xfontsel[1], man:xset[1], The X Windows System in a Nutshell, http://www.ora.com/[O'Reilly & Associates]. [[type1-fonts-ghostscript]] == Using Type 1 Fonts with Ghostscript Ghostscript references a font via its [.filename]#Fontmap#. This must be modified in a similar way to the X11 [.filename]#fonts.dir#. Ghostscript can use either the [.filename]#.pfa# or the [.filename]#.pfb# format fonts. Using the font from the previous example, here is how to use it with Ghostscript: [source,bash] .... Put the font in Ghostscript's font directory % cd /usr/local/shared/ghostscript/fonts % ln -s /usr/local/shared/fonts/type1/showboat.pfb . Edit Fontmap so Ghostscript knows about the font % cd /usr/local/shared/ghostscript/4.01 % ex Fontmap :$a /Showboat (showboat.pfb) ; % From CICA /fonts/atm/showboat . :wq Use Ghostscript to examine the font % gs prfont.ps Aladdin Ghostscript 4.01 (1996-7-10) Copyright (C) 1996 Aladdin Enterprises, Menlo Park, CA. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Loading Times-Roman font from /usr/local/shared/ghostscript/fonts/tir_____.pfb... /1899520 581354 1300084 13826 0 done. GS>Showboat DoFont Loading Showboat font from /usr/local/shared/ghostscript/fonts/showboat.pfb... 1939688 565415 1300084 16901 0 done. >>showpage, press to continue<< >>showpage, press to continue<< >>showpage, press to continue<< GS>quit .... References: [.filename]#fonts.txt# in the Ghostscript 4.01 distribution [[type1-fonts-groff]] == Using Type 1 Fonts with Groff -Now that the new font can be used by both X11 and Ghostscript, how can one use the new font with groff? First of all, since we are dealing with type 1 PostScript(R) fonts, the groff device that is applicable is the _ps_ device. A font file must be created for each font that groff can use. A groff font name is just a file in [.filename]#/usr/shared/groff_font/devps#. With our example, the font file could be [.filename]#/usr/shared/groff_font/devps/SHOWBOAT#. The file must be created using tools provided by groff. +Now that the new font can be used by both X11 and Ghostscript, how can one use the new font with groff? First of all, since we are dealing with type 1 PostScript(R) fonts, the groff device that is applicable is the _ps_ device. A font file must be created for each font that groff can use. A groff font name is just a file in [.filename]#/usr/share/groff_font/devps#. With our example, the font file could be [.filename]#/usr/share/groff_font/devps/SHOWBOAT#. The file must be created using tools provided by groff. The first tool is `afmtodit`. This is not normally installed, so it must be retrieved from the source distribution. I found I had to change the first line of the file, so I did: [source,bash] .... % cp /usr/src/gnu/usr.bin/groff/afmtodit/afmtodit.pl /tmp % ex /tmp/afmtodit.pl :1c #!/usr/bin/perl -P- . :wq .... This tool will create the groff font file from the metrics file ([.filename]#.afm# suffix.) Continuing with our example: [source,bash] .... Many .afm files are in Mac format... ^M delimited lines We need to convert them to UNIX(R) style ^J delimited lines % cd /tmp % cat /usr/local/shared/fonts/type1/showboat.afm | tr '\015' '\012' >showboat.afm Now create the groff font file -% cd /usr/shared/groff_font/devps +% cd /usr/share/groff_font/devps % /tmp/afmtodit.pl -d DESC -e text.enc /tmp/showboat.afm generate/textmap SHOWBOAT .... The font can now be referenced with the name SHOWBOAT. If Ghostscript is used to drive the printers on the system, then nothing more needs to be done. However, if true PostScript(R) printers are used, then the font must be downloaded to the printer in order for the font to be used (unless the printer happens to have the showboat font built in or on an accessible font disk.) The final step is to create a downloadable font. The `pfbtops` tool is used to create the [.filename]#.pfa# format of the font, and [.filename]#download# is modified to reference the new font. The [.filename]#download# must reference the internal name of the font. This can easily be determined from the groff font file as illustrated: [source,bash] .... Create the .pfa font file % pfbtops /usr/local/shared/fonts/type1/showboat.pfb >showboat.pfa .... Of course, if [.filename]#.pfa# is already available, just use a symbolic link to reference it. [source,bash] .... Get the internal font name % fgrep internalname SHOWBOAT internalname Showboat Tell groff that the font must be downloaded % ex download :$a Showboat showboat.pfa . :wq .... To test the font: [source,bash] .... % cd /tmp % cat >example.t <example.ps To use ghostscript/ghostview % ghostview example.ps To print it % lpr -Ppostscript example.ps .... References: [.filename]#/usr/src/gnu/usr.bin/groff/afmtodit/afmtodit.man#, man:groff_font[5], man:groff_char[7], man:pfbtops[1]. [[convert-truetype]] == Converting TrueType Fonts to a groff/PostScript Format For groff This potentially requires a bit of work, simply because it depends on some utilities that are not installed as part of the base system. They are: `ttf2pf`:: TrueType to PostScript conversion utilities. This allows conversion of a TrueType font to an ascii font metric ([.filename]#.afm#) file. + Currently available at http://sunsite.icm.edu.pl/pub/GUST/contrib/BachoTeX98/ttf2pf/[http://sunsite.icm.edu.pl/pub/GUST/contrib/BachoTeX98/ttf2pf/]. Note: These files are PostScript programs and must be downloaded to disk by holding down kbd:[Shift] when clicking on the link. Otherwise, your browser may try to launch ghostview to view them. + The files of interest are: ** [.filename]#GS_TTF.PS# ** [.filename]#PF2AFM.PS# ** [.filename]#ttf2pf.ps# + The funny upper/lower case is due to their being intended also for DOS shells. [.filename]#ttf2pf.ps# makes use of the others as upper case, so any renaming must be consistent with this. (Actually, [.filename]#GS_TTF.PS# and [.filename]#PFS2AFM.PS# are supposedly part of the Ghostscript distribution, but it is just as easy to use these as an isolated utility. FreeBSD does not seem to include the latter.) You also may want to have these installed to [.filename]#/usr/local/shared/groff_font/devps#(?). `afmtodit`:: Creates font files for use with groff from ascii font metrics file. This usually resides in the directory, [.filename]#/usr/src/contrib/groff/afmtodit#, and requires some work to get going. + [NOTE] ==== If you are paranoid about working in the [.filename]#/usr/src# tree, simply copy the contents of the above directory to a work location. ==== + In the work area, you will need to make the utility. Just type: + [source,bash] .... # make -f Makefile.sub afmtodit .... + -You may also need to copy [.filename]#/usr/contrib/groff/devps/generate/textmap# to [.filename]#/usr/shared/groff_font/devps/generate# if it does not already exist. +You may also need to copy [.filename]#/usr/contrib/groff/devps/generate/textmap# to [.filename]#/usr/share/groff_font/devps/generate# if it does not already exist. Once all these utilities are in place, you are ready to commence: . Create [.filename]#.afm# by typing: + [source,bash] .... % gs -dNODISPLAY -q -- ttf2pf.ps TTF_name PS_font_name AFM_name .... + Where, _TTF_name_ is your TrueType font file, _PS_font_name_ is the file name for [.filename]#.pfa#, _AFM_name_ is the name you wish for [.filename]#.afm#. If you do not specify output file names for the [.filename]#.pfa# or [.filename]#.afm# files, then default names will be generated from the TrueType font file name. + This also produces a [.filename]#.pfa#, the ascii PostScript font metrics file ([.filename]#.pfb# is for the binary form). This will not be needed, but could (I think) be useful for a fontserver. + For example, to convert the 30f9 Barcode font using the default file names, use the following command: + [source,bash] .... % gs -dNODISPLAY -- ttf2pf.ps 3of9.ttf Aladdin Ghostscript 5.10 (1997-11-23) Copyright (C) 1997 Aladdin Enterprises, Menlo Park, CA. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Converting 3of9.ttf to 3of9.pfa and 3of9.afm. .... + If you want the converted fonts to be stored in [.filename]#A.pfa# and [.filename]#B.afm#, then use this command: + [source,bash] .... % gs -dNODISPLAY -- ttf2pf.ps 3of9.ttf A B Aladdin Ghostscript 5.10 (1997-11-23) Copyright (C) 1997 Aladdin Enterprises, Menlo Park, CA. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Converting 3of9.ttf to A.pfa and B.afm. .... . Create the groff PostScript file: + -Change directories to [.filename]#/usr/shared/groff_font/devps# so as to make the following command easier to execute. You will probably need root privileges for this. (Or, if you are paranoid about working there, make sure you reference the files [.filename]#DESC#, [.filename]#text.enc# and [.filename]#generate/textmap# as being in this directory.) +Change directories to [.filename]#/usr/share/groff_font/devps# so as to make the following command easier to execute. You will probably need root privileges for this. (Or, if you are paranoid about working there, make sure you reference the files [.filename]#DESC#, [.filename]#text.enc# and [.filename]#generate/textmap# as being in this directory.) + [source,bash] .... % afmtodit -d DESC -e text.enc file.afm generate/textmap PS_font_name .... + Where, [.filename]#file.afm# is the _AFM_name_ created by `ttf2pf.ps` above, and _PS_font_name_ is the font name used from that command, as well as the name that man:groff[1] will use for references to this font. For example, assuming you used the first `tiff2pf.ps` above, then the 3of9 Barcode font can be created using the command: + [source,bash] .... % afmtodit -d DESC -e text.enc 3of9.afm generate/textmap 3of9 .... + -Ensure that the resulting _PS_font_name_ file (e.g., [.filename]#3of9# in the example above) is located in the directory [.filename]#/usr/shared/groff_font/devps# by copying or moving it there. +Ensure that the resulting _PS_font_name_ file (e.g., [.filename]#3of9# in the example above) is located in the directory [.filename]#/usr/share/groff_font/devps# by copying or moving it there. + Note that if [.filename]#ttf2pf.ps# assigns a font name using the one it finds in the TrueType font file and you want to use a different name, you must edit the [.filename]#.afm# prior to running `afmtodit`. This name must also match the one used in the Fontmap file if you wish to pipe man:groff[1] into man:gs[1]. [[truetype-for-other-programs]] == Can TrueType Fonts be Used with Other Programs? The TrueType font format is used by Windows, Windows 95, and Mac's. It is quite popular and there are a great number of fonts available in this format. Unfortunately, there are few applications that I am aware of that can use this format: Ghostscript and Povray come to mind. Ghostscript's support, according to the documentation, is rudimentary and the results are likely to be inferior to type 1 fonts. Povray version 3 also has the ability to use TrueType fonts, but I rather doubt many people will be creating documents as a series of raytraced pages :-). This rather dismal situation may soon change. The http://www.freetype.org/[FreeType Project] is currently developing a useful set of FreeType tools: * The `xfsft` font server for X11 can serve TrueType fonts in addition to regular fonts. Though currently in beta, it is said to be quite usable. See http://www.dcs.ed.ac.uk/home/jec/programs/xfsft/[Juliusz Chroboczek's page] for further information. Porting instructions for FreeBSD can be found at http://math.missouri.edu/~stephen/software/[Stephen Montgomery's software page]. * xfstt is another font server for X11, available under link:ftp://sunsite.unc.edu/pub/Linux/X11/fonts/[ftp://sunsite.unc.edu/pub/Linux/X11/fonts/]. * A program called `ttf2bdf` can produce BDF files suitable for use in an X environment from TrueType files. Linux binaries are said to be available from link:ftp://crl.nmsu.edu/CLR/multiling/General/[ftp://crl.nmsu.edu/CLR/multiling/General/]. * and others ... [[obtaining-additional-fonts]] == Where Can Additional Fonts be Obtained? Many fonts are available on the Internet. They are either entirely free, or are share-ware. In addition many fonts are available in the [.filename]#x11-fonts/# category in the ports collection [[additional-questions]] == Additional Questions * What use are the [.filename]#.pfm# files? * Can one generate the [.filename]#.afm# from a [.filename]#.pfa# or [.filename]#.pfb#? * How to generate the groff character mapping files for PostScript fonts with non-standard character names? * Can xditview and devX?? devices be set up to access all the new fonts? * It would be good to have examples of using TrueType fonts with Povray and Ghostscript. diff --git a/documentation/content/en/articles/rc-scripting/_index.adoc b/documentation/content/en/articles/rc-scripting/_index.adoc index 1106c92505..7bd655e21d 100644 --- a/documentation/content/en/articles/rc-scripting/_index.adoc +++ b/documentation/content/en/articles/rc-scripting/_index.adoc @@ -1,592 +1,592 @@ --- title: Practical rc.d scripting in BSD authors: - author: Yar Tikhiy email: yar@FreeBSD.org copyright: 2005-2006, 2012 The FreeBSD Project releaseinfo: "$FreeBSD$" trademarks: ["freebsd", "netbsd", "general"] --- = Practical rc.d scripting in BSD :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: include::shared/en/urls.adoc[] [.abstract-title] Abstract Beginners may find it difficult to relate the facts from the formal documentation on the BSD [.filename]#rc.d# framework with the practical tasks of [.filename]#rc.d# scripting. In this article, we consider a few typical cases of increasing complexity, show [.filename]#rc.d# features suited for each case, and discuss how they work. Such an examination should provide reference points for further study of the design and efficient application of [.filename]#rc.d#. ''' toc::[] [[rcng-intro]] == Introduction The historical BSD had a monolithic startup script, [.filename]#/etc/rc#. It was invoked by man:init[8] at system boot time and performed all userland tasks required for multi-user operation: checking and mounting file systems, setting up the network, starting daemons, and so on. The precise list of tasks was not the same in every system; admins needed to customize it. With few exceptions, [.filename]#/etc/rc# had to be modified, and true hackers liked it. The real problem with the monolithic approach was that it provided no control over the individual components started from [.filename]#/etc/rc#. For instance, [.filename]#/etc/rc# could not restart a single daemon. The system admin had to find the daemon process by hand, kill it, wait until it actually exited, then browse through [.filename]#/etc/rc# for the flags, and finally type the full command line to start the daemon again. The task would become even more difficult and prone to errors if the service to restart consisted of more than one daemon or demanded additional actions. In a few words, the single script failed to fulfil what scripts are for: to make the system admin's life easier. Later there was an attempt to split out some parts of [.filename]#/etc/rc# for the sake of starting the most important subsystems separately. The notorious example was [.filename]#/etc/netstart# to bring up networking. It did allow for accessing the network from single-user mode, but it did not integrate well into the automatic startup process because parts of its code needed to interleave with actions essentially unrelated to networking. That was why [.filename]#/etc/netstart# mutated into [.filename]#/etc/rc.network#. The latter was no longer an ordinary script; it comprised of large, tangled man:sh[1] functions called from [.filename]#/etc/rc# at different stages of system startup. However, as the startup tasks grew diverse and sophisticated, the "quasi-modular" approach became even more of a drag than the monolithic [.filename]#/etc/rc# had been. Without a clean and well-designed framework, the startup scripts had to bend over backwards to satisfy the needs of rapidly developing BSD-based operating systems. It became obvious at last that more steps are necessary on the way to a fine-grained and extensible [.filename]#rc# system. Thus BSD [.filename]#rc.d# was born. Its acknowledged fathers were Luke Mewburn and the NetBSD community. Later it was imported into FreeBSD. Its name refers to the location of system scripts for individual services, which is in [.filename]#/etc/rc.d#. Soon we will learn about more components of the [.filename]#rc.d# system and see how the individual scripts are invoked. The basic ideas behind BSD [.filename]#rc.d# are _fine modularity_ and __code reuse__. _Fine modularity_ means that each basic "service" such as a system daemon or primitive startup task gets its own man:sh[1] script able to start the service, stop it, reload it, check its status. A particular action is chosen by the command-line argument to the script. The [.filename]#/etc/rc# script still drives system startup, but now it merely invokes the smaller scripts one by one with the `start` argument. It is easy to perform shutdown tasks as well by running the same set of scripts with the `stop` argument, which is done by [.filename]#/etc/rc.shutdown#. Note how closely this follows the Unix way of having a set of small specialized tools, each fulfilling its task as well as possible. _Code reuse_ means that common operations are implemented as man:sh" "1" >}} functions and collected in [.filename]#/etc/rc.subr#. Now a typical script can be just a few lines' worth of man:sh" "1" >}} code. Finally, an important part of the [.filename]#rc.d# framework is man:rcorder[8], which helps [.filename]#/etc/rc# to run the small scripts orderly with respect to dependencies between them. It can help [.filename]#/etc/rc.shutdown#, too, because the proper order for the shutdown sequence is opposite to that of startup. The BSD [.filename]#rc.d# design is described in <>, and the [.filename]#rc.d# components are documented in great detail in <>. However, it might not appear obvious to an [.filename]#rc.d# newbie how to tie the numerous bits and pieces together in order to create a well-styled script for a particular task. Therefore this article will try a different approach to describe [.filename]#rc.d#. It will show which features should be used in a number of typical cases, and why. Note that this is not a how-to document because our aim is not at giving ready-made recipes, but at showing a few easy entrances into the [.filename]#rc.d# realm. Neither is this article a replacement for the relevant manual pages. Do not hesitate to refer to them for more formal and complete documentation while reading this article. There are prerequisites to understanding this article. First of all, you should be familiar with the man:sh[1] scripting language in order to master [.filename]#rc.d#. In addition, you should know how the system performs userland startup and shutdown tasks, which is described in man:rc[8]. This article focuses on the FreeBSD branch of [.filename]#rc.d#. Nevertheless, it may be useful to NetBSD developers, too, because the two branches of BSD [.filename]#rc.d# not only share the same design but also stay similar in their aspects visible to script authors. [[rcng-task]] == Outlining the task A little consideration before starting `$EDITOR` will not hurt. In order to write a well-tempered [.filename]#rc.d# script for a system service, we should be able to answer the following questions first: * Is the service mandatory or optional? * Will the script serve a single program, e.g., a daemon, or perform more complex actions? * Which other services will our service depend on, and vice versa? From the examples that follow we will see why it is important to know the answers to these questions. [[rcng-dummy]] == A dummy script The following script just emits a message each time the system boots up: [.programlisting] .... #!/bin/sh <.> . /etc/rc.subr <.> name="dummy" <.> start_cmd="${name}_start" <.> stop_cmd=":" <.> dummy_start() <.> { echo "Nothing started." } load_rc_config $name <.> run_rc_command "$1" <.> .... Things to note are: ➊ An interpreted script should begin with the magic "shebang" line. That line specifies the interpreter program for the script. Due to the shebang line, the script can be invoked exactly like a binary program provided that it has the execute bit set. (See man:chmod[1].) For example, a system admin can run our script manually, from the command line: [source,bash] .... # /etc/rc.d/dummy start .... [NOTE] ==== In order to be properly managed by the [.filename]#rc.d# framework, its scripts need to be written in the man:sh[1] language. If you have a service or port that uses a binary control utility or a startup routine written in another language, install that element in [.filename]#/usr/sbin# (for the system) or [.filename]#/usr/local/sbin# (for ports) and call it from a man:sh[1] script in the appropriate [.filename]#rc.d# directory. ==== [TIP] ==== If you would like to learn the details of why [.filename]#rc.d# scripts must be written in the man:sh[1] language, see how [.filename]#/etc/rc# invokes them by means of `run_rc_script`, then study the implementation of `run_rc_script` in [.filename]#/etc/rc.subr#. ==== ➋ In [.filename]#/etc/rc.subr#, a number of man:sh[1] functions are defined for an [.filename]#rc.d# script to use. The functions are documented in man:rc.subr[8]. While it is theoretically possible to write an [.filename]#rc.d# script without ever using man:rc.subr[8], its functions prove extremely handy and make the job an order of magnitude easier. So it is no surprise that everybody resorts to man:rc.subr[8] in [.filename]#rc.d# scripts. We are not going to be an exception. An [.filename]#rc.d# script must "source"[.filename]#/etc/rc.subr# (include it using "`.`") _before_ it calls man:rc.subr[8] functions so that man:sh[1] has an opportunity to learn the functions. The preferred style is to source [.filename]#/etc/rc.subr# first of all. [NOTE] ==== Some useful functions related to networking are provided by another include file, [.filename]#/etc/network.subr#. ==== ➌ [[name-var]]The mandatory variable `name` specifies the name of our script. It is required by man:rc.subr[8]. That is, each [.filename]#rc.d# script _must_ set `name` before it calls man:rc.subr[8] functions. Now it is the right time to choose a unique name for our script once and for all. We will use it in a number of places while developing the script. For a start, let us give the same name to the script file, too. [NOTE] ==== The current style of [.filename]#rc.d# scripting is to enclose values assigned to variables in double quotes. Keep in mind that it is just a style issue that may not always be applicable. You can safely omit quotes from around simple words without man:sh[1] metacharacters in them, while in certain cases you will need single quotes to prevent any interpretation of the value by man:sh[1]. A programmer should be able to tell the language syntax from style conventions and use both of them wisely. ==== ➍ The main idea behind man:rc.subr[8] is that an [.filename]#rc.d# script provides handlers, or methods, for man:rc.subr[8] to invoke. In particular, `start`, `stop`, and other arguments to an [.filename]#rc.d# script are handled this way. A method is a man:sh[1] expression stored in a variable named `argument_cmd`, where _argument_ corresponds to what can be specified on the script's command line. We will see later how man:rc.subr[8] provides default methods for the standard arguments. [NOTE] ==== To make the code in [.filename]#rc.d# more uniform, it is common to use `${name}` wherever appropriate. Thus a number of lines can be just copied from one script to another. ==== ➎ We should keep in mind that man:rc.subr[8] provides default methods for the standard arguments. Consequently, we must override a standard method with a no-op man:sh[1] expression if we want it to do nothing. ➏ The body of a sophisticated method can be implemented as a function. It is a good idea to make the function name meaningful. [IMPORTANT] ==== It is strongly recommended to add the prefix `${name}` to the names of all functions defined in our script so they never clash with the functions from man:rc.subr[8] or another common include file. ==== ➐ This call to man:rc.subr[8] loads man:rc.conf[5] variables. Our script makes no use of them yet, but it still is recommended to load man:rc.conf[5] because there can be man:rc.conf[5] variables controlling man:rc.subr[8] itself. ➑ Usually this is the last command in an [.filename]#rc.d# script. It invokes the man:rc.subr[8] machinery to perform the requested action using the variables and methods our script has provided. [[rcng-confdummy]] == A configurable dummy script Now let us add some controls to our dummy script. As you may know, [.filename]#rc.d# scripts are controlled with man:rc.conf[5]. Fortunately, man:rc.subr[8] hides all the complications from us. The following script uses man:rc.conf[5] via man:rc.subr[8] to see whether it is enabled in the first place, and to fetch a message to show at boot time. These two tasks in fact are independent. On the one hand, an [.filename]#rc.d# script can just support enabling and disabling its service. On the other hand, a mandatory [.filename]#rc.d# script can have configuration variables. We will do both things in the same script though: [.programlisting] .... #!/bin/sh . /etc/rc.subr name=dummy rcvar=dummy_enable <.> start_cmd="${name}_start" stop_cmd=":" load_rc_config $name <.> : ${dummy_enable:=no} <.> : ${dummy_msg="Nothing started."} <.> dummy_start() { echo "$dummy_msg" <.> } run_rc_command "$1" .... What changed in this example? ➊ The variable `rcvar` specifies the name of the ON/OFF knob variable. ➋ Now `load_rc_config` is invoked earlier in the script, before any man:rc.conf[5] variables are accessed. [NOTE] ==== While examining [.filename]#rc.d# scripts, keep in mind that man:sh[1] defers the evaluation of expressions in a function until the latter is called. Therefore it is not an error to invoke `load_rc_config` as late as just before `run_rc_command` and still access man:rc.conf[5] variables from the method functions exported to `run_rc_command`. This is because the method functions are to be called by `run_rc_command`, which is invoked _after_ `load_rc_config`. ==== ➌ A warning will be emitted by `run_rc_command` if `rcvar` itself is set, but the indicated knob variable is unset. If your [.filename]#rc.d# script is for the base system, you should add a default setting for the knob to [.filename]#/etc/defaults/rc.conf# and document it in man:rc.conf[5]. Otherwise it is your script that should provide a default setting for the knob. The canonical approach to the latter case is shown in the example. [NOTE] ==== You can make man:rc.subr[8] act as though the knob is set to `ON`, irrespective of its current setting, by prefixing the argument to the script with `one` or `force`, as in `onestart` or `forcestop`. Keep in mind though that `force` has other dangerous effects we will touch upon below, while `one` just overrides the ON/OFF knob. E.g., assume that `dummy_enable` is `OFF`. The following command will run the `start` method in spite of the setting: [source,bash] .... # /etc/rc.d/dummy onestart .... ==== ➍ Now the message to be shown at boot time is no longer hard-coded in the script. It is specified by an man:rc.conf[5] variable named `dummy_msg`. This is a trivial example of how man:rc.conf[5] variables can control an [.filename]#rc.d# script. [IMPORTANT] ==== The names of all man:rc.conf[5] variables used exclusively by our script _must_ have the same prefix: `${name}_`. For example: `dummy_mode`, `dummy_state_file`, and so on. ==== [NOTE] ==== While it is possible to use a shorter name internally, e.g., just `msg`, adding the unique prefix `${name}_` to all global names introduced by our script will save us from possible collisions with the man:rc.subr[8] namespace. As a rule, [.filename]#rc.d# scripts of the base system need not provide defaults for their man:rc.conf[5] variables because the defaults should be set in [.filename]#/etc/defaults/rc.conf# instead. On the other hand, [.filename]#rc.d# scripts for ports should provide the defaults as shown in the example. ==== ➎ Here we use `dummy_msg` to actually control our script, i.e., to emit a variable message. Use of a shell function is overkill here, since it only runs a single command; an equally valid alternative is: [.programlisting] .... start_cmd="echo \"$dummy_msg\"" .... [[rcng-daemon]] == Startup and shutdown of a simple daemon We said earlier that man:rc.subr[8] could provide default methods. Obviously, such defaults cannot be too general. They are suited for the common case of starting and shutting down a simple daemon program. Let us assume now that we need to write an [.filename]#rc.d# script for such a daemon called `mumbled`. Here it is: [.programlisting] .... #!/bin/sh . /etc/rc.subr name=mumbled rcvar=mumbled_enable command="/usr/sbin/${name}" <.> load_rc_config $name run_rc_command "$1" .... Pleasingly simple, isn't it? Let us examine our little script. The only new thing to note is as follows: ➊ The `command` variable is meaningful to man:rc.subr[8]. If it is set, man:rc.subr[8] will act according to the scenario of serving a conventional daemon. In particular, the default methods will be provided for such arguments: `start`, `stop`, `restart`, `poll`, and `status`. The daemon will be started by running `$command` with command-line flags specified by `$mumbled_flags`. Thus all the input data for the default `start` method are available in the variables set by our script. Unlike `start`, other methods may require additional information about the process started. For instance, `stop` must know the PID of the process to terminate it. In the present case, man:rc.subr[8] will scan through the list of all processes, looking for a process with its name equal to `procname`. The latter is another variable of meaning to man:rc.subr[8], and its value defaults to that of `command`. In other words, when we set `command`, `procname` is effectively set to the same value. This enables our script to kill the daemon and to check if it is running in the first place. [NOTE] ==== Some programs are in fact executable scripts. The system runs such a script by starting its interpreter and passing the name of the script to it as a command-line argument. This is reflected in the list of processes, which can confuse man:rc.subr[8]. You should additionally set `command_interpreter` to let man:rc.subr[8] know the actual name of the process if `$command` is a script. For each [.filename]#rc.d# script, there is an optional man:rc.conf[5] variable that takes precedence over `command`. Its name is constructed as follows: `${name}_program`, where `name` is the mandatory variable we discussed <>. E.g., in this case it will be `mumbled_program`. It is man:rc.subr[8] that arranges `${name}_program` to override `command`. Of course, man:sh[1] will permit you to set `${name}_program` from man:rc.conf[5] or the script itself even if `command` is unset. In that case, the special properties of `${name}_program` are lost, and it becomes an ordinary variable your script can use for its own purposes. However, the sole use of `${name}_program` is discouraged because using it together with `command` became an idiom of [.filename]#rc.d# scripting. ==== For more detailed information on default methods, refer to man:rc.subr[8]. [[rcng-daemon-adv]] == Startup and shutdown of an advanced daemon Let us add some meat onto the bones of the previous script and make it more complex and featureful. The default methods can do a good job for us, but we may need some of their aspects tweaked. Now we will learn how to tune the default methods to our needs. [.programlisting] .... #!/bin/sh . /etc/rc.subr name=mumbled rcvar=mumbled_enable command="/usr/sbin/${name}" command_args="mock arguments > /dev/null 2>&1" <.> pidfile="/var/run/${name}.pid" <.> -required_files="/etc/${name}.conf /usr/shared/misc/${name}.rules" <.> +required_files="/etc/${name}.conf /usr/share/misc/${name}.rules" <.> sig_reload="USR1" <.> start_precmd="${name}_prestart" <.> stop_postcmd="echo Bye-bye" <.> extra_commands="reload plugh xyzzy" <.> plugh_cmd="mumbled_plugh" <.> xyzzy_cmd="echo 'Nothing happens.'" mumbled_prestart() { if checkyesno mumbled_smart; then <.> rc_flags="-o smart ${rc_flags}" <.> fi case "$mumbled_mode" in foo) rc_flags="-frotz ${rc_flags}" ;; bar) rc_flags="-baz ${rc_flags}" ;; *) warn "Invalid value for mumbled_mode" <.> return 1 <.> ;; esac run_rc_command xyzzy <.> return 0 } mumbled_plugh() <.> { echo 'A hollow voice says "plugh".' } load_rc_config $name run_rc_command "$1" .... ➊ Additional arguments to `$command` can be passed in `command_args`. They will be added to the command line after `$mumbled_flags`. Since the final command line is passed to `eval` for its actual execution, input and output redirections can be specified in `command_args`. [NOTE] ==== _Never_ include dashed options, like `-X` or `--foo`, in `command_args`. The contents of `command_args` will appear at the end of the final command line, hence they are likely to follow arguments present in `${name}_flags`; but most commands will not recognize dashed options after ordinary arguments. A better way of passing additional options to `$command` is to add them to the beginning of `${name}_flags`. Another way is to modify `rc_flags` <>. ==== ➋ A good-mannered daemon should create a _pidfile_ so that its process can be found more easily and reliably. The variable `pidfile`, if set, tells man:rc.subr[8] where it can find the pidfile for its default methods to use. [NOTE] ==== In fact, man:rc.subr[8] will also use the pidfile to see if the daemon is already running before starting it. This check can be skipped by using the `faststart` argument. ==== ➌ If the daemon cannot run unless certain files exist, just list them in `required_files`, and man:rc.subr[8] will check that those files do exist before starting the daemon. There also are `required_dirs` and `required_vars` for directories and environment variables, respectively. They all are described in detail in man:rc.subr[8]. [NOTE] ==== The default method from man:rc.subr[8] can be forced to skip the prerequisite checks by using `forcestart` as the argument to the script. ==== ➍ We can customize signals to send to the daemon in case they differ from the well-known ones. In particular, `sig_reload` specifies the signal that makes the daemon reload its configuration; it is SIGHUP by default. Another signal is sent to stop the daemon process; the default is SIGTERM, but this can be changed by setting `sig_stop` appropriately. [NOTE] ==== The signal names should be specified to man:rc.subr[8] without the `SIG` prefix, as it is shown in the example. The FreeBSD version of man:kill[1] can recognize the `SIG` prefix, but the versions from other OS types may not. ==== ➎➏ Performing additional tasks before or after the default methods is easy. For each command-argument supported by our script, we can define `argument_precmd` and `argument_postcmd`. These man:sh[1] commands are invoked before and after the respective method, as it is evident from their names. [NOTE] ==== Overriding a default method with a custom `argument_cmd` still does not prevent us from making use of `argument_precmd` or `argument_postcmd` if we need to. In particular, the former is good for checking custom, sophisticated conditions that should be met before performing the command itself. Using `argument_precmd` along with `argument_cmd` lets us logically separate the checks from the action. Do not forget that you can cram any valid man:sh[1] expressions into the methods, pre-, and post-commands you define. Just invoking a function that makes the real job is a good style in most cases, but never let style limit your understanding of what is going on behind the curtain. ==== ➐ If we would like to implement custom arguments, which can also be thought of as _commands_ to our script, we need to list them in `extra_commands` and provide methods to handle them. [NOTE] ==== The `reload` command is special. On the one hand, it has a preset method in man:rc.subr[8]. On the other hand, `reload` is not offered by default. The reason is that not all daemons use the same reload mechanism and some have nothing to reload at all. So we need to ask explicitly that the builtin functionality be provided. We can do so via `extra_commands`. What do we get from the default method for `reload`? Quite often daemons reload their configuration upon reception of a signal - typically, SIGHUP. Therefore man:rc.subr[8] attempts to reload the daemon by sending a signal to it. The signal is preset to SIGHUP but can be customized via `sig_reload` if necessary. ==== ➑⓮ Our script supports two non-standard commands, `plugh` and `xyzzy`. We saw them listed in `extra_commands`, and now it is time to provide methods for them. The method for `xyzzy` is just inlined while that for `plugh` is implemented as the `mumbled_plugh` function. Non-standard commands are not invoked during startup or shutdown. Usually they are for the system admin's convenience. They can also be used from other subsystems, e.g., man:devd[8] if specified in man:devd.conf[5]. The full list of available commands can be found in the usage line printed by man:rc.subr[8] when the script is invoked without arguments. For example, here is the usage line from the script under study: [source,bash] .... # /etc/rc.d/mumbled Usage: /etc/rc.d/mumbled [fast|force|one](start|stop|restart|rcvar|reload|plugh|xyzzy|status|poll) .... ⓭ A script can invoke its own standard or non-standard commands if needed. This may look similar to calling functions, but we know that commands and shell functions are not always the same thing. For instance, `xyzzy` is not implemented as a function here. In addition, there can be a pre-command and post-command, which should be invoked orderly. So the proper way for a script to run its own command is by means of man:rc.subr[8], as shown in the example. ➒ A handy function named `checkyesno` is provided by man:rc.subr[8]. It takes a variable name as its argument and returns a zero exit code if and only if the variable is set to `YES`, or `TRUE`, or `ON`, or `1`, case insensitive; a non-zero exit code is returned otherwise. In the latter case, the function tests the variable for being set to `NO`, `FALSE`, `OFF`, or `0`, case insensitive; it prints a warning message if the variable contains anything else, i.e., junk. Keep in mind that for man:sh[1] a zero exit code means true and a non-zero exit code means false. [IMPORTANT] ==== The `checkyesno` function takes a __variable name__. Do not pass the expanded _value_ of a variable to it; it will not work as expected. The following is the correct usage of `checkyesno`: [.programlisting] .... if checkyesno mumbled_enable; then foo fi .... On the contrary, calling `checkyesno` as shown below will not work - at least not as expected: [.programlisting] .... if checkyesno "${mumbled_enable}"; then foo fi .... ==== ➓ [[rc-flags]]We can affect the flags to be passed to `$command` by modifying `rc_flags` in `$start_precmd`. ⓫ In certain cases we may need to emit an important message that should go to `syslog` as well. This can be done easily with the following man:rc.subr[8] functions: `debug`, `info`, `warn`, and `err`. The latter function then exits the script with the code specified. ⓬ The exit codes from methods and their pre-commands are not just ignored by default. If `argument_precmd` returns a non-zero exit code, the main method will not be performed. In turn, `argument_postcmd` will not be invoked unless the main method returns a zero exit code. [NOTE] ==== However, man:rc.subr[8] can be instructed from the command line to ignore those exit codes and invoke all commands anyway by prefixing an argument with `force`, as in `forcestart`. ==== [[rcng-hookup]] == Connecting a script to the rc.d framework After a script has been written, it needs to be integrated into [.filename]#rc.d#. The crucial step is to install the script in [.filename]#/etc/rc.d# (for the base system) or [.filename]#/usr/local/etc/rc.d# (for ports). Both [.filename]#bsd.prog.mk# and [.filename]#bsd.port.mk# provide convenient hooks for that, and usually you do not have to worry about the proper ownership and mode. System scripts should be installed from [.filename]#src/etc/rc.d# through the [.filename]#Makefile# found there. Port scripts can be installed using `USE_RC_SUBR` as described link:{porters-handbook}#rc-scripts[in the Porter's Handbook]. However, we should consider beforehand the place of our script in the system startup sequence. The service handled by our script is likely to depend on other services. For instance, a network daemon cannot function without the network interfaces and routing up and running. Even if a service seems to demand nothing, it can hardly start before the basic filesystems have been checked and mounted. We mentioned man:rcorder[8] already. Now it is time to have a close look at it. In a nutshell, man:rcorder[8] takes a set of files, examines their contents, and prints a dependency-ordered list of files from the set to `stdout`. The point is to keep dependency information _inside_ the files so that each file can speak for itself only. A file can specify the following information: * the names of the "conditions" (which means services to us) it __provides__; * the names of the "conditions" it __requires__; * the names of the "conditions" this file should run __before__; * additional _keywords_ that can be used to select a subset from the whole set of files (man:rcorder[8] can be instructed via options to include or omit the files having particular keywords listed.) It is no surprise that man:rcorder[8] can handle only text files with a syntax close to that of man:sh[1]. That is, special lines understood by man:rcorder[8] look like man:sh[1] comments. The syntax of such special lines is rather rigid to simplify their processing. See man:rcorder[8] for details. Besides using man:rcorder[8] special lines, a script can insist on its dependency upon another service by just starting it forcibly. This can be needed when the other service is optional and will not start by itself because the system admin has disabled it mistakenly in man:rc.conf[5]. With this general knowledge in mind, let us consider the simple daemon script enhanced with dependency stuff: [.programlisting] .... #!/bin/sh # PROVIDE: mumbled oldmumble <.> # REQUIRE: DAEMON cleanvar frotz <.> # BEFORE: LOGIN <.> # KEYWORD: nojail shutdown <.> . /etc/rc.subr name=mumbled rcvar=mumbled_enable command="/usr/sbin/${name}" start_precmd="${name}_prestart" mumbled_prestart() { if ! checkyesno frotz_enable && \ ! /etc/rc.d/frotz forcestatus 1>/dev/null 2>&1; then force_depend frotz || return 1 <.> fi return 0 } load_rc_config $name run_rc_command "$1" .... As before, detailed analysis follows: ➊ That line declares the names of "conditions" our script provides. Now other scripts can record a dependency on our script by those names. [NOTE] ==== Usually a script specifies a single condition provided. However, nothing prevents us from listing several conditions there, e.g., for compatibility reasons. In any case, the name of the main, or the only, `PROVIDE:` condition should be the same as `${name}`. ==== ➋➌ So our script indicates which "conditions" provided by other scripts it depends on. According to the lines, our script asks man:rcorder[8] to put it after the script(s) providing [.filename]#DAEMON# and [.filename]#cleanvar#, but before that providing [.filename]#LOGIN#. [NOTE] ==== The `BEFORE:` line should not be abused to work around an incomplete dependency list in the other script. The appropriate case for using `BEFORE:` is when the other script does not care about ours, but our script can do its task better if run before the other one. A typical real-life example is the network interfaces vs. the firewall: While the interfaces do not depend on the firewall in doing their job, the system security will benefit from the firewall being ready before there is any network traffic. Besides conditions corresponding to a single service each, there are meta-conditions and their "placeholder" scripts used to ensure that certain groups of operations are performed before others. These are denoted by [.filename]#UPPERCASE# names. Their list and purposes can be found in man:rc[8]. Keep in mind that putting a service name in the `REQUIRE:` line does not guarantee that the service will actually be running by the time our script starts. The required service may fail to start or just be disabled in man:rc.conf[5]. Obviously, man:rcorder[8] cannot track such details, and man:rc[8] will not do that either. Consequently, the application started by our script should be able to cope with any required services being unavailable. In certain cases, we can help it as discussed <> ==== [[keywords]]➍ As we remember from the above text, man:rcorder[8] keywords can be used to select or leave out some scripts. Namely any man:rcorder[8] consumer can specify through `-k` and `-s` options which keywords are on the "keep list" and "skip list", respectively. From all the files to be dependency sorted, man:rcorder[8] will pick only those having a keyword from the keep list (unless empty) and not having a keyword from the skip list. In FreeBSD, man:rcorder[8] is used by [.filename]#/etc/rc# and [.filename]#/etc/rc.shutdown#. These two scripts define the standard list of FreeBSD [.filename]#rc.d# keywords and their meanings as follows: [[forcedep]]➎ To begin with, `force_depend` should be used with much care. It is generally better to revise the hierarchy of configuration variables for your [.filename]#rc.d# scripts if they are interdependent. If you still cannot do without `force_depend`, the example offers an idiom of how to invoke it conditionally. In the example, our `mumbled` daemon requires that another one, `frotz`, be started in advance. However, `frotz` is optional, too; and man:rcorder[8] knows nothing about such details. Fortunately, our script has access to all man:rc.conf[5] variables. If `frotz_enable` is true, we hope for the best and rely on [.filename]#rc.d# to have started `frotz`. Otherwise we forcibly check the status of `frotz`. Finally, we enforce our dependency on `frotz` if it is found to be not running. A warning message will be emitted by `force_depend` because it should be invoked only if a misconfiguration has been detected. [[rcng-args]] == Giving more flexibility to an rc.d script When invoked during startup or shutdown, an [.filename]#rc.d# script is supposed to act on the entire subsystem it is responsible for. E.g., [.filename]#/etc/rc.d/netif# should start or stop all network interfaces described by man:rc.conf[5]. Either task can be uniquely indicated by a single command argument such as `start` or `stop`. Between startup and shutdown, [.filename]#rc.d# scripts help the admin to control the running system, and it is when the need for more flexibility and precision arises. For instance, the admin may want to add the settings of a new network interface to man:rc.conf[5] and then to start it without interfering with the operation of the existing interfaces. Next time the admin may need to shut down a single network interface. In the spirit of the command line, the respective [.filename]#rc.d# script calls for an extra argument, the interface name. Fortunately, man:rc.subr[8] allows for passing any number of arguments to script's methods (within the system limits). Due to that, the changes in the script itself can be minimal. How can man:rc.subr[8] gain access to the extra command-line arguments. Should it just grab them directly? Not by any means. Firstly, an man:sh[1] function has no access to the positional parameters of its caller, but man:rc.subr[8] is just a sack of such functions. Secondly, the good manner of [.filename]#rc.d# dictates that it is for the main script to decide which arguments are to be passed to its methods. So the approach adopted by man:rc.subr[8] is as follows: `run_rc_command` passes on all its arguments but the first one to the respective method verbatim. The first, omitted, argument is the name of the method itself: `start`, `stop`, etc. It will be shifted out by `run_rc_command`, so what is `$2` in the original command line will be presented as `$1` to the method, and so on. To illustrate this opportunity, let us modify the primitive dummy script so that its messages depend on the additional arguments supplied. Here we go: [.programlisting] .... #!/bin/sh . /etc/rc.subr name="dummy" start_cmd="${name}_start" stop_cmd=":" kiss_cmd="${name}_kiss" extra_commands="kiss" dummy_start() { if [ $# -gt 0 ]; then <.> echo "Greeting message: $*" else echo "Nothing started." fi } dummy_kiss() { echo -n "A ghost gives you a kiss" if [ $# -gt 0 ]; then <.> echo -n " and whispers: $*" fi case "$*" in *[.!?]) echo ;; *) echo . ;; esac } load_rc_config $name run_rc_command "$@" <.> .... What essential changes can we notice in the script? ➊ All arguments you type after `start` can end up as positional parameters to the respective method. We can use them in any way according to our task, skills, and fancy. In the current example, we just pass all of them to man:echo[1] as one string in the next line - note `$*` within the double quotes. Here is how the script can be invoked now: [source,bash] .... # /etc/rc.d/dummy start Nothing started. # /etc/rc.d/dummy start Hello world! Greeting message: Hello world! .... ➋ The same applies to any method our script provides, not only to a standard one. We have added a custom method named `kiss`, and it can take advantage of the extra arguments not less than `start` does. E.g.: [source,bash] .... # /etc/rc.d/dummy kiss A ghost gives you a kiss. # /etc/rc.d/dummy kiss Once I was Etaoin Shrdlu... A ghost gives you a kiss and whispers: Once I was Etaoin Shrdlu... .... ➌ If we want just to pass all extra arguments to any method, we can merely substitute `"$@"` for `"$1"` in the last line of our script, where we invoke `run_rc_command`. [IMPORTANT] ==== An man:sh[1] programmer ought to understand the subtle difference between `$*` and `$@` as the ways to designate all positional parameters. For its in-depth discussion, refer to a good handbook on man:sh[1] scripting. _Do not_ use the expressions until you fully understand them because their misuse will result in buggy and insecure scripts. ==== [NOTE] ==== Currently `run_rc_command` may have a bug that prevents it from keeping the original boundaries between arguments. That is, arguments with embedded whitespace may not be processed correctly. The bug stems from `$*` misuse. ==== [[rcng-furthur]] == Further reading [[lukem]]http://www.mewburn.net/luke/papers/rc.d.pdf[The original article by Luke Mewburn] offers a general overview of [.filename]#rc.d# and detailed rationale for its design decisions. It provides insight on the whole [.filename]#rc.d# framework and its place in a modern BSD operating system. [[manpages]]The manual pages man:rc[8], man:rc.subr[8], and man:rcorder[8] document the [.filename]#rc.d# components in great detail. You cannot fully use the [.filename]#rc.d# power without studying the manual pages and referring to them while writing your own scripts. The major source of working, real-life examples is [.filename]#/etc/rc.d# in a live system. Its contents are easy and pleasant to read because most rough corners are hidden deep in man:rc.subr[8]. Keep in mind though that the [.filename]#/etc/rc.d# scripts were not written by angels, so they might suffer from bugs and suboptimal design decisions. Now you can improve them! diff --git a/documentation/content/en/books/developers-handbook/l10n/chapter.adoc b/documentation/content/en/books/developers-handbook/l10n/chapter.adoc index 4966af0aa2..3903ed3d75 100644 --- a/documentation/content/en/books/developers-handbook/l10n/chapter.adoc +++ b/documentation/content/en/books/developers-handbook/l10n/chapter.adoc @@ -1,209 +1,209 @@ --- title: Chapter 4. Localization and Internationalization - L10N and I18N authors: prev: books/developers-handbook/secure next: books/developers-handbook/policies --- [[l10n]] = Localization and Internationalization - L10N and I18N :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 4 include::shared/mirrors.adoc[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[l10n-programming]] == Programming I18N Compliant Applications To make your application more useful for speakers of other languages, we hope that you will program I18N compliant. The GNU gcc compiler and GUI libraries like QT and GTK support I18N through special handling of strings. Making a program I18N compliant is very easy. It allows contributors to port your application to other languages quickly. Refer to the library specific I18N documentation for more details. In contrast with common perception, I18N compliant code is easy to write. Usually, it only involves wrapping your strings with library specific functions. In addition, please be sure to allow for wide or multibyte character support. === A Call to Unify the I18N Effort It has come to our attention that the individual I18N/L10N efforts for each country has been repeating each others' efforts. Many of us have been reinventing the wheel repeatedly and inefficiently. We hope that the various major groups in I18N could congregate into a group effort similar to the Core Team's responsibility. Currently, we hope that, when you write or port I18N programs, you would send it out to each country's related FreeBSD mailing list for testing. In the future, we hope to create applications that work in all the languages out-of-the-box without dirty hacks. The {freebsd-i18n} has been established. If you are an I18N/L10N developer, please send your comments, ideas, questions, and anything you deem related to it. === Perl and Python Perl and Python have I18N and wide character handling libraries. Please use them for I18N compliance. [[posix-nls]] == Localized Messages with POSIX.1 Native Language Support (NLS) Beyond the basic I18N functions, like supporting various input encodings or supporting national conventions, such as the different decimal separators, at a higher level of I18N, it is possible to localize the messages written to the output by the various programs. A common way of doing this is using the POSIX.1 NLS functions, which are provided as a part of the FreeBSD base system. [[nls-catalogs]] === Organizing Localized Messages into Catalog Files POSIX.1 NLS is based on catalog files, which contain the localized messages in the desired encoding. The messages are organized into sets and each message is identified by an integer number in the containing set. The catalog files are conventionally named after the locale they contain localized messages for, followed by the `.msg` extension. For instance, the Hungarian messages for ISO8859-2 encoding should be stored in a file called [.filename]#hu_HU.ISO8859-2#. These catalog files are common text files that contain the numbered messages. It is possible to write comments by starting the line with a `$` sign. Set boundaries are also separated by special comments, where the keyword `set` must directly follow the `$` sign. The `set` keyword is then followed by the set number. For example: [.programlisting] .... $set 1 .... The actual message entries start with the message number and followed by the localized message. The well-known modifiers from man:printf[3] are accepted: [.programlisting] .... 15 "File not found: %s\n" .... The language catalog files have to be compiled into a binary form before they can be opened from the program. This conversion is done with the man:gencat[1] utility. Its first argument is the filename of the compiled catalog and its further arguments are the input catalogs. The localized messages can also be organized into more catalog files and then all of them can be processed with man:gencat[1]. [[nls-using]] === Using the Catalog Files from the Source Code -Using the catalog files is simple. To use the related functions, [.filename]#nl_types.h# must be included. Before using a catalog, it has to be opened with man:catopen[3]. The function takes two arguments. The first parameter is the name of the installed and compiled catalog. Usually, the name of the program is used, such as grep. This name will be used when looking for the compiled catalog file. The man:catopen[3] call looks for this file in [.filename]#/usr/shared/nls/locale/catname# and in [.filename]#/usr/local/shared/nls/locale/catname#, where `locale` is the locale set and `catname` is the catalog name being discussed. The second parameter is a constant, which can have two values: +Using the catalog files is simple. To use the related functions, [.filename]#nl_types.h# must be included. Before using a catalog, it has to be opened with man:catopen[3]. The function takes two arguments. The first parameter is the name of the installed and compiled catalog. Usually, the name of the program is used, such as grep. This name will be used when looking for the compiled catalog file. The man:catopen[3] call looks for this file in [.filename]#/usr/share/nls/locale/catname# and in [.filename]#/usr/local/shared/nls/locale/catname#, where `locale` is the locale set and `catname` is the catalog name being discussed. The second parameter is a constant, which can have two values: * `NL_CAT_LOCALE`, which means that the used catalog file will be based on `LC_MESSAGES`. * `0`, which means that `LANG` has to be used to open the proper catalog. The man:catopen[3] call returns a catalog identifier of type `nl_catd`. Please refer to the manual page for a list of possible returned error codes. After opening a catalog man:catgets[3] can be used to retrieve a message. The first parameter is the catalog identifier returned by man:catopen[3], the second one is the number of the set, the third one is the number of the messages, and the fourth one is a fallback message, which will be returned if the requested message cannot be retrieved from the catalog file. After using the catalog file, it must be closed by calling man:catclose[3], which has one argument, the catalog id. [[nls-example]] === A Practical Example The following example will demonstrate an easy solution on how to use NLS catalogs in a flexible way. The below lines need to be put into a common header file of the program, which is included into all source files where localized messages are necessary: [.programlisting] .... #ifdef WITHOUT_NLS #define getstr(n) nlsstr[n] #else #include nl_types.h extern nl_catd catalog; #define getstr(n) catgets(catalog, 1, n, nlsstr[n]) #endif extern char *nlsstr[]; .... Next, put these lines into the global declaration part of the main source file: [.programlisting] .... #ifndef WITHOUT_NLS #include nl_types.h nl_catd catalog; #endif /* * Default messages to use when NLS is disabled or no catalog * is found. */ char *nlsstr[] = { "", /* 1*/ "some random message", /* 2*/ "some other message" }; .... Next come the real code snippets, which open, read, and close the catalog: [.programlisting] .... #ifndef WITHOUT_NLS catalog = catopen("myapp", NL_CAT_LOCALE); #endif ... printf(getstr(1)); ... #ifndef WITHOUT_NLS catclose(catalog); #endif .... ==== Reducing Strings to Localize There is a good way of reducing the strings that need to be localized by using libc error messages. This is also useful to just avoid duplication and provide consistent error messages for the common errors that can be encountered by a great many of programs. First, here is an example that does not use libc error messages: [.programlisting] .... #include err.h ... if (!S_ISDIR(st.st_mode)) errx(1, "argument is not a directory"); .... This can be transformed to print an error message by reading `errno` and printing an error message accordingly: [.programlisting] .... #include err.h #include errno.h ... if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; err(1, NULL); } .... In this example, the custom string is eliminated, thus translators will have less work when localizing the program and users will see the usual "Not a directory" error message when they encounter this error. This message will probably seem more familiar to them. Please note that it was necessary to include [.filename]#errno.h# in order to directly access `errno`. It is worth to note that there are cases when `errno` is set automatically by a preceding call, so it is not necessary to set it explicitly: [.programlisting] .... #include err.h ... if ((p = malloc(size)) == NULL) err(1, NULL); .... [[nls-mk]] === Making use of [.filename]#bsd.nls.mk# Using the catalog files requires few repeatable steps, such as compiling the catalogs and installing them to the proper location. In order to simplify this process even more, [.filename]#bsd.nls.mk# introduces some macros. It is not necessary to include [.filename]#bsd.nls.mk# explicitly, it is pulled in from the common Makefiles, such as [.filename]#bsd.prog.mk# or [.filename]#bsd.lib.mk#. Usually it is enough to define `NLSNAME`, which should have the catalog name mentioned as the first argument of man:catopen[3] and list the catalog files in `NLS` without their `.msg` extension. Here is an example, which makes it possible to to disable NLS when used with the code examples before. The `WITHOUT_NLS` man:make[1] variable has to be defined in order to build the program without NLS support. [.programlisting] .... .if !defined(WITHOUT_NLS) NLS= es_ES.ISO8859-1 NLS+= hu_HU.ISO8859-2 NLS+= pt_BR.ISO8859-1 .else CFLAGS+= -DWITHOUT_NLS .endif .... Conventionally, the catalog files are placed under the [.filename]#nls# subdirectory and this is the default behavior of [.filename]#bsd.nls.mk#. It is possible, though to override the location of the catalogs with the `NLSSRCDIR` man:make[1] variable. The default name of the precompiled catalog files also follow the naming convention mentioned before. It can be overridden by setting the `NLSNAME` variable. There are other options to fine tune the processing of the catalog files but usually it is not needed, thus they are not described here. For further information on [.filename]#bsd.nls.mk#, please refer to the file itself, it is short and easy to understand. diff --git a/documentation/content/en/books/developers-handbook/tools/chapter.adoc b/documentation/content/en/books/developers-handbook/tools/chapter.adoc index cb23112114..c24e655267 100644 --- a/documentation/content/en/books/developers-handbook/tools/chapter.adoc +++ b/documentation/content/en/books/developers-handbook/tools/chapter.adoc @@ -1,1492 +1,1492 @@ --- title: Chapter 2. Programming Tools authors: - author: James Raynard - author: Murray Stokely prev: books/developers-handbook/introduction next: books/developers-handbook/secure --- [[tools]] = Programming Tools :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 2 :c-plus-plus-command: c++ :clang-plus-plus-command: clang++ include::shared/mirrors.adoc[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[tools-synopsis]] == Synopsis This chapter is an introduction to using some of the programming tools supplied with FreeBSD, although much of it will be applicable to many other versions of UNIX(R). It does _not_ attempt to describe coding in any detail. Most of the chapter assumes little or no previous programming knowledge, although it is hoped that most programmers will find something of value in it. [[tools-intro]] == Introduction FreeBSD offers an excellent development environment. Compilers for C and C++ and an assembler come with the basic system, not to mention classic UNIX(R) tools such as `sed` and `awk`. If that is not enough, there are many more compilers and interpreters in the Ports collection. The following section, <>, lists some of the available options. FreeBSD is very compatible with standards such as POSIX(R) and ANSI C, as well with its own BSD heritage, so it is possible to write applications that will compile and run with little or no modification on a wide range of platforms. However, all this power can be rather overwhelming at first if you have never written programs on a UNIX(R) platform before. This document aims to help you get up and running, without getting too deeply into more advanced topics. The intention is that this document should give you enough of the basics to be able to make some sense of the documentation. Most of the document requires little or no knowledge of programming, although it does assume a basic competence with using UNIX(R) and a willingness to learn! [[tools-programming]] == Introduction to Programming A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to perform depends on what happened when it performed a previous instruction. This section gives an overview of the two main ways in which you can give these instructions, or "commands" as they are usually called. One way uses an _interpreter_, the other a _compiler_. As human languages are too difficult for a computer to understand in an unambiguous way, commands are usually written in one or other languages specially designed for the purpose. === Interpreters With an interpreter, the language comes as an environment, where you type in commands at a prompt and the environment executes them for you. For more complicated programs, you can type the commands into a file and get the interpreter to load the file and execute the commands in it. If anything goes wrong, many interpreters will drop you into a debugger to help you track down the problem. The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected readily. The biggest disadvantage comes when you want to share your programs with someone. They must have the same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. Also users may not appreciate being thrown into a debugger if they press the wrong key! From a performance point of view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers. In my opinion, interpreted languages are the best way to start if you have not done any programming before. This kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also be argued that the UNIX(R) shell (`sh`, `csh`) is itself an interpreter, and many people do in fact write shell "scripts" to help with various "housekeeping" tasks on their machine. Indeed, part of the original UNIX(R) philosophy was to provide lots of small utility programs that could be linked together in shell scripts to perform useful tasks. === Interpreters Available with FreeBSD Here is a list of interpreters that are available from the FreeBSD Ports Collection, with a brief discussion of some of the more popular interpreted languages. Instructions on how to get and install applications from the Ports Collection can be found in the link:{handbook}#ports-using/[Ports section] of the handbook. BASIC:: Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching University students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been the first programming language for many programmers. It is also the foundation for Visual Basic. + The Bywater Basic Interpreter can be found in the Ports Collection as package:lang/bwbasic[] and the Phil Cockroft's Basic Interpreter (formerly Rabbit Basic) is available as package:lang/pbasic[]. Lisp:: A language that was developed in the late 1950s as an alternative to the "number-crunching" languages that were popular at the time. Instead of being based on numbers, Lisp is based on lists; in fact, the name is short for "List Processing". It is very popular in AI (Artificial Intelligence) circles. + Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. + Various implementations of Lisp that can run on UNIX(R) systems are available in the Ports Collection for FreeBSD. GNU Common Lisp can be found as package:lang/gcl[]. CLISP by Bruno Haible and Michael Stoll is available as package:lang/clisp[]. For CMUCL, which includes a highly-optimizing compiler too, or simpler Lisp implementations like SLisp, which implements most of the Common Lisp constructs in a few hundred lines of C code, package:lang/cmucl[] and package:lang/slisp[] are available respectively. Perl:: Very popular with system administrators for writing scripts; also often used on World Wide Web servers for writing CGI scripts. + Perl is available in the Ports Collection as package:lang/perl5.24[] for all FreeBSD releases. Scheme:: A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as it is simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to be used in research work. + Scheme is available from the Ports Collection as package:lang/elk[] for the Elk Scheme Interpreter. The MIT Scheme Interpreter can be found in package:lang/mit-scheme[] and the SCM Scheme Interpreter in package:lang/scm[]. Icon:: Icon is a high-level language with extensive facilities for processing strings and structures. The version of Icon for FreeBSD can be found in the Ports Collection as package:lang/icon[]. Logo:: Logo is a language that is easy to learn, and has been used as an introductory programming language in various courses. It is an excellent tool to work with when teaching programming to smaller age groups, as it makes creation of elaborate geometric shapes an easy task. + The latest version of Logo for FreeBSD is available from the Ports Collection in package:lang/logo[]. Python:: Python is an Object-Oriented, interpreted language. Its advocates argue that it is one of the best languages to start programming with, since it is relatively easy to start with, but is not limited in comparison to other popular interpreted languages that are used for the development of large, complex applications (Perl and Tcl are two other languages that are popular for such tasks). + The latest version of Python is available from the Ports Collection in package:lang/python[]. Ruby:: Ruby is an interpreter, pure object-oriented programming language. It has become widely popular because of its easy to understand syntax, flexibility when writing code, and the ability to easily develop and maintain large, complex programs. + Ruby is available from the Ports Collection as package:lang/ruby25[]. Tcl and Tk:: Tcl is an embeddable, interpreted language, that has become widely used and became popular mostly because of its portability to many platforms. It can be used both for quickly writing small, prototype applications, or (when combined with Tk, a GUI toolkit) fully-fledged, featureful programs. + Various versions of Tcl are available as ports for FreeBSD. The latest version, Tcl 8.5, can be found in package:lang/tcl87[]. === Compilers Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then run the compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the editor; if it did compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works properly.footnote:[If you run it in the shell, you may get a core dump.] Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things which are very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating system-or even writing your own operating system! It is also useful if you need to write very efficient code, as the compiler can take its time and optimize the code, which would not be acceptable in an interpreter. Moreover, distributing a program written for a compiler is usually more straightforward than one written for an interpreter-you can just give them a copy of the executable, assuming they have the same operating system as you. As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not include an IDE in the base system, but package:devel/kdevelop[] is available in the Ports Collection and many use Emacs for this purpose. Using Emacs as an IDE is discussed in <>. [[tools-compiling]] == Compiling with `cc` This section deals with the gcc and clang compilers for C and C++, since they come with the FreeBSD base system. Starting with FreeBSD 10.X `clang` is installed as `cc`. The details of producing a program with an interpreter vary considerably between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. Once you have written your masterpiece, the next step is to convert it into something that will (hopefully!) run on FreeBSD. This usually involves several steps, each of which is done by a separate program. [.procedure] . Pre-process your source code to remove comments and do other tricks like expanding macros in C. . Check the syntax of your code to see if you have obeyed the rules of the language. If you have not, it will complain! . Convert the source code into assembly language-this is very close to machine code, but still understandable by humans. Allegedly. . Convert the assembly language into machine code-yep, we are talking bits and bytes, ones and zeros here. . Check that you have used things like functions and global variables in a consistent way. For example, if you have called a non-existent function, it will complain. . If you are trying to produce an executable from several source code files, work out how to fit them all together. . Work out how to produce something that the system's run-time loader will be able to load into memory and run. . Finally, write the executable on the filesystem. The word _compiling_ is often used to refer to just steps 1 to 4-the others are referred to as _linking_. Sometimes step 1 is referred to as _pre-processing_ and steps 3-4 as _assembling_. Fortunately, almost all this detail is hidden from you, as `cc` is a front end that manages calling all these programs with the right arguments for you; simply typing [source,bash] .... % cc foobar.c .... will cause [.filename]#foobar.c# to be compiled by all the steps above. If you have more than one file to compile, just do something like [source,bash] .... % cc foo.c bar.c .... Note that the syntax checking is just that-checking the syntax. It will not check for any logical mistakes you may have made, like putting the program into an infinite loop, or using a bubble sort when you meant to use a binary sort.footnote:[In case you did not know, a binary sort is an efficient way of sorting things into order and a bubble sort is not.] There are lots and lots of options for `cc`, which are all in the manual page. Here are a few of the most important ones, with examples of how to use them. `-o _filename_`:: The output name of the file. If you do not use this option, `cc` will produce an executable called [.filename]#a.out#.footnote:[The reasons for this are buried in the mists of history.] + [source,bash] .... % cc foobar.c executable is a.out % cc -o foobar foobar.c executable is foobar .... `-c`:: Just compile the file, do not link it. Useful for toy programs where you just want to check the syntax, or if you are using a [.filename]#Makefile#. + [source,bash] .... % cc -c foobar.c .... + This will produce an _object file_ (not an executable) called [.filename]#foobar.o#. This can be linked together with other object files into an executable. `-g`:: Create a debug version of the executable. This makes the compiler put information into the executable about which line of which source file corresponds to which function call. A debugger can use this information to show the source code as you step through the program, which is _very_ useful; the disadvantage is that all this extra information makes the program much bigger. Normally, you compile with `-g` while you are developing a program and then compile a "release version" without `-g` when you are satisfied it works properly. + [source,bash] .... % cc -g foobar.c .... + This will produce a debug version of the program. footnote:[Note, we did not use the -o flag to specify the executable name, so we will get an executable called a.out. Producing a debug version called foobar is left as an exercise for the reader!] `-O`:: Create an optimized version of the executable. The compiler performs various clever tricks to try to produce an executable that runs faster than normal. You can add a number after the `-O` to specify a higher level of optimization, but this often exposes bugs in the compiler's optimizer. + [source,bash] .... % cc -O -o foobar foobar.c .... + This will produce an optimized version of [.filename]#foobar#. The following three flags will force `cc` to check that your code complies to the relevant international standard, often referred to as the ANSI standard, though strictly speaking it is an ISO standard. `-Wall`:: Enable all the warnings which the authors of `cc` believe are worthwhile. Despite the name, it will not enable all the warnings `cc` is capable of. `-ansi`:: Turn off most, but not all, of the non-ANSI C features provided by `cc`. Despite the name, it does not guarantee strictly that your code will comply to the standard. `-pedantic`:: Turn off _all_ ``cc``'s non-ANSI C features. Without these flags, `cc` will allow you to use some of its non-standard extensions to the standard. Some of these are very useful, but will not work with other compilers-in fact, one of the main aims of the standard is to allow people to write code that will work with any compiler on any system. This is known as _portable code_. Generally, you should try to make your code as portable as possible, as otherwise you may have to completely rewrite the program later to get it to work somewhere else-and who knows what you may be using in a few years time? [source,bash] .... % cc -Wall -ansi -pedantic -o foobar foobar.c .... This will produce an executable [.filename]#foobar# after checking [.filename]#foobar.c# for standard compliance. `-l__library__`:: Specify a function library to be used at link time. + The most common example of this is when compiling a program that uses some of the mathematical functions in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell the compiler to add it. + The rule is that if the library is called [.filename]#libsomething.a#, you give `cc` the argument `-l__something__`. For example, the math library is [.filename]#libm.a#, so you give `cc` the argument `-lm`. A common "gotcha" with the math library is that it has to be the last library on the command line. + [source,bash] .... % cc -o foobar foobar.c -lm .... + This will link the math library functions into [.filename]#foobar#. + If you are compiling C++ code, use {c-plus-plus-command}. {c-plus-plus-command} can also be invoked as {clang-plus-plus-command} on FreeBSD. + [source,bash] .... % c++ -o foobar foobar.cc .... + This will both produce an executable [.filename]#foobar# from the C++ source file [.filename]#foobar.cc#. === Common `cc` Queries and Problems ==== I am trying to write a program which uses the sin() function and I get an error like this. What does it mean? [source,bash] .... /var/tmp/cc0143941.o: Undefined symbol `_sin' referenced from text segment .... When using mathematical functions like `sin()`, you have to tell `cc` to link in the math library, like so: [source,bash] .... % cc -o foobar foobar.c -lm .... ==== All right, I wrote this simple program to practice using -lm. All it does is raise 2.1 to the power of 6. [.programlisting] .... #include int main() { float f; f = pow(2.1, 6); printf("2.1 ^ 6 = %f\n", f); return 0; } .... and I compiled it as: [source,bash] .... % cc temp.c -lm .... like you said I should, but I get this when I run it: [source,bash] .... % ./a.out 2.1 ^ 6 = 1023.000000 .... This is not the right answer! What is going on? When the compiler sees you call a function, it checks if it has already seen a prototype for it. If it has not, it assumes the function returns an int, which is definitely not what you want here. ==== So how do I fix this? The prototypes for the mathematical functions are in [.filename]#math.h#. If you include this file, the compiler will be able to find the prototype and it will stop doing strange things to your calculation! [.programlisting] .... #include #include int main() { ... .... After recompiling it as you did before, run it: [source,bash] .... % ./a.out 2.1 ^ 6 = 85.766121 .... If you are using any of the mathematical functions, _always_ include [.filename]#math.h# and remember to link in the math library. ==== I compiled a file called foobar.c and I cannot find an executable called foobar. Where has it gone? Remember, `cc` will call the executable [.filename]#a.out# unless you tell it differently. Use the `-o _filename_` option: [source,bash] .... % cc -o foobar foobar.c .... ==== OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it? Unlike MS-DOS(R), UNIX(R) does not look in the current directory when it is trying to find out which executable you want it to run, unless you tell it to. Type `./foobar`, which means "run the file called [.filename]#foobar# in the current directory." === I called my executable test, but nothing happens when I run it. What is going on? Most UNIX(R) systems have a program called `test` in [.filename]#/usr/bin# and the shell is picking that one up before it gets to checking the current directory. Either type: [source,bash] .... % ./test .... or choose a better name for your program! ==== I compiled my program and it seemed to run all right at first, then there was an error and it said something about core dumped. What does that mean? The name _core dump_ dates back to the very early days of UNIX(R), when the machines used core memory for storing data. Basically, if the program failed under certain conditions, the system would write the contents of core memory to disk in a file called [.filename]#core#, which the programmer could then pore over to find out what went wrong. ==== Fascinating stuff, but what I am supposed to do now? Use a debugger to analyze the core (see <>). ==== When my program dumped core, it said something about a segmentation fault. What is that? This basically means that your program tried to perform some sort of illegal operation on memory; UNIX(R) is designed to protect the operating system and other programs from rogue programs. Common causes for this are: * Trying to write to a NULL pointer, eg + [.programlisting] .... char *foo = NULL; strcpy(foo, "bang!"); .... * Using a pointer that has not been initialized, eg + [.programlisting] .... char *foo; strcpy(foo, "bang!"); .... + The pointer will have some random value that, with luck, will point into an area of memory that is not available to your program and the kernel will kill your program before it can do any damage. If you are unlucky, it will point somewhere inside your own program and corrupt one of your data structures, causing the program to fail mysteriously. * Trying to access past the end of an array, eg + [.programlisting] .... int bar[20]; bar[27] = 6; .... * Trying to store something in read-only memory, eg + [.programlisting] .... char *foo = "My string"; strcpy(foo, "bang!"); .... + UNIX(R) compilers often put string literals like `"My string"` into read-only areas of memory. * Doing naughty things with `malloc()` and `free()`, eg + [.programlisting] .... char bar[80]; free(bar); .... + or + [.programlisting] .... char *foo = malloc(27); free(foo); free(foo); .... Making one of these mistakes will not always lead to an error, but they are always bad practice. Some systems and compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try them on an another. ==== Sometimes when I get a core dump it says bus error. It says in my UNIX(R) book that this means a hardware problem, but the computer still seems to be working. Is this true? No, fortunately not (unless of course you really do have a hardware problem...). This is usually another way of saying that you accessed memory in a way you should not have. ==== This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. Can I do this, or do I have to wait until there is an error? Yes, just go to another console or xterm, do [source,bash] .... % ps .... to find out the process ID of your program, and do [source,bash] .... % kill -ABRT pid .... where `_pid_` is the process ID you looked up. This is useful if your program has got stuck in an infinite loop, for instance. If your program happens to trap SIGABRT, there are several other signals which have a similar effect. Alternatively, you can create a core dump from inside your program, by calling the `abort()` function. See the manual page of man:abort[3] to learn more. If you want to create a core dump from outside your program, but do not want the process to terminate, you can use the `gcore` program. See the manual page of man:gcore[1] for more information. [[tools-make]] == Make === What is `make`? When you are working on a simple program with only one or two source files, typing in [source,bash] .... % cc file1.c file2.c .... is not too bad, but it quickly becomes very tedious when there are several files-and it can take a while to compile, too. One way to get around this is to use object files and only recompile the source file if the source code has changed. So we could have something like: [source,bash] .... % cc file1.o file2.o … file37.c … .... if we had changed [.filename]#file37.c#, but not any of the others, since the last time we compiled. This may speed up the compilation quite a bit, but does not solve the typing problem. Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it very inefficient on a large project. What happens if we have hundreds of source files lying about? What if we are working in a team with other people who forget to tell us when they have changed one of their source files that we use? Perhaps we could put the two solutions together and write something like a shell script that would contain some kind of magic rule saying when a source file needs compiling. Now all we need now is a program that can understand these rules, as it is a bit too complicated for the shell. This program is called `make`. It reads in a file, called a _makefile_, that tells it how different files depend on each other, and works out which files need to be re-compiled and which ones do not. For example, a rule could say something like "if [.filename]#fromboz.o# is older than [.filename]#fromboz.c#, that means someone must have changed [.filename]#fromboz.c#, so it needs to be re-compiled." The makefile also has rules telling make _how_ to re-compile the source file, making it a much more powerful tool. Makefiles are typically kept in the same directory as the source they apply to, and can be called [.filename]#makefile#, [.filename]#Makefile# or [.filename]#MAKEFILE#. Most programmers use the name [.filename]#Makefile#, as this puts it near the top of a directory listing, where it can easily be seen.footnote:[They do not use the MAKEFILE form as block capitals are often used for documentation files like README.] === Example of Using `make` Here is a very simple make file: [.programlisting] .... foo: foo.c cc -o foo foo.c .... It consists of two lines, a dependency line and a creation line. The dependency line here consists of the name of the program (known as the _target_), followed by a colon, then whitespace, then the name of the source file. When `make` reads this line, it looks to see if [.filename]#foo# exists; if it exists, it compares the time [.filename]#foo# was last modified to the time [.filename]#foo.c# was last modified. If [.filename]#foo# does not exist, or is older than [.filename]#foo.c#, it then looks at the creation line to find out what to do. In other words, this is the rule for working out when [.filename]#foo.c# needs to be re-compiled. The creation line starts with a tab (press kbd:[tab]) and then the command you would type to create [.filename]#foo# if you were doing it at a command prompt. If [.filename]#foo# is out of date, or does not exist, `make` then executes this command to create it. In other words, this is the rule which tells make how to re-compile [.filename]#foo.c#. So, when you type `make`, it will make sure that [.filename]#foo# is up to date with respect to your latest changes to [.filename]#foo.c#. This principle can be extended to [.filename]#Makefile#'s with hundreds of targets-in fact, on FreeBSD, it is possible to compile the entire operating system just by typing `make world` in the appropriate directory! Another useful property of makefiles is that the targets do not have to be programs. For instance, we could have a make file that looks like this: [.programlisting] .... foo: foo.c cc -o foo foo.c install: cp foo /home/me .... We can tell make which target we want to make by typing: [source,bash] .... % make target .... `make` will then only look at that target and ignore any others. For example, if we type `make foo` with the makefile above, make will ignore the `install` target. If we just type `make` on its own, make will always look at the first target and then stop without looking at any others. So if we typed `make` here, it will just go to the `foo` target, re-compile [.filename]#foo# if necessary, and then stop without going on to the `install` target. Notice that the `install` target does not actually depend on anything! This means that the command on the following line is always executed when we try to make that target by typing `make install`. In this case, it will copy [.filename]#foo# into the user's home directory. This is often used by application makefiles, so that the application can be installed in the correct directory when it has been correctly compiled. This is a slightly confusing subject to try to explain. If you do not quite understand how `make` works, the best thing to do is to write a simple program like "hello world" and a make file like the one above and experiment. Then progress to using more than one source file, or having the source file include a header file. `touch` is very useful here-it changes the date on a file without you having to edit it. === Make and include-files C code often starts with a list of files to include, for example stdio.h. Some of these files are system-include files, some of them are from the project you are now working on: [.programlisting] .... #include #include "foo.h" int main(.... .... To make sure that this file is recompiled the moment [.filename]#foo.h# is changed, you have to add it in your [.filename]#Makefile#: [.programlisting] .... foo: foo.c foo.h .... The moment your project is getting bigger and you have more and more own include-files to maintain, it will be a pain to keep track of all include files and the files which are depending on it. If you change an include-file but forget to recompile all the files which are depending on it, the results will be devastating. `clang` has an option to analyze your files and to produce a list of include-files and their dependencies: `-MM`. If you add this to your Makefile: [.programlisting] .... depend: cc -E -MM *.c > .depend .... and run `make depend`, the file [.filename]#.depend# will appear with a list of object-files, C-files and the include-files: [.programlisting] .... foo.o: foo.c foo.h .... If you change [.filename]#foo.h#, next time you run `make` all files depending on [.filename]#foo.h# will be recompiled. Do not forget to run `make depend` each time you add an include-file to one of your files. === FreeBSD Makefiles Makefiles can be rather complicated to write. Fortunately, BSD-based systems like FreeBSD come with some very powerful ones as part of the system. One very good example of this is the FreeBSD ports system. Here is the essential part of a typical ports [.filename]#Makefile#: [.programlisting] .... MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz .include .... Now, if we go to the directory for this port and type `make`, the following happens: [.procedure] . A check is made to see if the source code for this port is already on the system. . If it is not, an FTP connection to the URL in MASTER_SITES is set up to download the source. . The checksum for the source is calculated and compared it with one for a known, good, copy of the source. This is to make sure that the source was not corrupted while in transit. . Any changes required to make the source work on FreeBSD are applied-this is known as _patching_. . Any special configuration needed for the source is done. (Many UNIX(R) program distributions try to work out which version of UNIX(R) they are being compiled on and which optional UNIX(R) features are present-this is where they are given the information in the FreeBSD ports scenario). . The source code for the program is compiled. In effect, we change to the directory where the source was unpacked and do `make`-the program's own make file has the necessary information to build the program. . We now have a compiled version of the program. If we wish, we can test it now; when we feel confident about the program, we can type `make install`. This will cause the program and any supporting files it needs to be copied into the correct location; an entry is also made into a `package database`, so that the port can easily be uninstalled later if we change our mind about it. Now I think you will agree that is rather impressive for a four line script! The secret lies in the last line, which tells `make` to look in the system makefile called [.filename]#bsd.port.mk#. It is easy to overlook this line, but this is where all the clever stuff comes from-someone has written a makefile that tells `make` to do all the things above (plus a couple of other things I did not mention, including handling any errors that may occur) and anyone can get access to that just by putting a single line in their own make file! -If you want to have a look at these system makefiles, they are in [.filename]#/usr/shared/mk#, but it is probably best to wait until you have had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) +If you want to have a look at these system makefiles, they are in [.filename]#/usr/share/mk#, but it is probably best to wait until you have had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you have a flask of strong coffee handy!) === More Advanced Uses of `make` `Make` is a very powerful tool, and can do much more than the simple example above shows. Unfortunately, there are several different versions of `make`, and they all differ considerably. The best way to learn what they can do is probably to read the documentation-hopefully this introduction will have given you a base from which you can do this. -The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in [.filename]#/usr/shared/doc/psd/12.make#. To view it, do +The version of make that comes with FreeBSD is the Berkeley make; there is a tutorial for it in [.filename]#/usr/share/doc/psd/12.make#. To view it, do [source,bash] .... % zmore paper.ascii.gz .... in that directory. Many applications in the ports use GNU make, which has a very good set of "info" pages. If you have installed any of these ports, GNU make will automatically have been installed as `gmake`. It is also available as a port and package in its own right. To view the info pages for GNU make, you will have to edit [.filename]#dir# in the [.filename]#/usr/local/info# directory to add an entry for it. This involves adding a line like [.programlisting] .... * Make: (make). The GNU Make utility. .... to the file. Once you have done this, you can type `info` and then select [.guimenuitem]#make# from the menu (or in Emacs, do `C-h i`). [[debugging]] == Debugging === Introduction to Available Debuggers Using a debugger allows running the program under more controlled circumstances. Typically, it is possible to step through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a certain point and then stop, and so on. It is also possible to attach to a program that is already running, or load a core file to investigate why the program crashed. It is even possible to debug the kernel, though that is a little trickier than the user applications we will be discussing in this section. This section is intended to be a quick introduction to using debuggers and does not cover specialized topics such as debugging the kernel. For more information about that, refer to <>. The standard debugger supplied with FreeBSD {rel121-current} is called `lldb` (LLVM debugger). As it is part of the standard installation for that release, there is no need to do anything special to use it. It has good command help, accessible via the `help` command, as well as https://lldb.llvm.org/[a web tutorial and documentation]. [NOTE] ==== The `lldb` command is available for FreeBSD {rel113-current} link:{handbook}#ports-using/[from ports or packages] as package:devel/llvm[]. This will install the default version of lldb (currently 9.0). ==== The other debugger available with FreeBSD is called `gdb` (GNU debugger). Unlike lldb, it is not installed by default on FreeBSD {rel121-current}; to use it, link:{handbook}#ports-using/[install] package:devel/gdb[] from ports or packages. The version installed by default on FreeBSD {rel113-current} is old; instead, install package:devel/gdb[] there as well. It has quite good on-line help, as well as a set of info pages. Which one to use is largely a matter of taste. If familiar with one only, use that one. People familiar with neither or both but wanting to use one from inside Emacs will need to use `gdb` as `lldb` is unsupported by Emacs. Otherwise, try both and see which one you prefer. === Using lldb ==== Starting lldb Start up lldb by typing [source,bash] .... % lldb -- progname .... ==== Running a Program with lldb Compile the program with `-g` to get the most out of using `lldb`. It will work without, but will only display the name of the function currently running, instead of the source code. If it displays a line like: [source,bash] .... Breakpoint 1: where = temp`main, address = … .... (without an indication of source code filename and line number) when setting a breakpoint, this means that the program was not compiled with `-g`. [TIP] ==== Most `lldb` commands have shorter forms that can be used instead. The longer forms are used here for clarity. ==== At the `lldb` prompt, type `breakpoint set -n main`. This will tell the debugger not to display the preliminary set-up code in the program being run and to stop execution at the beginning of the program's code. Now type `process launch` to actually start the program- it will start at the beginning of the set-up code and then get stopped by the debugger when it calls `main()`. To step through the program a line at a time, type `thread step-over`. When the program gets to a function call, step into it by typing `thread step-in`. Once in a function call, return from it by typing `thread step-out` or use `up` and `down` to take a quick look at the caller. Here is a simple example of how to spot a mistake in a program with `lldb`. This is our program (with a deliberate mistake): [.programlisting] .... #include int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } .... This program sets i to be `5` and passes it to a function `bazz()` which prints out the number we gave it. Compiling and running the program displays [source,bash] .... % cc -g -o temp temp.c % ./temp This is my program anint = -5360 .... That is not what was expected! Time to see what is going on! [source,bash] .... % lldb -- temp (lldb) target create "temp" Current executable set to 'temp' (x86_64). (lldb) breakpoint set -n main Skip the set-up code Breakpoint 1: where = temp`main + 15 at temp.c:8:2, address = 0x00000000002012ef lldb puts breakpoint at main() (lldb) process launch Run as far as main() Process 9992 launching Process 9992 launched: '/home/pauamma/tmp/temp' (x86_64) Program starts running Process 9992 stopped * thread #1, name = 'temp', stop reason = breakpoint 1.1 lldb stops at main() frame #0: 0x00000000002012ef temp`main at temp.c:8:2 5 main() { 6 int i; 7 -> 8 printf("This is my program\n"); Indicates the line where it stopped 9 bazz(i); 10 return 0; 11 } (lldb) thread step-over Go to next line This is my program Program prints out Process 9992 stopped * thread #1, name = 'temp', stop reason = step over frame #0: 0x0000000000201300 temp`main at temp.c:9:7 6 int i; 7 8 printf("This is my program\n"); -> 9 bazz(i); 10 return 0; 11 } 12 (lldb) thread step-in step into bazz() Process 9992 stopped * thread #1, name = 'temp', stop reason = step in frame #0: 0x000000000020132b temp`bazz(anint=-5360) at temp.c:14:29 lldb displays stack frame 11 } 12 13 int bazz(int anint) { -> 14 printf("You gave me %d\n", anint); 15 return anint; 16 } (lldb) .... Hang on a minute! How did anint get to be `-5360`? Was it not set to `5` in `main()`? Let us move up to `main()` and have a look. [source,bash] .... (lldb) up Move up call stack frame #1: 0x000000000020130b temp`main at temp.c:9:2 lldb displays stack frame 6 int i; 7 8 printf("This is my program\n"); -> 9 bazz(i); 10 return 0; 11 } 12 (lldb) frame variable i Show us the value of i (int) i = -5360 lldb displays -5360 .... Oh dear! Looking at the code, we forgot to initialize i. We meant to put [.programlisting] .... ... main() { int i; i = 5; printf("This is my program\n"); ... .... but we left the `i=5;` line out. As we did not initialize i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be `-5360`. [NOTE] ==== The `lldb` command displays the stack frame every time we go into or out of a function, even if we are using `up` and `down` to move around the call stack. This shows the name of the function and the values of its arguments, which helps us keep track of where we are and what is going on. (The stack is a storage area where the program stores information about the arguments passed to functions and where to go when it returns from a function call.) ==== ==== Examining a Core File with lldb A core file is basically a file which contains the complete state of the process when it crashed. In "the good old days", programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called [.filename]#progname.core# instead of just [.filename]#core#, to make it clearer which program a core file belongs to. To examine a core file, specify the name of the core file in addition to the program itself. Instead of starting up `lldb` in the usual way, type `lldb -c _progname_.core -- _progname_` The debugger will display something like this: [source,bash,subs="verbatim,quotes"] .... % lldb -c [.filename]#progname.core# -- [.filename]#progname# (lldb) target create "[.filename]#progname#" --core "[.filename]#progname#.core" Core file '/home/pauamma/tmp/[.filename]#progname.core#' (x86_64) was loaded. (lldb) .... In this case, the program was called [.filename]#progname#, so the core file is called [.filename]#progname.core#. The debugger does not display why the program crashed or where. For this, use `thread backtrace all`. This will also show how the function where the program dumped core was called. [source,bash,subs="verbatim,quotes"] .... (lldb) thread backtrace all * thread #1, name = 'progname', stop reason = signal SIGSEGV * frame #0: 0x0000000000201347 progname`bazz(anint=5) at temp2.c:17:10 frame #1: 0x0000000000201312 progname`main at temp2.c:10:2 frame #2: 0x000000000020110f progname`_start(ap=, cleanup=) at crt1.c:76:7 (lldb) .... `SIGSEGV` indicates that the program tried to access memory (run code or read/write data usually) at a location that does not belong to it, but does not give any specifics. For that, look at the source code at line 10 of file temp2.c, in `bazz()`. The backtrace also says that in this case, `bazz()` was called from `main()`. ==== Attaching to a Running Program with lldb One of the neatest features about `lldb` is that it can attach to a program that is already running. Of course, that requires sufficient permissions to do so. A common problem is stepping through a program that forks and wanting to trace the child, but the debugger will only trace the parent. To do that, start up another `lldb`, use `ps` to find the process ID for the child, and do [source,bash] .... (lldb) process attach -p pid .... in `lldb`, and then debug as usual. For that to work well, the code that calls `fork` to create the child needs to do something like the following (courtesy of the `gdb` info pages): [.programlisting] .... ... if ((pid = fork()) < 0) /* _Always_ check this */ error(); else if (pid == 0) { /* child */ int PauseMode = 1; while (PauseMode) sleep(10); /* Wait until someone attaches to us */ ... } else { /* parent */ ... .... Now all that is needed is to attach to the child, set PauseMode to `0` with `expr PauseMode = 0` and wait for the `sleep()` call to return. === Remote Debugging Using LLDB [NOTE] ==== The described functionality is available starting with LLDB version 12.0.0. Users of FreeBSD releases containing an earlier LLDB version may wish to use the snapshot available in link:{handbook}#ports-using/[ports or packages], as package:devel/llvm-devel[]. ==== Starting with LLDB 12.0.0, remote debugging is supported on FreeBSD. This means that `lldb-server` can be started to debug a program on one host, while the interactive `lldb` client connects to it from another one. To launch a new process to be debugged remotely, run `lldb-server` on the remote server by typing [source,bash] .... % lldb-server g host:port -- progname .... The process will be stopped immediately after launching, and `lldb-server` will wait for the client to connect. Start `lldb` locally and type the following command to connect to the remote server: [source,bash] .... (lldb) gdb-remote host:port .... `lldb-server` can also attach to a running process. To do that, type the following on the remote server: [source,bash] .... % lldb-server g host:port --attach pid-or-name .... === Using gdb ==== Starting gdb Start up gdb by typing [source,bash] .... % gdb progname .... although many people prefer to run it inside Emacs. To do this, type: [source,bash] .... M-x gdb RET progname RET .... Finally, for those finding its text-based command-prompt style off-putting, there is a graphical front-end for it (package:devel/xxgdb[]) in the Ports Collection. ==== Running a Program with gdb Compile the program with `-g` to get the most out of using `gdb`. It will work without, but will only display the name of the function currently running, instead of the source code. A line like: [source,bash] .... ... (no debugging symbols found) ... .... when `gdb` starts up means that the program was not compiled with `-g`. At the `gdb` prompt, type `break main`. This will tell the debugger to skip the preliminary set-up code in the program being run and to stop execution at the beginning of the program's code. Now type `run` to start the program- it will start at the beginning of the set-up code and then get stopped by the debugger when it calls `main()`. To step through the program a line at a time, press `n`. When at a function call, step into it by pressing `s`. Once in a function call, return from it by pressing `f`, or use `up` and `down` to take a quick look at the caller. Here is a simple example of how to spot a mistake in a program with `gdb`. This is our program (with a deliberate mistake): [.programlisting] .... #include int bazz(int anint); main() { int i; printf("This is my program\n"); bazz(i); return 0; } int bazz(int anint) { printf("You gave me %d\n", anint); return anint; } .... This program sets i to be `5` and passes it to a function `bazz()` which prints out the number we gave it. Compiling and running the program displays [source,bash] .... % cc -g -o temp temp.c % ./temp This is my program anint = 4231 .... That was not what we expected! Time to see what is going on! [source,bash] .... % gdb temp GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) break main Skip the set-up code Breakpoint 1 at 0x160f: file temp.c, line 9. gdb puts breakpoint at main() (gdb) run Run as far as main() Starting program: /home/james/tmp/temp Program starts running Breakpoint 1, main () at temp.c:9 gdb stops at main() (gdb) n Go to next line This is my program Program prints out (gdb) s step into bazz() bazz (anint=4231) at temp.c:17 gdb displays stack frame (gdb) .... Hang on a minute! How did anint get to be `4231`? Was it not set to `5` in `main()`? Let us move up to `main()` and have a look. [source,bash] .... (gdb) up Move up call stack #1 0x1625 in main () at temp.c:11 gdb displays stack frame (gdb) p i Show us the value of i $1 = 4231 gdb displays 4231 .... Oh dear! Looking at the code, we forgot to initialize i. We meant to put [.programlisting] .... ... main() { int i; i = 5; printf("This is my program\n"); ... .... but we left the `i=5;` line out. As we did not initialize i, it had whatever number happened to be in that area of memory when the program ran, which in this case happened to be `4231`. [NOTE] ==== The `gdb` command displays the stack frame every time we go into or out of a function, even if we are using `up` and `down` to move around the call stack. This shows the name of the function and the values of its arguments, which helps us keep track of where we are and what is going on. (The stack is a storage area where the program stores information about the arguments passed to functions and where to go when it returns from a function call.) ==== ==== Examining a Core File with gdb A core file is basically a file which contains the complete state of the process when it crashed. In "the good old days", programmers had to print out hex listings of core files and sweat over machine code manuals, but now life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, a core file is called [.filename]#progname.core# instead of just [.filename]#core#, to make it clearer which program a core file belongs to. To examine a core file, start up `gdb` in the usual way. Instead of typing `break` or `run`, type [source,bash] .... (gdb) core progname.core .... If the core file is not in the current directory, type `dir /path/to/core/file` first. The debugger should display something like this: [source,bash,subs="verbatim,quotes"] .... % gdb [.filename]#progname# GDB is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for GDB; type "show warranty" for details. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. (gdb) core [.filename]#progname.core# Core was generated by `[.filename]#progname#'. Program terminated with signal 11, Segmentation fault. Cannot access memory at address 0x7020796d. #0 0x164a in bazz (anint=0x5) at temp.c:17 (gdb) .... In this case, the program was called [.filename]#progname#, so the core file is called [.filename]#progname.core#. We can see that the program crashed due to trying to access an area in memory that was not available to it in a function called `bazz`. Sometimes it is useful to be able to see how a function was called, as the problem could have occurred a long way up the call stack in a complex program. `bt` causes `gdb` to print out a back-trace of the call stack: [source,bash] .... (gdb) bt #0 0x164a in bazz (anint=0x5) at temp.c:17 #1 0xefbfd888 in end () #2 0x162c in main () at temp.c:11 (gdb) .... The `end()` function is called when a program crashes; in this case, the `bazz()` function was called from `main()`. ==== Attaching to a Running Program with gdb One of the neatest features about `gdb` is that it can attach to a program that is already running. Of course, that requires sufficient permissions to do so. A common problem is stepping through a program that forks and wanting to trace the child, but the debugger will only trace the parent. To do that, start up another `gdb`, use `ps` to find the process ID for the child, and do [source,bash] .... (gdb) attach pid .... in `gdb`, and then debug as usual. For that to work well, the code that calls `fork` to create the child needs to do something like the following (courtesy of the `gdb` info pages): [.programlisting] .... ... if ((pid = fork()) < 0) /* _Always_ check this */ error(); else if (pid == 0) { /* child */ int PauseMode = 1; while (PauseMode) sleep(10); /* Wait until someone attaches to us */ ... } else { /* parent */ ... .... Now all that is needed is to attach to the child, set PauseMode to `0`, and wait for the `sleep()` call to return! [[emacs]] == Using Emacs as a Development Environment === Emacs Emacs is a highly customizable editor-indeed, it has been customized to the point where it is more like an operating system than an editor! Many developers and sysadmins do in fact spend practically all their time working inside Emacs, leaving it only to log out. It is impossible even to summarize everything Emacs can do here, but here are some of the features of interest to developers: * Very powerful editor, allowing search-and-replace on both strings and regular expressions (patterns), jumping to start/end of block expression, etc, etc. * Pull-down menus and online help. * Language-dependent syntax highlighting and indentation. * Completely customizable. * You can compile and debug programs within Emacs. * On a compilation error, you can jump to the offending line of source code. * Friendly-ish front-end to the `info` program used for reading GNU hypertext documentation, including the documentation on Emacs itself. * Friendly front-end to `gdb`, allowing you to look at the source code as you step through your program. And doubtless many more that have been overlooked. Emacs can be installed on FreeBSD using the package:editors/emacs[] port. Once it is installed, start it up and do `C-h t` to read an Emacs tutorial-that means hold down kbd:[control], press kbd:[h], let go of kbd:[control], and then press kbd:[t]. (Alternatively, you can use the mouse to select [.guimenuitem]#Emacs Tutorial# from the menu:Help[] menu.) Although Emacs does have menus, it is well worth learning the key bindings, as it is much quicker when you are editing something to press a couple of keys than to try to find the mouse and then click on the right place. And, when you are talking to seasoned Emacs users, you will find they often casually throw around expressions like "`M-x replace-s RET foo RET bar RET`" so it is useful to know what they mean. And in any case, Emacs has far too many useful functions for them to all fit on the menu bars. Fortunately, it is quite easy to pick up the key-bindings, as they are displayed next to the menu item. My advice is to use the menu item for, say, opening a file until you understand how it works and feel confident with it, then try doing C-x C-f. When you are happy with that, move on to another menu command. If you cannot remember what a particular combination of keys does, select [.guimenuitem]#Describe Key# from the menu:Help[] menu and type it in-Emacs will tell you what it does. You can also use the [.guimenuitem]#Command Apropos# menu item to find out all the commands which contain a particular word in them, with the key binding next to it. By the way, the expression above means hold down the kbd:[Meta] key, press kbd:[x], release the kbd:[Meta] key, type `replace-s` (short for `replace-string`-another feature of Emacs is that you can abbreviate commands), press the kbd:[return] key, type `foo` (the string you want replaced), press the kbd:[return] key, type bar (the string you want to replace `foo` with) and press kbd:[return] again. Emacs will then do the search-and-replace operation you have just requested. If you are wondering what on earth kbd:[Meta] is, it is a special key that many UNIX(R) workstations have. Unfortunately, PC's do not have one, so it is usually kbd:[alt] (or if you are unlucky, the kbd:[escape] key). Oh, and to get out of Emacs, do `C-x C-c` (that means hold down the kbd:[control] key, press kbd:[x], press kbd:[c] and release the kbd:[control] key). If you have any unsaved files open, Emacs will ask you if you want to save them. (Ignore the bit in the documentation where it says `C-z` is the usual way to leave Emacs-that leaves Emacs hanging around in the background, and is only really useful if you are on a system which does not have virtual terminals). === Configuring Emacs Emacs does many wonderful things; some of them are built in, some of them need to be configured. Instead of using a proprietary macro language for configuration, Emacs uses a version of Lisp specially adapted for editors, known as Emacs Lisp. Working with Emacs Lisp can be quite helpful if you want to go on and learn something like Common Lisp. Emacs Lisp has many features of Common Lisp, although it is considerably smaller (and thus easier to master). The best way to learn Emacs Lisp is to download the link:ftp://ftp.gnu.org/old-gnu/emacs/elisp-manual-19-2.4.tar.gz[Emacs Tutorial] However, there is no need to actually know any Lisp to get started with configuring Emacs, as I have included a sample [.filename]#.emacs#, which should be enough to get you started. Just copy it into your home directory and restart Emacs if it is already running; it will read the commands from the file and (hopefully) give you a useful basic setup. === A Sample [.filename]#.emacs# Unfortunately, there is far too much here to explain it in detail; however there are one or two points worth mentioning. * Everything beginning with a `;` is a comment and is ignored by Emacs. * In the first line, the `-*- Emacs-Lisp -*-` is so that we can edit [.filename]#.emacs# itself within Emacs and get all the fancy features for editing Emacs Lisp. Emacs usually tries to guess this based on the filename, and may not get it right for [.filename]#.emacs#. * The kbd:[tab] key is bound to an indentation function in some modes, so when you press the tab key, it will indent the current line of code. If you want to put a tab character in whatever you are writing, hold the kbd:[control] key down while you are pressing the kbd:[tab] key. * This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by guessing the language from the filename. * Emacs already has a pre-defined function called `next-error`. In a compilation output window, this allows you to move from one compilation error to the next by doing `M-n`; we define a complementary function, `previous-error`, that allows you to go to a previous error by doing `M-p`. The nicest feature of all is that `C-c C-c` will open up the source file in which the error occurred and jump to the appropriate line. * We enable Emacs's ability to act as a server, so that if you are doing something outside Emacs and you want to edit a file, you can just type in + [source,bash] .... % emacsclient filename .... + and then you can edit the file in your Emacs!footnote:[Many Emacs users set their EDITOR environment to emacsclient so this happens every time they need to edit a file.] .A Sample [.filename]#.emacs# ==== [.programlisting] .... ;; -*-Emacs-Lisp-*- ;; This file is designed to be re-evaled; use the variable first-time ;; to avoid any problems with this. (defvar first-time t "Flag signifying this is the first time that .emacs has been evaled") ;; Meta (global-set-key "\M- " 'set-mark-command) (global-set-key "\M-\C-h" 'backward-kill-word) (global-set-key "\M-\C-r" 'query-replace) (global-set-key "\M-r" 'replace-string) (global-set-key "\M-g" 'goto-line) (global-set-key "\M-h" 'help-command) ;; Function keys (global-set-key [f1] 'manual-entry) (global-set-key [f2] 'info) (global-set-key [f3] 'repeat-complex-command) (global-set-key [f4] 'advertised-undo) (global-set-key [f5] 'eval-current-buffer) (global-set-key [f6] 'buffer-menu) (global-set-key [f7] 'other-window) (global-set-key [f8] 'find-file) (global-set-key [f9] 'save-buffer) (global-set-key [f10] 'next-error) (global-set-key [f11] 'compile) (global-set-key [f12] 'grep) (global-set-key [C-f1] 'compile) (global-set-key [C-f2] 'grep) (global-set-key [C-f3] 'next-error) (global-set-key [C-f4] 'previous-error) (global-set-key [C-f5] 'display-faces) (global-set-key [C-f8] 'dired) (global-set-key [C-f10] 'kill-compilation) ;; Keypad bindings (global-set-key [up] "\C-p") (global-set-key [down] "\C-n") (global-set-key [left] "\C-b") (global-set-key [right] "\C-f") (global-set-key [home] "\C-a") (global-set-key [end] "\C-e") (global-set-key [prior] "\M-v") (global-set-key [next] "\C-v") (global-set-key [C-up] "\M-\C-b") (global-set-key [C-down] "\M-\C-f") (global-set-key [C-left] "\M-b") (global-set-key [C-right] "\M-f") (global-set-key [C-home] "\M-<") (global-set-key [C-end] "\M->") (global-set-key [C-prior] "\M-<") (global-set-key [C-next] "\M->") ;; Mouse (global-set-key [mouse-3] 'imenu) ;; Misc (global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab. (setq backup-by-copying-when-mismatch t) ;; Treat 'y' or as yes, 'n' as no. (fset 'yes-or-no-p 'y-or-n-p) (define-key query-replace-map [return] 'act) (define-key query-replace-map [?\C-m] 'act) ;; Load packages (require 'desktop) (require 'tar-mode) ;; Pretty diff mode (autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t) (autoload 'ediff-files-remote "ediff" "Intelligent Emacs interface to diff") (if first-time (setq auto-mode-alist (append '(("\\.cpp$" . c++-mode) ("\\.hpp$" . c++-mode) ("\\.lsp$" . lisp-mode) ("\\.scm$" . scheme-mode) ("\\.pl$" . perl-mode) ) auto-mode-alist))) ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") (defvar font-lock-mode-keyword-alist '((c++-c-mode . c-font-lock-keywords) (perl-mode . perl-font-lock-keywords)) "Associations between modes and keywords") (defun font-lock-auto-mode-select () "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list" (if (memq major-mode font-lock-auto-mode-list) (progn (font-lock-mode t)) ) ) (global-set-key [M-f1] 'font-lock-fontify-buffer) ;; New dabbrev stuff ;(require 'new-dabbrev) (setq dabbrev-always-check-other-buffers t) (setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_") (add-hook 'emacs-lisp-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'c-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) nil) (set (make-local-variable 'dabbrev-case-replace) nil))) (add-hook 'text-mode-hook '(lambda () (set (make-local-variable 'dabbrev-case-fold-search) t) (set (make-local-variable 'dabbrev-case-replace) t))) ;; C++ and C mode... (defun my-c++-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c++-mode-map "\C-ce" 'c-comment-edit) (setq c++-auto-hungry-initial-state 'none) (setq c++-delete-function 'backward-delete-char) (setq c++-tab-always-indent t) (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c++-empty-arglist-indent 4)) (defun my-c-mode-hook () (setq tab-width 4) (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key c-mode-map "\C-ce" 'c-comment-edit) (setq c-auto-hungry-initial-state 'none) (setq c-delete-function 'backward-delete-char) (setq c-tab-always-indent t) ;; BSD-ish indentation style (setq c-indent-level 4) (setq c-continued-statement-offset 4) (setq c-brace-offset -4) (setq c-argdecl-indent 0) (setq c-label-offset -4)) ;; Perl mode (defun my-perl-mode-hook () (setq tab-width 4) (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent) (setq perl-indent-level 4) (setq perl-continued-statement-offset 4)) ;; Scheme mode... (defun my-scheme-mode-hook () (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent)) ;; Emacs-Lisp mode... (defun my-lisp-mode-hook () (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent) (define-key lisp-mode-map "\C-i" 'lisp-indent-line) (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp)) ;; Add all of the hooks... (add-hook 'c++-mode-hook 'my-c++-mode-hook) (add-hook 'c-mode-hook 'my-c-mode-hook) (add-hook 'scheme-mode-hook 'my-scheme-mode-hook) (add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'lisp-mode-hook 'my-lisp-mode-hook) (add-hook 'perl-mode-hook 'my-perl-mode-hook) ;; Complement to next-error (defun previous-error (n) "Visit previous compilation error message and corresponding source code." (interactive "p") (next-error (- n))) ;; Misc... (transient-mark-mode 1) (setq mark-even-if-inactive t) (setq visible-bell nil) (setq next-line-add-newlines nil) (setq compile-command "make") (setq suggest-key-bindings nil) (put 'eval-expression 'disabled nil) (put 'narrow-to-region 'disabled nil) (put 'set-goal-column 'disabled nil) (if (>= emacs-major-version 21) (setq show-trailing-whitespace t)) ;; Elisp archive searching (autoload 'format-lisp-code-directory "lispdir" nil t) (autoload 'lisp-dir-apropos "lispdir" nil t) (autoload 'lisp-dir-retrieve "lispdir" nil t) (autoload 'lisp-dir-verify "lispdir" nil t) ;; Font lock mode (defun my-make-face (face color &optional bold) "Create a face from a color and optionally make it bold" (make-face face) (copy-face 'default face) (set-face-foreground face color) (if bold (make-face-bold face)) ) (if (eq window-system 'x) (progn (my-make-face 'blue "blue") (my-make-face 'red "red") (my-make-face 'green "dark green") (setq font-lock-comment-face 'blue) (setq font-lock-string-face 'bold) (setq font-lock-type-face 'bold) (setq font-lock-keyword-face 'bold) (setq font-lock-function-name-face 'red) (setq font-lock-doc-string-face 'green) (add-hook 'find-file-hooks 'font-lock-auto-mode-select) (setq baud-rate 1000000) (global-set-key "\C-cmm" 'menu-bar-mode) (global-set-key "\C-cms" 'scroll-bar-mode) (global-set-key [backspace] 'backward-delete-char) ; (global-set-key [delete] 'delete-char) (standard-display-european t) (load-library "iso-transl"))) ;; X11 or PC using direct screen writes (if window-system (progn ;; (global-set-key [M-f1] 'hilit-repaint-command) ;; (global-set-key [M-f2] [?\C-u M-f1]) (setq hilit-mode-enable-list '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode scheme-mode) hilit-auto-highlight nil hilit-auto-rehighlight 'visible hilit-inhibit-hooks nil hilit-inhibit-rebinding t) (require 'hilit19) (require 'paren)) (setq baud-rate 2400) ; For slow serial connections ) ;; TTY type terminal (if (and (not window-system) (not (equal system-type 'ms-dos))) (progn (if first-time (progn (keyboard-translate ?\C-h ?\C-?) (keyboard-translate ?\C-? ?\C-h))))) ;; Under UNIX (if (not (equal system-type 'ms-dos)) (progn (if first-time (server-start)))) ;; Add any face changes here (add-hook 'term-setup-hook 'my-term-setup-hook) (defun my-term-setup-hook () (if (eq window-system 'pc) (progn ;; (set-face-background 'default "red") ))) ;; Restore the "desktop" - do this as late as possible (if first-time (progn (desktop-load-default) (desktop-read))) ;; Indicate that this file has been read at least once (setq first-time nil) ;; No need to debug anything now (setq debug-on-error nil) ;; All done (message "All done, %s%s" (user-login-name) ".") .... ==== === Extending the Range of Languages Emacs Understands Now, this is all very well if you only want to program in the languages already catered for in [.filename]#.emacs# (C, C++, Perl, Lisp and Scheme), but what happens if a new language called "whizbang" comes out, full of exciting features? The first thing to do is find out if whizbang comes with any files that tell Emacs about the language. These usually end in [.filename]#.el#, short for "Emacs Lisp". For example, if whizbang is a FreeBSD port, we can locate these files by doing [source,bash] .... % find /usr/ports/lang/whizbang -name "*.el" -print .... and install them by copying them into the Emacs site Lisp directory. On FreeBSD, this is [.filename]#/usr/local/shared/emacs/site-lisp#. So for example, if the output from the find command was [source,bash] .... /usr/ports/lang/whizbang/work/misc/whizbang.el .... we would do [source,bash] .... # cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/shared/emacs/site-lisp .... Next, we need to decide what extension whizbang source files have. Let us say for the sake of argument that they all end in [.filename]#.wiz#. We need to add an entry to our [.filename]#.emacs# to make sure Emacs will be able to use the information in [.filename]#whizbang.el#. Find the auto-mode-alist entry in [.filename]#.emacs# and add a line for whizbang, such as: [.programlisting] .... ... ("\\.lsp$" . lisp-mode) ("\\.wiz$" . whizbang-mode) ("\\.scm$" . scheme-mode) ... .... This means that Emacs will automatically go into `whizbang-mode` when you edit a file ending in [.filename]#.wiz#. Just below this, you will find the font-lock-auto-mode-list entry. Add `whizbang-mode` to it like so: [.programlisting] .... ;; Auto font lock mode (defvar font-lock-auto-mode-list (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode) "List of modes to always start in font-lock-mode") .... This means that Emacs will always enable `font-lock-mode` (ie syntax highlighting) when editing a [.filename]#.wiz# file. And that is all that is needed. If there is anything else you want done automatically when you open up [.filename]#.wiz#, you can add a `whizbang-mode hook` (see `my-scheme-mode-hook` for a simple example that adds `auto-indent`). [[tools-reading]] == Further Reading For information about setting up a development environment for contributing fixes to FreeBSD itself, please see man:development[7]. * Brian Harvey and Matthew Wright _Simply Scheme_ MIT 1994. ISBN 0-262-08226-8 * Randall Schwartz _Learning Perl_ O'Reilly 1993 ISBN 1-56592-042-2 * Patrick Henry Winston and Berthold Klaus Paul Horn _Lisp (3rd Edition)_ Addison-Wesley 1989 ISBN 0-201-08319-1 * Brian W. Kernighan and Rob Pike _The Unix Programming Environment_ Prentice-Hall 1984 ISBN 0-13-937681-X * Brian W. Kernighan and Dennis M. Ritchie _The C Programming Language (2nd Edition)_ Prentice-Hall 1988 ISBN 0-13-110362-8 * Bjarne Stroustrup _The C++ Programming Language_ Addison-Wesley 1991 ISBN 0-201-53992-6 * W. Richard Stevens _Advanced Programming in the Unix Environment_ Addison-Wesley 1992 ISBN 0-201-56317-7 * W. Richard Stevens _Unix Network Programming_ Prentice-Hall 1990 ISBN 0-13-949876-1 diff --git a/documentation/content/en/books/faq/_index.adoc b/documentation/content/en/books/faq/_index.adoc index b3f7f1b99b..48c7675599 100644 --- a/documentation/content/en/books/faq/_index.adoc +++ b/documentation/content/en/books/faq/_index.adoc @@ -1,2642 +1,2642 @@ --- title: Frequently Asked Questions for FreeBSD 11.X and 12.X authors: - author: The FreeBSD Documentation Project copyright: 1995-2020 The FreeBSD Documentation Project releaseinfo: "$FreeBSD$" trademarks: ["freebsd", "ibm", "ieee", "adobe", "intel", "linux", "microsoft", "opengroup", "sun", "netbsd", "general"] --- = Frequently Asked Questions for FreeBSD {rel2-relx} and {rel-relx} :doctype: book :toc: macro :toclevels: 1 :icons: font :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnums: :sectnumlevels: 6 :partnums: :chapter-signifier: Chapter :part-signifier: Part :source-highlighter: rouge :experimental: :skip-front-matter: :rel-numbranch: 3 :rel-head: 13-CURRENT :rel-head-relx: 13.X :rel-head-releng: head/ :rel-relx: 12.X :rel-stable: 12-STABLE :rel-releng: stable/12/ :rel-relengdate: December 2018 :rel2-relx: 11.X :rel2-stable: 11-STABLE :rel2-releng: stable/11/ :rel2-relengdate: October 2016 ifeval::["{backend}" == "html5"] include::shared/mirrors.adoc[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../shared/mirrors.adoc[] include::../../../../shared/authors.adoc[] include::../../../../shared/releases.adoc[] include::../../../../shared/en/mailing-lists.adoc[] include::../../../../shared/en/teams.adoc[] include::../../../../shared/en/urls.adoc[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../shared/mirrors.adoc[] include::../../../../shared/authors.adoc[] include::../../../../shared/releases.adoc[] include::../../../../shared/en/mailing-lists.adoc[] include::../../../../shared/en/teams.adoc[] include::../../../../shared/en/urls.adoc[] endif::[] [.abstract-title] Abstract This is the Frequently Asked Questions (FAQ) for FreeBSD versions {rel-relx} and {rel2-relx}. Every effort has been made to make this FAQ as informative as possible; if you have any suggestions as to how it may be improved, send them to the {freebsd-doc}. The latest version of this document is always available from the link:{faq}[FreeBSD website]. It may also be downloaded as one large link:.[HTML] file with HTTP or as a variety of other formats from the https://download.freebsd.org/ftp/doc/[FreeBSD FTP server]. ''' toc::[] [[introduction]] == Introduction [[what-is-FreeBSD]] === What is FreeBSD? FreeBSD is a modern operating system for desktops, laptops, servers, and embedded systems with support for a large number of https://www.FreeBSD.org/platforms/[platforms]. It is based on U.C. Berkeley's "4.4BSD-Lite" release, with some "4.4BSD-Lite2" enhancements. It is also based indirectly on William Jolitz's port of U.C. Berkeley's "Net/2" to the i386(TM), known as "386BSD", though very little of the 386BSD code remains. FreeBSD is used by companies, Internet Service Providers, researchers, computer professionals, students and home users all over the world in their work, education and recreation. For more detailed information on FreeBSD, refer to the link:{handbook}[FreeBSD Handbook]. [[FreeBSD-goals]] === What is the goal of the FreeBSD Project? The goal of the FreeBSD Project is to provide a stable and fast general purpose operating system that may be used for any purpose without strings attached. [[bsd-license-restrictions]] === Does the FreeBSD license have any restrictions? Yes. Those restrictions do not control how the code is used, but how to treat the FreeBSD Project itself. The license itself is available at https://www.FreeBSD.org/copyright/freebsd-license/[license] and can be summarized like this: * Do not claim that you wrote this. * Do not sue us if it breaks. * Do not remove or modify the license. Many of us have a significant investment in the project and would certainly not mind a little financial compensation now and then, but we definitely do not insist on it. We believe that our first and foremost "mission" is to provide code to any and all comers, and for whatever purpose, so that the code gets the widest possible use and provides the widest possible benefit. This, we believe, is one of the most fundamental goals of Free Software and one that we enthusiastically support. Code in our source tree which falls under the https://www.FreeBSD.org/copyright/COPYING[GNU General Public License (GPL)] or https://www.FreeBSD.org/copyright/COPYING.LIB[GNU Library General Public License (LGPL)] comes with slightly more strings attached, though at least on the side of enforced access rather than the usual opposite. Due to the additional complexities that can evolve in the commercial use of GPL software, we do, however, endeavor to replace such software with submissions under the more relaxed https://www.FreeBSD.org/copyright/freebsd-license/[FreeBSD license] whenever possible. [[replace-current-OS]] === Can FreeBSD replace my current operating system? For most people, yes. But this question is not quite that cut-and-dried. Most people do not actually use an operating system. They use applications. The applications are what really use the operating system. FreeBSD is designed to provide a robust and full-featured environment for applications. It supports a wide variety of web browsers, office suites, email readers, graphics programs, programming environments, network servers, and much more. Most of these applications can be managed through the https://www.FreeBSD.org/ports/[Ports Collection]. If an application is only available on one operating system, that operating system cannot just be replaced. Chances are, there is a very similar application on FreeBSD, however. As a solid office or Internet server or a reliable workstation, FreeBSD will almost certainly do everything you need. Many computer users across the world, including both novices and experienced UNIX(R) administrators, use FreeBSD as their only desktop operating system. Users migrating to FreeBSD from another UNIX(R)-like environment will find FreeBSD to be similar. Windows(R) and Mac OS(R) users may be interested in instead using https://www.ghostbsd.org/[GhostBSD], https://www.midnightbsd.org/[MidnightBSD] or https://www.nomadbsd.org/[NomadBSD] three FreeBSD-based desktop distributions. Non-UNIX(R) users should expect to invest some additional time learning the UNIX(R) way of doing things. This FAQ and the link:{handbook}[FreeBSD Handbook] are excellent places to start. [[why-called-FreeBSD]] === Why is it called FreeBSD? * It may be used free of charge, even by commercial users. * Full source for the operating system is freely available, and the minimum possible restrictions have been placed upon its use, distribution and incorporation into other work (commercial or non-commercial). * Anyone who has an improvement or bug fix is free to submit their code and have it added to the source tree (subject to one or two obvious provisions). It is worth pointing out that the word "free" is being used in two ways here: one meaning "at no cost" and the other meaning "do whatever you like". Apart from one or two things you _cannot_ do with the FreeBSD code, for example pretending you wrote it, you can really do whatever you like with it. [[differences-to-other-bsds]] === What are the differences between FreeBSD and NetBSD, OpenBSD, and other open source BSD operating systems? James Howard wrote a good explanation of the history and differences between the various projects, called https://jameshoward.us/archive/bsd-family-tree/[The BSD Family Tree] which goes a fair way to answering this question. Some of the information is out of date, but the history portion in particular remains accurate. Most of the BSDs share patches and code, even today. All of the BSDs have common ancestry. The design goals of FreeBSD are described in <>, above. The design goals of the other most popular BSDs may be summarized as follows: * OpenBSD aims for operating system security above all else. The OpenBSD team wrote man:ssh[1] and man:pf[4], which have both been ported to FreeBSD. * NetBSD aims to be easily ported to other hardware platforms. * DragonFly BSD is a fork of FreeBSD 4.8 that has since developed many interesting features of its own, including the HAMMER file system and support for user-mode "vkernels". [[latest-version]] === What is the latest version of FreeBSD? At any point in the development of FreeBSD, there can be multiple parallel branches. {rel-relx} releases are made from the {rel-stable} branch, and {rel2-relx} releases are made from the {rel2-stable} branch. Up until the release of 12.0, the {rel2-relx} series was the one known as _-STABLE_. However, as of {rel-head-relx}, the {rel2-relx} branch will be designated for an "extended support" status and receive only fixes for major problems, such as security-related fixes. Releases are made <>. While many people stay more up-to-date with the FreeBSD sources (see the questions on <> and <>) than that, doing so is more of a commitment, as the sources are a moving target. More information on FreeBSD releases can be found on the https://www.FreeBSD.org/releng/#release-build[Release Engineering page] and in man:release[7]. [[current]] === What is _FreeBSD-CURRENT_? link:{handbook}#current[FreeBSD-CURRENT] is the development version of the operating system, which will in due course become the new FreeBSD-STABLE branch. As such, it is really only of interest to developers working on the system and die-hard hobbyists. See the link:{handbook}#current[relevant section] in the link:{handbook}[Handbook] for details on running _-CURRENT_. Users not familiar with FreeBSD should not use FreeBSD-CURRENT. This branch sometimes evolves quite quickly and due to mistake can be un-buildable at times. People that use FreeBSD-CURRENT are expected to be able to analyze, debug, and report problems. [[stable]] === What is the FreeBSD-STABLE concept? _FreeBSD-STABLE_ is the development branch from which major releases are made. Changes go into this branch at a slower pace and with the general assumption that they have first been tested in FreeBSD-CURRENT. However, at any given time, the sources for FreeBSD-STABLE may or may not be suitable for general use, as it may uncover bugs and corner cases that were not yet found in FreeBSD-CURRENT. Users who do not have the resources to perform testing should instead run the most recent release of FreeBSD. _FreeBSD-CURRENT_, on the other hand, has been one unbroken line since 2.0 was released. For more detailed information on branches see "link:{releng}#rel-branch[FreeBSD Release Engineering: Creating the Release Branch]", the status of the branches and the upcoming release schedule can be found on the https://www.FreeBSD.org/releng[Release Engineering Information] page. Version https://download.FreeBSD.org/ftp/releases/amd64/amd64/{rel121-current}-RELEASE/[{rel121-current}] is the latest release from the {rel-stable} branch; it was released in {rel121-current-date}. Version https://download.FreeBSD.org/ftp/releases/amd64/amd64/{rel113-current}-RELEASE/[{rel113-current}] is the latest release from the {rel2-stable} branch; it was released in {rel113-current-date}. [[release-freq]] === When are FreeBSD releases made? The {re} releases a new major version of FreeBSD about every 18 months and a new minor version about every 8 months, on average. Release dates are announced well in advance, so that the people working on the system know when their projects need to be finished and tested. A testing period precedes each release, to ensure that the addition of new features does not compromise the stability of the release. Many users regard this caution as one of the best things about FreeBSD, even though waiting for all the latest goodies to reach _-STABLE_ can be a little frustrating. More information on the release engineering process (including a schedule of upcoming releases) can be found on the https://www.FreeBSD.org/releng/[release engineering] pages on the FreeBSD Web site. For people who need or want a little more excitement, binary snapshots are made weekly as discussed above. [[snapshot-freq]] === When are FreeBSD snapshots made? FreeBSD link:https://www.FreeBSD.org/snapshots/[snapshot] releases are made based on the current state of the _-CURRENT_ and _-STABLE_ branches. The goals behind each snapshot release are: * To test the latest version of the installation software. * To give people who would like to run _-CURRENT_ or _-STABLE_ but who do not have the time or bandwidth to follow it on a day-to-day basis an easy way of bootstrapping it onto their systems. * To preserve a fixed reference point for the code in question, just in case we break something really badly later. (Although Subversion normally prevents anything horrible like this happening.) * To ensure that all new features and fixes in need of testing have the greatest possible number of potential testers. No claims are made that any _-CURRENT_ snapshot can be considered "production quality" for any purpose. If a stable and fully tested system is needed, stick to full releases. Snapshot releases are directly available from link:https://www.FreeBSD.org/snapshots/[snapshot]. Official snapshots are generated on a regular basis for all actively developed branches. [[responsible]] === Who is responsible for FreeBSD? The key decisions concerning the FreeBSD project, such as the overall direction of the project and who is allowed to add code to the source tree, are made by a link:https://www.FreeBSD.org/administration#t-core[core team] of 9 people. There is a much larger team of more than 350 link:{contributors}#staff-committers[committers] who are authorized to make changes directly to the FreeBSD source tree. However, most non-trivial changes are discussed in advance in the <>, and there are no restrictions on who may take part in the discussion. [[where-get]] === Where can I get FreeBSD? Every significant release of FreeBSD is available via anonymous FTP from the https://download.FreeBSD.org/ftp/releases/[FreeBSD FTP site]: * The latest {rel-stable} release, {rel121-current}-RELEASE can be found in the https://download.FreeBSD.org/ftp/releases/amd64/amd64/{rel121-current}-RELEASE/[{rel121-current}-RELEASE directory]. * link:https://www.FreeBSD.org/snapshots/[Snapshot] releases are made monthly for the <> and <> branch, these being of service purely to bleeding-edge testers and developers. * The latest {rel2-stable} release, {rel113-current}-RELEASE can be found in the https://download.FreeBSD.org/ftp/releases/amd64/amd64/{rel113-current}-RELEASE/[{rel113-current}-RELEASE directory]. Information about obtaining FreeBSD on CD, DVD, and other media can be found in link:{handbook}#mirrors/[the Handbook]. [[access-pr]] === How do I access the Problem Report database? The Problem Report database of all user change requests may be queried by using our web-based PR https://bugs.FreeBSD.org/search/[query] interface. The link:https://www.FreeBSD.org/support/bugreports[web-based problem report submission interface] can be used to submit problem reports through a web browser. Before submitting a problem report, read link:{problem-reports}[Writing FreeBSD Problem Reports], an article on how to write good problem reports. [[support]] == Documentation and Support [[books]] === What good books are there about FreeBSD? The project produces a wide range of documentation, available online from this link: https://www.FreeBSD.org/docs/[https://www.FreeBSD.org/docs/]. [[doc-formats]] === Is the documentation available in other formats, such as plain text (ASCII), or PDF? Yes. The documentation is available in a number of different formats and compression schemes on the FreeBSD FTP site, in the https://download.freebsd.org/ftp/doc/[/ftp/doc/] directory. The documentation is categorized in a number of different ways. These include: * The document's name, such as `faq`, or `handbook`. -* The document's language and encoding. These are based on the locale names found under [.filename]#/usr/shared/locale# on a FreeBSD system. The current languages and encodings are as follows: +* The document's language and encoding. These are based on the locale names found under [.filename]#/usr/share/locale# on a FreeBSD system. The current languages and encodings are as follows: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Name | Meaning |`en_US.ISO8859-1` |English (United States) |`bn_BD.ISO10646-1` |Bengali or Bangla (Bangladesh) |`da_DK.ISO8859-1` |Danish (Denmark) |`de_DE.ISO8859-1` |German (Germany) |`el_GR.ISO8859-7` |Greek (Greece) |`es_ES.ISO8859-1` |Spanish (Spain) |`fr_FR.ISO8859-1` |French (France) |`hu_HU.ISO8859-2` |Hungarian (Hungary) |`it_IT.ISO8859-15` |Italian (Italy) |`ja_JP.eucJP` |Japanese (Japan, EUC encoding) |`ko_KR.UTF-8` |Korean (Korea, UTF-8 encoding) |`mn_MN.UTF-8` |Mongolian (Mongolia, UTF-8 encoding) |`nl_NL.ISO8859-1` |Dutch (Netherlands) |`pl_PL.ISO8859-2` |Polish (Poland) |`pt_BR.ISO8859-1` |Portuguese (Brazil) |`ru_RU.KOI8-R` |Russian (Russia, KOI8-R encoding) |`tr_TR.ISO8859-9` |Turkish (Turkey) |`zh_CN.UTF-8` |Simplified Chinese (China, UTF-8 encoding) |`zh_TW.UTF-8` |Traditional Chinese (Taiwan, UTF-8 encoding) |=== + [NOTE] ==== Some documents may not be available in all languages. ==== * The document's format. We produce the documentation in a number of different output formats. Each format has its own advantages and disadvantages. Some formats are better suited for online reading, while others are meant to be aesthetically pleasing when printed on paper. Having the documentation available in any of these formats ensures that our readers will be able to read the parts they are interested in, either on their monitor, or on paper after printing the documents. The currently available formats are: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Format | Meaning |`html-split` |A collection of small, linked, HTML files. |`html` |One large HTML file containing the entire document |`pdf` |Adobe's Portable Document Format |`txt` |Plain text |=== * The compression and packaging scheme. .. Where the format is `html-split`, the files are bundled up using man:tar[1]. The resulting [.filename]#.tar# is then compressed using the compression schemes detailed in the next point. .. All the other formats generate one file. For example, [.filename]#article.pdf#, [.filename]#book.html#, and so on. + These files are then compressed using either the `zip` or `bz2` compression schemes. man:tar[1] can be used to uncompress these files. + So the PDF version of the Handbook, compressed using `bzip2` will be stored in a file called [.filename]#book.pdf.bz2# in the [.filename]#handbook/# directory. After choosing the format and compression mechanism, download the compressed files, uncompress them, and then copy the appropriate documents into place. For example, the split HTML version of the FAQ, compressed using man:bzip2[1], can be found in [.filename]#doc/en_US.ISO8859-1/books/faq/book.html-split.tar.bz2# To download and uncompress that file, type: [source,bash] .... # fetch https://download.freebsd.org/ftp/doc/en_US.ISO8859-1/books/faq/book.html-split.tar.bz2 # tar xvf book.html-split.tar.bz2 .... If the file is compressed, tar will automatically detect the appropriate format and decompress it correctly, resulting in a collection of [.filename]#.html# files. The main one is called [.filename]#index.html#, which will contain the table of contents, introductory material, and links to the other parts of the document. [[mailing]] === Where do I find info on the FreeBSD mailing lists? What FreeBSD news groups are available? Refer to the link:{handbook}#eresources-mail[Handbook entry on mailing-lists] and the link:{handbook}#eresources-news/[Handbook entry on newsgroups]. [[irc]] === Are there FreeBSD IRC (Internet Relay Chat) channels? Yes, most major IRC networks host a FreeBSD chat channel: * Channel `#FreeBSDhelp` on http://www.efnet.org/index.php[EFNet] is a channel dedicated to helping FreeBSD users. * Channel `#FreeBSD` on http://freenode.net/[Freenode] is a general help channel with many users at any time. The conversations have been known to run off-topic for a while, but priority is given to users with FreeBSD questions. Other users can help with the basics, referring to the Handbook whenever possible and providing links for learning more about a particular topic. This is primarily an English speaking channel, though it does have users from all over the world. Non-native English speakers should try to ask the question in English first and then relocate to `##freebsd-lang` as appropriate. * Channel `#FreeBSD` on http://www.dal.net/[DALNET] is available at `irc.dal.net` in the US and `irc.eu.dal.net` in Europe. * Channel `#FreeBSD` on http://www.undernet.org/[UNDERNET] is available at `us.undernet.org` in the US and `eu.undernet.org` in Europe. Since it is a help channel, be prepared to read the documents you are referred to. * Channel `#FreeBSD` on http://www.rusnet.org.ru/[RUSNET] is a Russian language channel dedicated to helping FreeBSD users. This is also a good place for non-technical discussions. * Channel `#bsdchat` on http://freenode.net/[Freenode] is a Traditional Chinese (UTF-8 encoding) language channel dedicated to helping FreeBSD users. This is also a good place for non-technical discussions. The FreeBSD wiki has a https://wiki.freebsd.org/IRC/Channels[good list] of IRC channels. Each of these channels are distinct and are not connected to each other. Since their chat styles differ, try each to find one suited to your chat style. [[forums]] === Are there any web based forums to discuss FreeBSD? The official FreeBSD forums are located at https://forums.FreeBSD.org/[https://forums.FreeBSD.org/]. [[training]] === Where can I get commercial FreeBSD training and support? http://www.ixsystems.com[iXsystems, Inc.], parent company of the http://www.freebsdmall.com/[FreeBSD Mall], provides commercial FreeBSD and TrueOS software http://www.ixsystems.com/support[support], in addition to FreeBSD development and tuning solutions. BSD Certification Group, Inc. provides system administration certifications for DragonFly BSD, FreeBSD, NetBSD, and OpenBSD. Refer to http://www.BSDCertification.org[their site] for more information. Any other organizations providing training and support should contact the Project to be listed here. [[install]] == Installation [[which-architecture]] === Which platform should I download? I have a 64 bit capable Intel(R) CPU, but I only see amd64. amd64 is the term FreeBSD uses for 64-bit compatible x86 architectures (also known as "x86-64" or "x64"). Most modern computers should use amd64. Older hardware should use i386. When installing on a non-x86-compatible architecture, select the platform which best matches the hardware. [[floppy-download]] === Which file do I download to get FreeBSD? On the https://www.freebsd.org/where/[Getting FreeBSD] page, select `[iso]` next to the architecture that matches the hardware. Any of the following can be used: [.informaltable] [cols="1,1", frame="none", options="header"] |=== | file | description |[.filename]#disc1.iso# |Contains enough to install FreeBSD and a minimal set of packages. |[.filename]#dvd1.iso# |Similar to [.filename]#disc1.iso# but with additional packages. |[.filename]#memstick.img# |A bootable image sufficient for writing to a USB stick. |[.filename]#bootonly.iso# |A minimal image that requires network access during installation to completely install FreeBSD. |=== Full instructions on this procedure and a little bit more about installation issues in general can be found in the link:{handbook}#bsdinstall/[Handbook entry on installing FreeBSD]. [[floppy-image-too-large]] === What do I do if the install image does not boot? This can be caused by not downloading the image in _binary_ mode when using FTP. Some FTP clients default their transfer mode to _ascii_ and attempt to change any end-of-line characters received to match the conventions used by the client's system. This will almost invariably corrupt the boot image. Check the SHA-256 checksum of the downloaded boot image: if it is not _exactly_ that on the server, then the download process is suspect. When using a command line FTP client, type _binary_ at the FTP command prompt after getting connected to the server and before starting the download of the image. [[install-instructions-location]] === Where are the instructions for installing FreeBSD? Installation instructions can be found at link:{handbook}#bsdinstall/[Handbook entry on installing FreeBSD]. [[custom-boot-floppy]] === How can I make my own custom release or install disk? Customized FreeBSD installation media can be created by building a custom release. Follow the instructions in the link:{releng}[Release Engineering] article. [[windows-coexist]] === Can Windows(R) co-exist with FreeBSD? (x86-specific) If Windows(R) is installed first, then yes. FreeBSD's boot manager will then manage to boot Windows(R) and FreeBSD. If Windows(R) is installed afterwards, it will overwrite the boot manager. If that happens, see the next section. [[bootmanager-restore]] === Another operating system destroyed my Boot Manager. How do I get it back? (x86-specific) This depends upon the boot manager. The FreeBSD boot selection menu can be reinstalled using man:boot0cfg[8]. For example, to restore the boot menu onto the disk _ada0_: [source,bash] .... # boot0cfg -B ada0 .... The non-interactive MBR bootloader can be installed using man:gpart[8]: [source,bash] .... # gpart bootcode -b /boot/mbr ada0 .... For more complex situations, including GPT disks, see man:gpart[8]. [[need-complete-sources]] === Do I need to install the source? In general, no. There is nothing in the base system which requires the presence of the source to operate. Some ports, like package:sysutils/lsof[], will not build unless the source is installed. In particular, if the port builds a kernel module or directly operates on kernel structures, the source must be installed. [[need-kernel]] === Do I need to build a kernel? Usually not. The supplied `GENERIC` kernel contains the drivers an ordinary computer will need. man:freebsd-update[8], the FreeBSD binary upgrade tool, cannot upgrade custom kernels, another reason to stick with the `GENERIC` kernel when possible. For computers with very limited RAM, such as embedded systems, it may be worthwhile to build a smaller custom kernel containing just the required drivers. [[password-encryption]] === Should I use DES, Blowfish, or MD5 passwords and how do I specify which form my users receive? FreeBSD uses _SHA512_ by default. DES passwords are still available for backwards compatibility with operating systems that still use the less secure password format. FreeBSD also supports the Blowfish and MD5 password formats. Which password format to use for new passwords is controlled by the `passwd_format` login capability in [.filename]#/etc/login.conf#, which takes values of `des`, `blf` (if these are available) or `md5`. See the man:login.conf[5] manual page for more information about login capabilities. [[ffs-limits]] === What are the limits for FFS file systems? For FFS file systems, the largest file system is practically limited by the amount of memory required to man:fsck[8] the file system. man:fsck[8] requires one bit per fragment, which with the default fragment size of 4 KB equates to 32 MB of memory per TB of disk. This does mean that on architectures which limit userland processes to 2 GB (e.g., i386(TM)), the maximum man:fsck[8]'able filesystem is ~60 TB. If there was not a man:fsck[8] memory limit the maximum filesystem size would be 2 ^ 64 (blocks) * 32 KB => 16 Exa * 32 KB => 512 ZettaBytes. The maximum size of a single FFS file is approximately 2 PB with the default block size of 32 KB. Each 32 KB block can point to 4096 blocks. With triple indirect blocks, the calculation is 32 KB * 12 + 32 KB * 4096 + 32 KB * 4096^2 + 32 KB * 4096^3. Increasing the block size to 64 KB will increase the max file size by a factor of 16. [[archsw-readin-failed-error]] === Why do I get an error message, readin failed after compiling and booting a new kernel? The world and kernel are out of sync. This is not supported. Be sure to use `make buildworld` and `make buildkernel` to update the kernel. Boot the system by specifying the kernel directly at the second stage, pressing any key when the `|` shows up before loader is started. [[general-configuration-tool]] === Is there a tool to perform post-installation configuration tasks? Yes. bsdconfig provides a nice interface to configure FreeBSD post-installation. [[hardware]] == Hardware Compatibility [[compatibility-general]] === General [[which-hardware-to-get]] ==== I want to get a piece of hardware for my FreeBSD system. Which model/brand/type is best? This is discussed continually on the FreeBSD mailing lists but is to be expected since hardware changes so quickly. Read through the Hardware Notes for FreeBSD link:{u-rel121-hardware}[{rel121-current}] or link:{u-rel113-hardware}[{rel113-current}] and search the mailing list https://www.FreeBSD.org/search/#mailinglists[archives] before asking about the latest and greatest hardware. Chances are a discussion about that type of hardware took place just last week. Before purchasing a laptop, check the archives for {freebsd-questions}, or possibly a specific mailing list for a particular hardware type. [[memory-upper-limitation]] ==== What are the limits for memory? FreeBSD as an operating system generally supports as much physical memory (RAM) as the platform it is running on does. Keep in mind that different platforms have different limits for memory; for example i386(TM) without PAE supports at most 4 GB of memory (and usually less than that because of PCI address space) and i386(TM) with PAE supports at most 64 GB memory. As of FreeBSD 10, AMD64 platforms support up to 4 TB of physical memory. [[memory-i386-over-4gb]] ==== Why does FreeBSD report less than 4 GB memory when installed on an i386(TM) machine? The total address space on i386(TM) machines is 32-bit, meaning that at most 4 GB of memory is addressable (can be accessed). Furthermore, some addresses in this range are reserved by hardware for different purposes, for example for using and controlling PCI devices, for accessing video memory, and so on. Therefore, the total amount of memory usable by the operating system for its kernel and applications is limited to significantly less than 4 GB. Usually, 3.2 GB to 3.7 GB is the maximum usable physical memory in this configuration. To access more than 3.2 GB to 3.7 GB of installed memory (meaning up to 4 GB but also more than 4 GB), a special tweak called PAE must be used. PAE stands for Physical Address Extension and is a way for 32-bit x86 CPUs to address more than 4 GB of memory. It remaps the memory that would otherwise be overlaid by address reservations for hardware devices above the 4 GB range and uses it as additional physical memory (see man:pae[4]). Using PAE has some drawbacks; this mode of memory access is a little bit slower than the normal (without PAE) mode and loadable modules (see man:kld[4]) are not supported. This means all drivers must be compiled into the kernel. The most common way to enable PAE is to build a new kernel with the special ready-provided kernel configuration file called [.filename]#PAE#, which is already configured to build a safe kernel. Note that some entries in this kernel configuration file are too conservative and some drivers marked as unready to be used with PAE are actually usable. A rule of thumb is that if the driver is usable on 64-bit architectures (like AMD64), it is also usable with PAE. When creating a custom kernel configuration file, PAE can be enabled by adding the following line: [.programlisting] .... options PAE .... PAE is not much used nowadays because most new x86 hardware also supports running in 64-bit mode, known as AMD64 or Intel(R) 64. It has a much larger address space and does not need such tweaks. FreeBSD supports AMD64 and it is recommended that this version of FreeBSD be used instead of the i386(TM) version if 4 GB or more memory is required. [[compatibility-processors]] === Architectures and Processors [[architectures]] ==== Does FreeBSD support architectures other than the x86? Yes. FreeBSD divides support into multiple tiers. Tier 1 architectures, such as i386 or amd64; are fully supported. Tiers 2 and 3 are supported on a best-effort basis. A full explanation of the tier system is available in the link:{committers-guide}#archs/[Committer's Guide.] A complete list of supported architectures can be found on the https://www.FreeBSD.org/platforms/[platforms page.] [[smp-support]] ==== Does FreeBSD support Symmetric Multiprocessing (SMP)? FreeBSD supports symmetric multi-processor (SMP) on all non-embedded platforms (e.g, i386, amd64, etc.). SMP is also supported in arm and MIPS kernels, although some CPUs may not support this. FreeBSD's SMP implementation uses fine-grained locking, and performance scales nearly linearly with number of CPUs. man:smp[4] has more details. [[microcode]] ==== What is microcode? How do I install Intel(R) CPU microcode updates? Microcode is a method of programmatically implementing hardware level instructions. This allows for CPU bugs to be fixed without replacing the on board chip. Install package:sysutils/devcpu-data[], then add: [.programlisting] .... microcode_update_enable="YES" .... to [.filename]#/etc/rc.conf# [[compatibility-peripherals]] === Peripherals [[supported-peripherals]] ==== What kind of peripherals does FreeBSD support? See the complete list in the Hardware Notes for FreeBSD link:{u-rel121-hardware}[{rel121-current}] or link:{u-rel113-hardware}[{rel113-current}]. [[compatibility-kbd-mice]] === Keyboards and Mice [[moused]] ==== Is it possible to use a mouse outside the X Window system? The default console driver, man:vt[4], provides the ability to use a mouse pointer in text consoles to cut & paste text. Run the mouse daemon, man:moused[8], and turn on the mouse pointer in the virtual console: [source,bash] .... # moused -p /dev/xxxx -t yyyy # vidcontrol -m on .... Where _xxxx_ is the mouse device name and _yyyy_ is a protocol type for the mouse. The mouse daemon can automatically determine the protocol type of most mice, except old serial mice. Specify the `auto` protocol to invoke automatic detection. If automatic detection does not work, see the man:moused[8] manual page for a list of supported protocol types. For a PS/2 mouse, add `moused_enable="YES"` to [.filename]#/etc/rc.conf# to start the mouse daemon at boot time. Additionally, to use the mouse daemon on all virtual terminals instead of just the console, add `allscreens_flags="-m on"` to [.filename]#/etc/rc.conf#. When the mouse daemon is running, access to the mouse must be coordinated between the mouse daemon and other programs such as X Windows. Refer to the FAQ<> for more details on this issue. [[text-mode-cut-paste]] ==== How do I cut and paste text with a mouse in the text console? It is not possible to remove data using the mouse. However, it is possible to copy and paste. Once the mouse daemon is running as described in the <>, hold down button 1 (left button) and move the mouse to select a region of text. Then, press button 2 (middle button) to paste it at the text cursor. Pressing button 3 (right button) will "extend" the selected region of text. If the mouse does not have a middle button, it is possible to emulate one or remap buttons using mouse daemon options. See the man:moused[8] manual page for details. [[mouse-wheel-buttons]] ==== My mouse has a fancy wheel and buttons. Can I use them in FreeBSD? The answer is, unfortunately, "It depends". These mice with additional features require specialized driver in most cases. Unless the mouse device driver or the user program has specific support for the mouse, it will act just like a standard two, or three button mouse. For the possible usage of wheels in the X Window environment, refer to <>. [[keyboard-delete-key]] ==== How do I use my delete key in sh and csh? For the Bourne Shell, add the following lines to [.filename]#~/.shrc#. See man:sh[1] and man:editrc[5]. [.programlisting] .... bind ^[[3~ ed-delete-next-char # for xterm .... For the C Shell, add the following lines to [.filename]#~/.cshrc#. See man:csh[1]. [.programlisting] .... bindkey ^[[3~ delete-char # for xterm .... [[compatibility-other]] === Other Hardware [[es1370-silent-pcm]] ==== Workarounds for no sound from my man:pcm[4] sound card? Some sound cards set their output volume to 0 at every boot. Run the following command every time the machine boots: [source,bash] .... # mixer pcm 100 vol 100 cd 100 .... [[power-management-support]] ==== Does FreeBSD support power management on my laptop? FreeBSD supports the ACPI features found in modern hardware. Further information can be found in man:acpi[4]. [[troubleshoot]] == Troubleshooting [[pae]] === Why is FreeBSD finding the wrong amount of memory on i386(TM) hardware? The most likely reason is the difference between physical memory addresses and virtual addresses. The convention for most PC hardware is to use the memory area between 3.5 GB and 4 GB for a special purpose (usually for PCI). This address space is used to access PCI hardware. As a result real, physical memory cannot be accessed by that address space. What happens to the memory that should appear in that location is hardware dependent. Unfortunately, some hardware does nothing and the ability to use that last 500 MB of RAM is entirely lost. Luckily, most hardware remaps the memory to a higher location so that it can still be used. However, this can cause some confusion when watching the boot messages. On a 32-bit version of FreeBSD, the memory appears lost, since it will be remapped above 4 GB, which a 32-bit kernel is unable to access. In this case, the solution is to build a PAE enabled kernel. See the entry on memory limits for more information. On a 64-bit version of FreeBSD, or when running a PAE-enabled kernel, FreeBSD will correctly detect and remap the memory so it is usable. During boot, however, it may seem as if FreeBSD is detecting more memory than the system really has, due to the described remapping. This is normal and the available memory will be corrected as the boot process completes. [[signal11]] === Why do my programs occasionally die with Signal 11 errors? Signal 11 errors are caused when a process has attempted to access memory which the operating system has not granted it access to. If something like this is happening at seemingly random intervals, start investigating the cause. These problems can usually be attributed to either: . If the problem is occurring only in a specific custom application, it is probably a bug in the code. . If it is a problem with part of the base FreeBSD system, it may also be buggy code, but more often than not these problems are found and fixed long before us general FAQ readers get to use these bits of code (that is what -CURRENT is for). It is probably not a FreeBSD bug if the problem occurs compiling a program, but the activity that the compiler is carrying out changes each time. For example, if `make buildworld` fails while trying to compile [.filename]#ls.c# into [.filename]#ls.o# and, when run again, it fails in the same place, this is a broken build. Try updating source and try again. If the compile fails elsewhere, it is almost certainly due to hardware. In the first case, use a debugger such as man:gdb[1] to find the point in the program which is attempting to access a bogus address and fix it. In the second case, verify which piece of hardware is at fault. Common causes of this include: . The hard disks might be overheating: Check that the fans are still working, as the disk and other hardware might be overheating. . The processor running is overheating: This might be because the processor has been overclocked, or the fan on the processor might have died. In either case, ensure that the hardware is running at what it is specified to run at, at least while trying to solve this problem. If it is not, clock it back to the default settings.) + Regarding overclocking, it is far cheaper to have a slow system than a fried system that needs replacing! Also the community is not sympathetic to problems on overclocked systems. . Dodgy memory: if multiple memory SIMMS/DIMMS are installed, pull them all out and try running the machine with each SIMM or DIMM individually to narrow the problem down to either the problematic DIMM/SIMM or perhaps even a combination. . Over-optimistic motherboard settings: the BIOS settings, and some motherboard jumpers, provide options to set various timings. The defaults are often sufficient, but sometimes setting the wait states on RAM too low, or setting the "RAM Speed: Turbo" option will cause strange behavior. A possible idea is to set to BIOS defaults, after noting the current settings first. . Unclean or insufficient power to the motherboard. Remove any unused I/O boards, hard disks, or CD-ROMs, or disconnect the power cable from them, to see if the power supply can manage a smaller load. Or try another power supply, preferably one with a little more power. For instance, if the current power supply is rated at 250 Watts, try one rated at 300 Watts. Read the section on <> for a further explanation and a discussion on how memory testing software or hardware can still pass faulty memory. There is an extensive FAQ on this at http://www.bitwizard.nl/sig11/[the SIG11 problem FAQ]. Finally, if none of this has helped, it is possibly a bug in FreeBSD. Follow <> to send a problem report. [[trap-12-panic]] === My system crashes with either Fatal trap 12: page fault in kernel mode, or panic:, and spits out a bunch of information. What should I do? The FreeBSD developers are interested in these errors, but need more information than just the error message. Copy the full crash message. Then consult the FAQ section on <>, build a debugging kernel, and get a backtrace. This might sound difficult, but does not require any programming skills. Just follow the instructions. [[proc-table-full]] === What is the meaning of the error maxproc limit exceeded by uid %i, please see tuning(7) and login.conf(5)? The FreeBSD kernel will only allow a certain number of processes to exist at one time. The number is based on the `kern.maxusers` man:sysctl[8] variable. `kern.maxusers` also affects various other in-kernel limits, such as network buffers. If the machine is heavily loaded, increase `kern.maxusers`. This will increase these other system limits in addition to the maximum number of processes. To adjust the `kern.maxusers` value, see the link:{handbook}#kern-maxfiles[File/Process Limits] section of the Handbook. While that section refers to open files, the same limits apply to processes. If the machine is lightly loaded but running a very large number of processes, adjust the `kern.maxproc` tunable by defining it in [.filename]#/boot/loader.conf#. The tunable will not get adjusted until the system is rebooted. For more information about tuning tunables, see man:loader.conf[5]. If these processes are being run by a single user, adjust `kern.maxprocperuid` to be one less than the new `kern.maxproc` value. It must be at least one less because one system program, man:init[8], must always be running. [[remote-fullscreen]] === Why do full screen applications on remote machines misbehave? The remote machine may be setting the terminal type to something other than `xterm` which is required by the FreeBSD console. Alternatively the kernel may have the wrong values for the width and height of the terminal. Check the value of the `TERM` environment variable is `xterm`. If the remote machine does not support that try `vt100`. Run `stty -a` to check what the kernel thinks the terminal dimensions are. If they are incorrect, they can be changed by running `stty rows _RR_ cols _CC_`. Alternatively, if the client machine has package:x11/xterm[] installed, then running `resize` will query the terminal for the correct dimensions and set them. [[connection-delay]] === Why does it take so long to connect to my computer via ssh or telnet? The symptom: there is a long delay between the time the TCP connection is established and the time when the client software asks for a password (or, in man:telnet[1]'s case, when a login prompt appears). The problem: more likely than not, the delay is caused by the server software trying to resolve the client's IP address into a hostname. Many servers, including the Telnet and SSH servers that come with FreeBSD, do this to store the hostname in a log file for future reference by the administrator. The remedy: if the problem occurs whenever connecting the client computer to any server, the problem is with the client. If the problem only occurs when someone connects to the server computer, the problem is with the server. If the problem is with the client, the only remedy is to fix the DNS so the server can resolve it. If this is on a local network, consider it a server problem and keep reading. If this is on the Internet, contact your ISP. If the problem is with the server on a local network, configure the server to resolve address-to-hostname queries for the local address range. See man:hosts[5] and man:named[8] for more information. If this is on the Internet, the problem may be that the local server's resolver is not functioning correctly. To check, try to look up another host such as `www.yahoo.com`. If it does not work, that is the problem. Following a fresh install of FreeBSD, it is also possible that domain and name server information is missing from [.filename]#/etc/resolv.conf#. This will often cause a delay in SSH, as the option `UseDNS` is set to `yes` by default in [.filename]#/etc/ssh/sshd_config#. If this is causing the problem, either fill in the missing information in [.filename]#/etc/resolv.conf# or set `UseDNS` to `no` in [.filename]#sshd_config# as a temporary workaround. [[file-table-full]] === Why does file: table is full show up repeatedly in man:dmesg[8]? This error message indicates that the number of available file descriptors have been exhausted on the system. Refer to the link:{handbook}#kern-maxfiles[kern.maxfiles] section of the link:{handbook}#configtuning-kernel-limits/[Tuning Kernel Limits] section of the Handbook for a discussion and solution. [[computer-clock-skew]] === Why does the clock on my computer keep incorrect time? The computer has two or more clocks, and FreeBSD has chosen to use the wrong one. Run man:dmesg[8], and check for lines that contain `Timecounter`. The one with the highest quality value that FreeBSD chose. [source,bash] .... # dmesg | grep Timecounter Timecounter "i8254" frequency 1193182 Hz quality 0 Timecounter "ACPI-fast" frequency 3579545 Hz quality 1000 Timecounter "TSC" frequency 2998570050 Hz quality 800 Timecounters tick every 1.000 msec .... Confirm this by checking the `kern.timecounter.hardware` man:sysctl[3]. [source,bash] .... # sysctl kern.timecounter.hardware kern.timecounter.hardware: ACPI-fast .... It may be a broken ACPI timer. The simplest solution is to disable the ACPI timer in [.filename]#/boot/loader.conf#: [.programlisting] .... debug.acpi.disabled="timer" .... Or the BIOS may modify the TSC clock-perhaps to change the speed of the processor when running from batteries, or going into a power saving mode, but FreeBSD is unaware of these adjustments, and appears to gain or lose time. In this example, the `i8254` clock is also available, and can be selected by writing its name to the `kern.timecounter.hardware` man:sysctl[3]. [source,bash] .... # sysctl kern.timecounter.hardware=i8254 kern.timecounter.hardware: TSC -> i8254 .... The computer should now start keeping more accurate time. To have this change automatically run at boot time, add the following line to [.filename]#/etc/sysctl.conf#: [.programlisting] .... kern.timecounter.hardware=i8254 .... [[indefinite-wait-buffer]] === What does the error swap_pager: indefinite wait buffer: mean? This means that a process is trying to page memory from disk, and the page attempt has hung trying to access the disk for more than 20 seconds. It might be caused by bad blocks on the disk drive, disk wiring, cables, or any other disk I/O-related hardware. If the drive itself is bad, disk errors will appear in [.filename]#/var/log/messages# and in the output of `dmesg`. Otherwise, check the cables and connections. [[lock-order-reversal]] === What is a lock order reversal? The FreeBSD kernel uses a number of resource locks to arbitrate contention for certain resources. When multiple kernel threads try to obtain multiple resource locks, there's always the potential for a deadlock, where two threads have each obtained one of the locks and blocks forever waiting for the other thread to release one of the other locks. This sort of locking problem can be avoided if all threads obtain the locks in the same order. A run-time lock diagnostic system called man:witness[4], enabled in FreeBSD-CURRENT and disabled by default for stable branches and releases, detects the potential for deadlocks due to locking errors, including errors caused by obtaining multiple resource locks with a different order from different parts of the kernel. The man:witness[4] framework tries to detect this problem as it happens, and reports it by printing a message to the system console about a `lock order reversal` (often referred to also as LOR). It is possible to get false positives, as man:witness[4] is conservative. A true positive report _does not_ mean that a system is dead-locked; instead it should be understood as a warning that a deadlock could have happened here. [NOTE] ==== Problematic LORs tend to get fixed quickly, so check the {freebsd-current} before posting to it. ==== [[called-with-non-sleepable-locks-held]] === What does Called ... with the following non-sleepable locks held mean? This means that a function that may sleep was called while a mutex (or other unsleepable) lock was held. The reason this is an error is because mutexes are not intended to be held for long periods of time; they are supposed to only be held to maintain short periods of synchronization. This programming contract allows device drivers to use mutexes to synchronize with the rest of the kernel during interrupts. Interrupts (under FreeBSD) may not sleep. Hence it is imperative that no subsystem in the kernel block for an extended period while holding a mutex. To catch such errors, assertions may be added to the kernel that interact with the man:witness[4] subsystem to emit a warning or fatal error (depending on the system configuration) when a potentially blocking call is made while holding a mutex. In summary, such warnings are non-fatal, however with unfortunate timing they could cause undesirable effects ranging from a minor blip in the system's responsiveness to a complete system lockup. For additional information about locking in FreeBSD see man:locking[9]. [[touch-not-found]] === Why does buildworld/installworld die with the message touch: not found? This error does not mean that the man:touch[1] utility is missing. The error is instead probably due to the dates of the files being set sometime in the future. If the CMOS clock is set to local time, run `adjkerntz -i` to adjust the kernel clock when booting into single-user mode. [[applications]] == User Applications [[user-apps]] === Where are all the user applications? Refer to link:https://www.FreeBSD.org/ports/[the ports page] for info on software packages ported to FreeBSD. Most ports should work on all supported versions of FreeBSD. Those that do not are specifically marked as such. Each time a FreeBSD release is made, a snapshot of the ports tree at the time of release is also included in the [.filename]#ports/# directory. FreeBSD supports compressed binary packages to easily install and uninstall ports. Use man:pkg[7] to control the installation of packages. [[how-do-download-ports-tree]] === How do I download the Ports tree? Should I be using Subversion? Any of the methods listed here work: * Use portsnap for most use cases. Refer to link:{handbook}#ports-using/[Using the Ports Collection] for instructions on how to use this tool. * Use Subversion if custom patches to the ports tree are needed or if running FreeBSD-CURRENT. Refer to link:{handbook}#svn/[Using Subversion] for details. [[ports-4x]] === Why can I not build this port on my {rel2-relx} -, or {rel-relx} -STABLE machine? If the installed FreeBSD version lags significantly behind _-CURRENT_ or _-STABLE_, update the Ports Collection using the instructions in link:{handbook}#ports-using/[Using the Ports Collection]. If the system is up-to-date, someone might have committed a change to the port which works for _-CURRENT_ but which broke the port for _-STABLE_. https://bugs.FreeBSD.org/submit/[Submit] a bug report, since the Ports Collection is supposed to work for both the _-CURRENT_ and _-STABLE_ branches. [[make-index]] === I just tried to build INDEX using make index, and it failed. Why? First, make sure that the Ports Collection is up-to-date. Errors that affect building [.filename]#INDEX# from an up-to-date copy of the Ports Collection are high-visibility and are thus almost always fixed immediately. There are rare cases where [.filename]#INDEX# will not build due to odd cases involving `OPTIONS_SET` being set in [.filename]#make.conf#. If you suspect that this is the case, try to make [.filename]#INDEX# with those variables turned off before reporting it to {freebsd-ports}. [[ports-update]] === I updated the sources, now how do I update my installed ports? FreeBSD does not include a port upgrading tool, but it does have some tools to make the upgrade process somewhat easier. Additional tools are available to simplify port handling and are described the link:{handbook}#ports-using/[Upgrading Ports] section in the FreeBSD Handbook. [[ports-major-upgrade]] === Do I need to recompile every port each time I perform a major version update? Yes! While a recent system will run with software compiled under an older release, things will randomly crash and fail to work once other ports are installed or updated. When the system is upgraded, various shared libraries, loadable modules, and other parts of the system will be replaced with newer versions. Applications linked against the older versions may fail to start or, in other cases, fail to function properly. For more information, see link:{handbook}#freebsdupdate-upgrade[the section on upgrades] in the FreeBSD Handbook. [[ports-minor-upgrade]] === Do I need to recompile every port each time I perform a minor version update? In general, no. FreeBSD developers do their utmost to guarantee binary compatibility across all releases with the same major version number. Any exceptions will be documented in the Release Notes, and advice given there should be followed. [[minimal-sh]] === Why is /bin/sh so minimal? Why does FreeBSD not use bash or another shell? Many people need to write shell scripts which will be portable across many systems. That is why POSIX(R) specifies the shell and utility commands in great detail. Most scripts are written in Bourne shell (man:sh[1]), and because several important programming interfaces (man:make[1], man:system[3], man:popen[3], and analogues in higher-level scripting languages like Perl and Tcl) are specified to use the Bourne shell to interpret commands. As the Bourne shell is so often and widely used, it is important for it to be quick to start, be deterministic in its behavior, and have a small memory footprint. The existing implementation is our best effort at meeting as many of these requirements simultaneously as we can. To keep `/bin/sh` small, we have not provided many of the convenience features that other shells have. That is why other more featureful shells like `bash`, `scsh`, man:tcsh[1], and `zsh` are available. Compare the memory utilization of these shells by looking at the "VSZ" and "RSS" columns in a `ps -u` listing. [[kernelconfig]] == Kernel Configuration [[make-kernel]] === I would like to customize my kernel. Is it difficult? Not at all! Check out the link:{handbook}#kernelconfig/[kernel config section of the Handbook]. [NOTE] ==== The new [.filename]#kernel# will be installed to the [.filename]#/boot/kernel# directory along with its modules, while the old kernel and its modules will be moved to the [.filename]#/boot/kernel.old# directory. If a mistake is made in the configuration, simply boot the previous version of the kernel. ==== [[why-kernel-big]] === Why is my kernel so big? `GENERIC` kernels shipped with FreeBSD are compiled in _debug mode_. Kernels built in debug mode contain debug data in separate files that are used for debugging. FreeBSD releases prior to 11.0 store these debug files in the same directory as the kernel itself, [.filename]#/boot/kernel/#. In FreeBSD 11.0 and later the debug files are stored in [.filename]#/usr/lib/debug/boot/kernel/#. Note that there will be little or no performance loss from running a debug kernel, and it is useful to keep one around in case of a system panic. When running low on disk space, there are different options to reduce the size of [.filename]#/boot/kernel/# and [.filename]#/usr/lib/debug/#. To not install the symbol files, make sure the following line exists in [.filename]#/etc/src.conf#: [.programlisting] .... WITHOUT_KERNEL_SYMBOLS=yes .... For more information see man:src.conf[5]. If you want to avoid building debug files altogether, make sure that both of the following are true: * This line does not exist in the kernel configuration file: + [.programlisting] .... makeoptions DEBUG=-g .... * Do not run man:config[8] with `-g`. Either of the above settings will cause the kernel to be built in debug mode. To build and install only the specified modules, list them in [.filename]#/etc/make.conf#: [.programlisting] .... MODULES_OVERRIDE= accf_http ipfw .... -Replace _accf_httpd ipfw_ with a list of needed modules. Only the listed modules will be built. This reduces the size of the kernel directory and decreases the amount of time needed to build the kernel. For more information, read [.filename]#/usr/shared/examples/etc/make.conf#. +Replace _accf_httpd ipfw_ with a list of needed modules. Only the listed modules will be built. This reduces the size of the kernel directory and decreases the amount of time needed to build the kernel. For more information, read [.filename]#/usr/share/examples/etc/make.conf#. Unneeded devices can be removed from the kernel to further reduce the size. See <> for more information. To put any of these options into effect, follow the instructions to link:{handbook}#kernelconfig-building/[build and install] the new kernel. For reference, the FreeBSD 11 amd64 kernel ([.filename]#/boot/kernel/kernel#) is approximately 25 MB. [[generic-kernel-build-failure]] === Why does every kernel I try to build fail to compile, even GENERIC? There are a number of possible causes for this problem: * The source tree is different from the one used to build the currently running system. When attempting an upgrade, read [.filename]#/usr/src/UPDATING#, paying particular attention to the "COMMON ITEMS" section at the end. * The `make buildkernel` did not complete successfully. The `make buildkernel` target relies on files generated by the `make buildworld` target to complete its job correctly. * Even when building <>, it is possible that the source tree was fetched at a time when it was either being modified or it was broken. Only releases are guaranteed to be buildable, although <> builds fine the majority of the time. Try re-fetching the source tree and see if the problem goes away. Try using a different mirror in case the previous one is having problems. [[scheduler-in-use]] === Which scheduler is in use on a running system? The name of the scheduler currently being used is directly available as the value of the `kern.sched.name` sysctl: [source,bash] .... % sysctl kern.sched.name kern.sched.name: ULE .... [[scheduler-kern-quantum]] === What is kern.sched.quantum? `kern.sched.quantum` is the maximum number of ticks a process can run without being preempted in the 4BSD scheduler. [[disks]] == Disks, File Systems, and Boot Loaders [[adding-disks]] === How can I add my new hard disk to my FreeBSD system? See the link:{handbook}#disks-adding/[Adding Disks] section in the FreeBSD Handbook. [[new-huge-disk]] === How do I move my system over to my huge new disk? The best way is to reinstall the operating system on the new disk, then move the user data over. This is highly recommended when tracking _-STABLE_ for more than one release or when updating a release instead of installing a new one. Install booteasy on both disks with man:boot0cfg[8] and dual boot until you are happy with the new configuration. Skip the next paragraph to find out how to move the data after doing this. Alternatively, partition and label the new disk with either man:sade[8] or man:gpart[8]. If the disks are MBR-formatted, booteasy can be installed on both disks with man:boot0cfg[8] so that the computer can dual boot to the old or new system after the copying is done. Once the new disk set up, the data cannot just be copied. Instead, use tools that understand device files and system flags, such as man:dump[8]. Although it is recommended to move the data while in single-user mode, it is not required. When the disks are formatted with UFS, never use anything but man:dump[8] and man:restore[8] to move the root file system. These commands should also be used when moving a single partition to another empty partition. The sequence of steps to use `dump` to move the data from one UFS partitions to a new partition is: [.procedure] ==== . `newfs` the new partition. . `mount` it on a temporary mount point. . `cd` to that directory. . `dump` the old partition, piping output to the new one. ==== For example, to move [.filename]#/dev/ada1s1a# with [.filename]#/mnt# as the temporary mount point, type: [source,bash] .... # newfs /dev/ada1s1a # mount /dev/ada1s1a /mnt # cd /mnt # dump 0af - / | restore rf - .... Rearranging partitions with `dump` takes a bit more work. To merge a partition like [.filename]#/var# into its parent, create the new partition large enough for both, move the parent partition as described above, then move the child partition into the empty directory that the first move created: [source,bash] .... # newfs /dev/ada1s1a # mount /dev/ada1s1a /mnt # cd /mnt # dump 0af - / | restore rf - # cd var # dump 0af - /var | restore rf - .... To split a directory from its parent, say putting [.filename]#/var# on its own partition when it was not before, create both partitions, then mount the child partition on the appropriate directory in the temporary mount point, then move the old single partition: [source,bash] .... # newfs /dev/ada1s1a # newfs /dev/ada1s1d # mount /dev/ada1s1a /mnt # mkdir /mnt/var # mount /dev/ada1s1d /mnt/var # cd /mnt # dump 0af - / | restore rf - .... The man:cpio[1] and man:pax[1] utilities are also available for moving user data. These are known to lose file flag information, so use them with caution. [[safe-softupdates]] === Which partitions can safely use Soft Updates? I have heard that Soft Updates on / can cause problems. What about Journaled Soft Updates? Short answer: Soft Updates can usually be safely used on all partitions. Long answer: Soft Updates has two characteristics that may be undesirable on certain partitions. First, a Soft Updates partition has a small chance of losing data during a system crash. The partition will not be corrupted as the data will simply be lost. Second, Soft Updates can cause temporary space shortages. When using Soft Updates, the kernel can take up to thirty seconds to write changes to the physical disk. When a large file is deleted the file still resides on disk until the kernel actually performs the deletion. This can cause a very simple race condition. Suppose one large file is deleted and another large file is immediately created. The first large file is not yet actually removed from the physical disk, so the disk might not have enough room for the second large file. This will produce an error that the partition does not have enough space, even though a large chunk of space has just been released. A few seconds later, the file creation works as expected. If a system should crash after the kernel accepts a chunk of data for writing to disk, but before that data is actually written out, data could be lost. This risk is extremely small, but generally manageable. These issues affect all partitions using Soft Updates. So, what does this mean for the root partition? Vital information on the root partition changes very rarely. If the system crashed during the thirty-second window after such a change is made, it is possible that data could be lost. This risk is negligible for most applications, but be aware that it exists. If the system cannot tolerate this much risk, do not use Soft Updates on the root file system! [.filename]#/# is traditionally one of the smallest partitions. If [.filename]#/tmp# is on [.filename]#/#, there may be intermittent space problems. Symlinking [.filename]#/tmp# to [.filename]#/var/tmp# will solve this problem. Finally, man:dump[8] does not work in live mode (-L) on a filesystem, with Journaled Soft Updates (SU+J). [[mount-foreign-fs]] === Can I mount other foreign file systems under FreeBSD? FreeBSD supports a variety of other file systems. UFS:: UFS CD-ROMs can be mounted directly on FreeBSD. Mounting disk partitions from Digital UNIX and other systems that support UFS may be more complex, depending on the details of the disk partitioning for the operating system in question. ext2/ext3:: FreeBSD supports `ext2fs` and `ext3fs` partitions. See man:ext2fs[5] for more information. NTFS:: FUSE based NTFS support is available as a port (package:sysutils/fusefs-ntfs[]). For more information see http://www.tuxera.com/community/ntfs-3g-manual/[ntfs-3g]. FAT:: FreeBSD includes a read-write FAT driver. For more information, see man:mount_msdosfs[8]. ZFS:: FreeBSD includes a port of Sun(TM)'s ZFS driver. The current recommendation is to use it only on amd64 platforms with sufficient memory. For more information, see man:zfs[8]. FreeBSD includes the Network File System NFS and the FreeBSD Ports Collection provides several FUSE applications to support many other file systems. [[mount-dos]] === How do I mount a secondary DOS partition? The secondary DOS partitions are found after _all_ the primary partitions. For example, if `E` is the second DOS partition on the second SCSI drive, there will be a device file for "slice 5" in [.filename]#/dev#. To mount it: [source,bash] .... # mount -t msdosfs /dev/da1s5 /dos/e .... [[crypto-file-system]] === Is there a cryptographic file system for FreeBSD? Yes, man:gbde[8] and man:geli[8]. See the link:{handbook}#disks-encrypting/[Encrypting Disk Partitions] section of the FreeBSD Handbook. [[grub-loader]] === How do I boot FreeBSD and Linux(R) using GRUB? To boot FreeBSD using GRUB, add the following to either [.filename]#/boot/grub/menu.lst# or [.filename]#/boot/grub/grub.conf#, depending upon which is used by the Linux(R) distribution. [.programlisting] .... title FreeBSD 9.1 root (hd0,a) kernel /boot/loader .... Where _hd0,a_ points to the root partition on the first disk. To specify the slice number, use something like this _(hd0,2,a)_. By default, if the slice number is omitted, GRUB searches the first slice which has the `a` partition. [[booteasy-loader]] === How do I boot FreeBSD and Linux(R) using BootEasy? Install LILO at the start of the Linux(R) boot partition instead of in the Master Boot Record. Then boot LILO from BootEasy. This is recommended when running Windows(R) and Linux(R) as it makes it simpler to get Linux(R) booting again if Windows(R) is reinstalled. [[changing-bootprompt]] === How do I change the boot prompt from ??? to something more meaningful? This cannot be accomplished with the standard boot manager without rewriting it. There are a number of other boot managers in the [.filename]#sysutils# category of the Ports Collection. [[removable-drives]] === How do I use a new removable drive? If the drive already has a file system on it, use a command like this: [source,bash] .... # mount -t msdosfs /dev/da0s1 /mnt .... If the drive will only be used with FreeBSD systems, partition it with UFS or ZFS. This will provide long filename support, improvement in performance, and stability. If the drive will be used by other operating systems, a more portable choice, such as msdosfs, is better. [source,bash] .... # dd if=/dev/zero of=/dev/da0 count=2 # gpart create -s GPT /dev/da0 # gpart add -t freebsd-ufs /dev/da0 .... Finally, create a new file system: [source,bash] .... # newfs /dev/da0p1 .... and mount it: [source,bash] .... # mount /dev/da0s1 /mnt .... It is a good idea to add a line to [.filename]#/etc/fstab# (see man:fstab[5]) so you can just type `mount /mnt` in the future: [.programlisting] .... /dev/da0p1 /mnt ufs rw,noauto 0 0 .... [[mount-cd-superblock]] === Why do I get Incorrect super block when mounting a CD? The type of device to mount must be specified. This is described in the Handbook section on link:{handbook}#mounting-cd[Using Data CDs]. [[cdrom-not-configured]] === Why do I get Device not configured when mounting a CD? This generally means that there is no CD in the drive, or the drive is not visible on the bus. Refer to the link:{handbook}#mounting-cd[Using Data CDs] section of the Handbook for a detailed discussion of this issue. [[cdrom-unicode-filenames]] === Why do all non-English characters in filenames show up as ? on my CDs when mounted in FreeBSD? The CD probably uses the "Joliet" extension for storing information about files and directories. This is discussed in the Handbook section on link:{handbook}#mounting-cd[Using Data CD-ROMs]. [[burncd-isofs]] === A CD burned under FreeBSD cannot be read under any other operating system. Why? This means a raw file was burned to the CD, rather than creating an ISO 9660 file system. Take a look at the Handbook section on link:{handbook}#mounting-cd[Using Data CDs]. [[copy-cd]] === How can I create an image of a data CD? This is discussed in the Handbook section on link:{handbook}#mkisofs[Writing Data to an ISO File System]. For more on working with CD-ROMs, see the link:{handbook}#creating-cds/[Creating CDs Section] in the Storage chapter in the Handbook. [[mount-audio-CD]] === Why can I not mount an audio CD? Trying to mount an audio CD will produce an error like `cd9660: /dev/cd0: Invalid argument`. This is because `mount` only works on file systems. Audio CDs do not have file systems; they just have data. Instead, use a program that reads audio CDs, such as the package:audio/xmcd[] package or port. [[multi-session-CD]] === How do I mount a multi-session CD? By default, man:mount[8] will attempt to mount the last data track (session) of a CD. To load an earlier session, use the `-s` command line argument. Refer to man:mount_cd9660[8] for specific examples. [[user-floppymount]] === How do I let ordinary users mount CD-ROMs, DVDs, USB drives, and other removable media? As `root` set the sysctl variable `vfs.usermount` to `1`. [source,bash] .... # sysctl vfs.usermount=1 .... To make this persist across reboots, add the line `vfs.usermount=1` to [.filename]#/etc/sysctl.conf# so that it is reset at system boot time. Users can only mount devices they have read permissions to. To allow users to mount a device permissions must be set in [.filename]#/etc/devfs.conf#. For example, to allow users to mount the first USB drive add: [.programlisting] .... # Allow all users to mount a USB drive. own /dev/da0 root:operator perm /dev/da0 0666 .... All users can now mount devices they could read onto a directory that they own: [source,bash] .... % mkdir ~/my-mount-point % mount -t msdosfs /dev/da0 ~/my-mount-point .... Unmounting the device is simple: [source,bash] .... % umount ~/my-mount-point .... Enabling `vfs.usermount`, however, has negative security implications. A better way to access MS-DOS(R) formatted media is to use the package:emulators/mtools[] package in the Ports Collection. [NOTE] ==== The device name used in the previous examples must be changed according to the configuration. ==== [[du-vs-df]] === The du and df commands show different amounts of disk space available. What is going on? This is due to how these commands actually work. `du` goes through the directory tree, measures how large each file is, and presents the totals. `df` just asks the file system how much space it has left. They seem to be the same thing, but a file without a directory entry will affect `df` but not `du`. When a program is using a file, and the file is deleted, the file is not really removed from the file system until the program stops using it. The file is immediately deleted from the directory listing, however. As an example, consider a file large enough to affect the output of `du` and `df`. A file being viewed with `more` can be deleted without causing an error. The entry is removed from the directory so no other program or user can access it. However, `du` shows that it is gone as it has walked the directory tree and the file is not listed. `df` shows that it is still there, as the file system knows that `more` is still using that space. Once the `more` session ends, `du` and `df` will agree. This situation is common on web servers. Many people set up a FreeBSD web server and forget to rotate the log files. The access log fills up [.filename]#/var#. The new administrator deletes the file, but the system still complains that the partition is full. Stopping and restarting the web server program would free the file, allowing the system to release the disk space. To prevent this from happening, set up man:newsyslog[8]. Note that Soft Updates can delay the freeing of disk space and it can take up to 30 seconds for the change to be visible. [[add-swap-space]] === How can I add more swap space? This section link:{handbook}#adding-swap-space/[of the Handbook] describes how to do this. [[manufacturer-disk-size]] === Why does FreeBSD see my disk as smaller than the manufacturer says it is? Disk manufacturers calculate gigabytes as a billion bytes each, whereas FreeBSD calculates them as 1,073,741,824 bytes each. This explains why, for example, FreeBSD's boot messages will report a disk that supposedly has 80 GB as holding 76,319 MB. Also note that FreeBSD will (by default) <> 8% of the disk space. [[disk-more-than-full]] === How is it possible for a partition to be more than 100% full? A portion of each UFS partition (8%, by default) is reserved for use by the operating system and the `root` user. man:df[1] does not count that space when calculating the `Capacity` column, so it can exceed 100%. Notice that the `Blocks` column is always greater than the sum of the `Used` and `Avail` columns, usually by a factor of 8%. For more details, look up `-m` in man:tunefs[8]. [[all-about-zfs]] == ZFS [[how-much-ram-for-zfs]] === What is the minimum amount of RAM one should have to run ZFS? A minimum of 4GB of RAM is required for comfortable usage, but individual workloads can vary widely. [[what-is-zil]] === What is the ZIL and when does it get used? The ZIL (ZFS intent log) is a write log used to implement posix write commitment semantics across crashes. Normally writes are bundled up into transaction groups and written to disk when filled ("Transaction Group Commit"). However syscalls like man:fsync[2] require a commitment that the data is written to stable storage before returning. The ZIL is needed for writes that have been acknowledged as written but which are not yet on disk as part of a transaction. The transaction groups are timestamped. In the event of a crash the last valid timestamp is found and missing data is merged in from the ZIL. [[need-ssd-for-zil]] === Do I need a SSD for ZIL? By default, ZFS stores the ZIL in the pool with all the data. If an application has a heavy write load, storing the ZIL in a separate device that has very fast synchronous, sequential write performance can improve overall system performance. For other workloads, a SSD is unlikely to make much of an improvement. [[what-is-l2arc]] === What is the L2ARC? The L2ARC is a read cache stored on a fast device such as an SSD. This cache is not persistent across reboots. Note that RAM is used as the first layer of cache and the L2ARC is only needed if there is insufficient RAM. L2ARC needs space in the ARC to index it. So, perversely, a working set that fits perfectly in the ARC will not fit perfectly any more if a L2ARC is used because part of the ARC is holding the L2ARC index, pushing part of the working set into the L2ARC which is slower than RAM. [[should-enable-dedup]] === Is enabling deduplication advisable? Generally speaking, no. Deduplication takes up a significant amount of RAM and may slow down read and write disk access times. Unless one is storing data that is very heavily duplicated, such as virtual machine images or user backups, it is possible that deduplication will do more harm than good. Another consideration is the inability to revert deduplication status. If data is written when deduplication is enabled, disabling dedup will not cause those blocks which were deduplicated to be replicated until they are next modified. Deduplication can also lead to some unexpected situations. In particular, deleting files may become much slower. [[zpool-fully-full]] === I cannot delete or create files on my ZFS pool. How can I fix this? This could happen because the pool is 100% full. ZFS requires space on the disk to write transaction metadata. To restore the pool to a usable state, truncate the file to delete: [source,bash] .... % truncate -s 0 unimportant-file .... File truncation works because a new transaction is not started, new spare blocks are created instead. [NOTE] ==== On systems with additional ZFS dataset tuning, such as deduplication, the space may not be immediately available ==== [[zfs-ssd-trim]] === Does ZFS support TRIM for Solid State Drives? ZFS TRIM support was added to FreeBSD 10-CURRENT with revision link:https://svnweb.freebsd.org/changeset/base/240868[r240868]. ZFS TRIM support was added to all FreeBSD-STABLE branches in link:https://svnweb.freebsd.org/changeset/base/252162[r252162] and link:https://svnweb.freebsd.org/changeset/base/251419[r251419], respectively. ZFS TRIM is enabled by default, and can be turned off by adding this line to [.filename]#/etc/sysctl.conf#: [.programlisting] .... vfs.zfs.trim.enabled=0 .... [NOTE] ==== ZFS TRIM support was added to GELI as of link:https://svnweb.freebsd.org/changeset/base/286444[r286444]. Please see man:geli[8] and the `-T` switch. ==== [[admin]] == System Administration [[startup-config-files]] === Where are the system start-up configuration files? The primary configuration file is [.filename]#/etc/defaults/rc.conf# which is described in man:rc.conf[5]. System startup scripts such as [.filename]#/etc/rc# and [.filename]#/etc/rc.d#, which are described in man:rc[8], include this file. _Do not edit this file!_ Instead, to edit an entry in [.filename]#/etc/defaults/rc.conf#, copy the line into [.filename]#/etc/rc.conf# and change it there. For example, if to start man:named[8], the included DNS server: [source,bash] .... # echo 'named_enable="YES"' >> /etc/rc.conf .... To start up local services, place shell scripts in the [.filename]#/usr/local/etc/rc.d# directory. These shell scripts should be set executable, the default file mode is `555`. [[adding-users]] === How do I add a user easily? Use the man:adduser[8] command, or the man:pw[8] command for more complicated situations. To remove the user, use the man:rmuser[8] command or, if necessary, man:pw[8]. [[root-not-found-cron-errors]] === Why do I keep getting messages like root: not found after editing /etc/crontab? This is normally caused by editing the system crontab. This is not the correct way to do things as the system crontab has a different format to the per-user crontabs. The system crontab has an extra field, specifying which user to run the command as. man:cron[8] assumes this user is the first word of the command to execute. Since no such command exists, this error message is displayed. To delete the extra, incorrect crontab: [source,bash] .... # crontab -r .... [[su-wheel-group]] === Why do I get the error, you are not in the correct group to su root when I try to su to root? This is a security feature. In order to `su` to `root`, or any other account with superuser privileges, the user account must be a member of the `wheel` group. If this feature were not there, anybody with an account on a system who also found out ``root``'s password would be able to gain superuser level access to the system. To allow someone to `su` to `root`, put them in the `wheel` group using `pw`: [source,bash] .... # pw groupmod wheel -m lisa .... The above example will add user `lisa` to the group `wheel`. [[rcconf-readonly]] === I made a mistake in rc.conf, or another startup file, and now I cannot edit it because the file system is read-only. What should I do? Restart the system using `boot -s` at the loader prompt to enter single-user mode. When prompted for a shell pathname, press kbd:[Enter] and run `mount -urw /` to re-mount the root file system in read/write mode. You may also need to run `mount -a -t ufs` to mount the file system where your favorite editor is defined. If that editor is on a network file system, either configure the network manually before mounting the network file systems, or use an editor which resides on a local file system, such as man:ed[1]. In order to use a full screen editor such as man:vi[1] or man:emacs[1], run `export TERM=xterm` so that these editors can load the correct data from the man:termcap[5] database. After performing these steps, edit [.filename]#/etc/rc.conf# to fix the syntax error. The error message displayed immediately after the kernel boot messages should indicate the number of the line in the file which is at fault. [[printer-setup]] === Why am I having trouble setting up my printer? See the link:{handbook}#printing/[Handbook entry on printing] for troubleshooting tips. [[keyboard-mappings]] === How can I correct the keyboard mappings for my system? Refer to the Handbook section on link:{handbook}#using-localization/[using localization], specifically the section on link:{handbook}#setting-console[console setup]. [[user-quotas]] === Why can I not get user quotas to work properly? . It is possible that the kernel is not configured to use quotas. In this case, add the following line to the kernel configuration file and recompile the kernel: + [.programlisting] .... options QUOTA .... + Refer to the link:{handbook}#quotas/[Handbook entry on quotas] for full details. . Do not turn on quotas on [.filename]#/#. . Put the quota file on the file system that the quotas are to be enforced on: + [.informaltable] [cols="1,1", frame="none", options="header"] |=== | File System | Quota file |[.filename]#/usr# |[.filename]#/usr/admin/quotas# |[.filename]#/home# |[.filename]#/home/admin/quotas# |... |... |=== [[sysv-ipc]] === Does FreeBSD support System V IPC primitives? Yes, FreeBSD supports System V-style IPC, including shared memory, messages and semaphores, in the [.filename]#GENERIC# kernel. With a custom kernel, support may be loaded with the [.filename]#sysvshm.ko#, [.filename]#sysvsem.ko# and [.filename]#sysvmsg.ko# kernel modules, or enabled in the custom kernel by adding the following lines to the kernel configuration file: [.programlisting] .... options SYSVSHM # enable shared memory options SYSVSEM # enable for semaphores options SYSVMSG # enable for messaging .... Recompile and install the kernel. [[sendmail-alternative]] === What other mail-server software can I use instead of Sendmail? The http://www.sendmail.org/[Sendmail] server is the default mail-server software for FreeBSD, but it can be replaced with another MTA installed from the Ports Collection. Available ports include package:mail/exim[], package:mail/postfix[], and package:mail/qmail[]. Search the mailing lists for discussions regarding the advantages and disadvantages of the available MTAs. [[forgot-root-pw]] === I have forgotten the root password! What do I do? Do not panic! Restart the system, type `boot -s` at the `Boot:` prompt to enter single-user mode. At the question about the shell to use, hit kbd:[Enter] which will display a # prompt. Enter `mount -urw /` to remount the root file system read/write, then run `mount -a` to remount all the file systems. Run `passwd root` to change the `root` password then run man:exit[1] to continue booting. [NOTE] ==== If you are still prompted to give the `root` password when entering the single-user mode, it means that the console has been marked as `insecure` in [.filename]#/etc/ttys#. In this case, it will be required to boot from a FreeBSD installation disk, choose the [.guimenuitem]#Live CD# or [.guimenuitem]#Shell# at the beginning of the install process and issue the commands mentioned above. Mount the specific partition in this case and then chroot to it. For example, replace `mount -urw /` with `mount /dev/ada0p1 /mnt; chroot /mnt` for a system on _ada0p1_. ==== [NOTE] ==== If the root partition cannot be mounted from single-user mode, it is possible that the partitions are encrypted and it is impossible to mount them without the access keys. For more information see the section about encrypted disks in the FreeBSD link:{handbook}#disks-encrypting/[Handbook]. ==== [[CAD-reboot]] === How do I keep kbd:[Control] + kbd:[Alt] + kbd:[Delete] from rebooting the system? When using man:vt[4], the default console driver, this can be done by setting the following man:sysctl[8]: [source,bash] .... # sysctl kern.vt.kbd_reboot=0 .... [[dos-to-unix-txt]] === How do I reformat DOS text files to UNIX(R) ones? Use this man:perl[1] command: [source,bash] .... % perl -i.bak -npe 's/\r\n/\n/g' file(s) .... where _file(s)_ is one or more files to process. The modification is done in-place, with the original file stored with a [.filename]#.bak# extension. Alternatively, use man:tr[1]: [source,bash] .... % tr -d '\r' < dos-text-file > unix-file .... _dos-text-file_ is the file containing DOS text while _unix-file_ will contain the converted output. This can be quite a bit faster than using `perl`. Yet another way to reformat DOS text files is to use the package:converters/dosunix[] port from the Ports Collection. Consult its documentation about the details. [[reread-rc]] === How do I re-read [.filename]#/etc/rc.conf# and re-start [.filename]#/etc/rc# without a reboot? Go into single-user mode and then back to multi-user mode: [source,bash] .... # shutdown now # return # exit .... [[release-candidate]] === I tried to update my system to the latest _-STABLE_, but got _-BETAx_, _-RC_ or __-PRERELEASE__! What is going on? Short answer: it is just a name. _RC_ stands for "Release Candidate". It signifies that a release is imminent. In FreeBSD, _-PRERELEASE_ is typically synonymous with the code freeze before a release. (For some releases, the _-BETA_ label was used in the same way as _-PRERELEASE_.) Long answer: FreeBSD derives its releases from one of two places. Major, dot-zero, releases, such as 9.0-RELEASE are branched from the head of the development stream, commonly referred to as <>. Minor releases, such as 6.3-RELEASE or 5.2-RELEASE, have been snapshots of the active <> branch. Starting with 4.3-RELEASE, each release also now has its own branch which can be tracked by people requiring an extremely conservative rate of development (typically only security advisories). When a release is about to be made, the branch from which it will be derived from has to undergo a certain process. Part of this process is a code freeze. When a code freeze is initiated, the name of the branch is changed to reflect that it is about to become a release. For example, if the branch used to be called 6.2-STABLE, its name will be changed to 6.3-PRERELEASE to signify the code freeze and signify that extra pre-release testing should be happening. Bug fixes can still be committed to be part of the release. When the source code is in shape for the release the name will be changed to 6.3-RC to signify that a release is about to be made from it. Once in the RC stage, only the most critical bugs found can be fixed. Once the release (6.3-RELEASE in this example) and release branch have been made, the branch will be renamed to 6.3-STABLE. For more information on version numbers and the various Subversion branches, refer to the link:{releng}[Release Engineering] article. [[kernel-chflag-failure]] === I tried to install a new kernel, and the man:chflags[1] failed. How do I get around this? Short answer: the security level is greater than 0. Reboot directly to single-user mode to install the kernel. Long answer: FreeBSD disallows changing system flags at security levels greater than 0. To check the current security level: [source,bash] .... # sysctl kern.securelevel .... The security level cannot be lowered in multi-user mode, so boot to single-user mode to install the kernel, or change the security level in [.filename]#/etc/rc.conf# then reboot. See the man:init[8] manual page for details on `securelevel`, and see [.filename]#/etc/defaults/rc.conf# and the man:rc.conf[5] manual page for more information on [.filename]#rc.conf#. [[kernel-securelevel-time]] === I cannot change the time on my system by more than one second! How do I get around this? Short answer: the system is at a security level greater than 1. Reboot directly to single-user mode to change the date. Long answer: FreeBSD disallows changing the time by more that one second at security levels greater than 1. To check the security level: [source,bash] .... # sysctl kern.securelevel .... The security level cannot be lowered in multi-user mode. Either boot to single-user mode to change the date or change the security level in [.filename]#/etc/rc.conf# and reboot. See the man:init[8] manual page for details on `securelevel`, and see [.filename]#/etc/defaults/rc.conf# and the man:rc.conf[5] manual page for more information on [.filename]#rc.conf#. [[statd-mem-leak]] === Why is rpc.statd using 256 MB of memory? No, there is no memory leak, and it is not using 256 MB of memory. For convenience, `rpc.statd` maps an obscene amount of memory into its address space. There is nothing terribly wrong with this from a technical standpoint; it just throws off things like man:top[1] and man:ps[1]. man:rpc.statd[8] maps its status file (resident on [.filename]#/var#) into its address space; to save worrying about remapping the status file later when it needs to grow, it maps the status file with a generous size. This is very evident from the source code, where one can see that the length argument to man:mmap[2] is `0x10000000`, or one sixteenth of the address space on an IA32, or exactly 256 MB. [[unsetting-schg]] === Why can I not unset the schg file flag? The system is running at securelevel greater than 0. Lower the securelevel and try again. For more information, see <> and the man:init[8] manual page. [[vnlru]] === What is vnlru? `vnlru` flushes and frees vnodes when the system hits the `kern.maxvnodes` limit. This kernel thread sits mostly idle, and only activates when there is a huge amount of RAM and users are accessing tens of thousands of tiny files. [[top-memory-states]] === What do the various memory states displayed by top mean? * `Active`: pages recently statistically used. * `Inactive`: pages recently statistically unused. * `Laundry`: pages recently statistically unused but known to be dirty, that is, whose contents needs to be paged out before they can be reused. * `Free`: pages without data content, which can be immediately reused. * `Wired`: pages that are fixed into memory, usually for kernel purposes, but also sometimes for special use in processes. Pages are most often written to disk (sort of a VM sync) when they are in the laundry state, but active or inactive pages can also be synced. This depends upon the CPU tracking of the modified bit being available, and in certain situations there can be an advantage for a block of VM pages to be synced, regardless of the queue they belong to. In most common cases, it is best to think of the laundry queue as a queue of relatively unused pages that might or might not be in the process of being written to disk. The inactive queue contains a mix of clean and dirty pages; clean pages near the head of the queue are reclaimed immediately to alleviate a free page shortage, and dirty pages are moved to the laundry queue for deferred processing. There are some other flags (e.g., busy flag or busy count) that might modify some of the described rules. [[free-memory-amount]] === How much free memory is available? There are a couple of kinds of "free memory". The most common is the amount of memory immediately available without reclaiming memory already in use. That is the size of the free pages queue plus some other reserved pages. This amount is exported by the `vm.stats.vm.v_free_count` man:sysctl[8], shown, for instance, by man:top[1]. Another kind of "free memory" is the total amount of virtual memory available to userland processes, which depends on the sum of swap space and usable memory. Other kinds of "free memory" descriptions are also possible, but it is relatively useless to define these, but rather it is important to make sure that the paging rate is kept low, and to avoid running out of swap space. [[var-empty]] === What is [.filename]#/var/empty#? [.filename]#/var/empty# is a directory that the man:sshd[8] program uses when performing privilege separation. The [.filename]#/var/empty# directory is empty, owned by `root` and has the `schg` flag set. This directory should not be deleted. [[newsyslog-expectations]] === I just changed [.filename]#/etc/newsyslog.conf#. How can I check if it does what I expect? To see what man:newsyslog[8] will do, use the following: [source,bash] .... % newsyslog -nrvv .... [[timezone]] === My time is wrong, how can I change the timezone? Use man:tzsetup[8]. [[X11]] == The X Window System and Virtual Consoles [[whatis-X]] === What is the X Window System? The X Window System (commonly `X11`) is the most widely available windowing system capable of running on UNIX(R) or UNIX(R) like systems, including FreeBSD. http://www.x.org/wiki/[The X.Org Foundation] administers the http://en.wikipedia.org/wiki/X_Window_System_core_protocol[X protocol standards], with the current reference implementation, version 11 release 7.7, so references are often shortened to `X11`. Many implementations are available for different architectures and operating systems. An implementation of the server-side code is properly known as an `X server`. [[running-X]] === I want to run Xorg, how do I go about it? To install Xorg do one of the following: Use the package:x11/xorg[] meta-port, which builds and installs every Xorg component. Use package:x11/xorg-minimal[], which builds and installs only the necessary Xorg components. Install Xorg from FreeBSD packages: [source,bash] .... # pkg install xorg .... After the installation of Xorg, follow the instructions from the link:{handbook}#x-config/[X11 Configuration] section of the FreeBSD Handbook. [[running-X-securelevels]] === I tried to run X, but I get a No devices detected. error when I type startx. What do I do now? The system is probably running at a raised `securelevel`. It is not possible to start X at a raised `securelevel` because X requires write access to man:io[4]. For more information, see at the man:init[8] manual page. There are two solutions to the problem: set the `securelevel` back down to zero or run man:xdm[1] (or an alternative display manager) at boot time before the `securelevel` is raised. See <> for more information about running man:xdm[1] at boot time. [[x-and-moused]] === Why does my mouse not work with X? When using man:vt[4], the default console driver, FreeBSD can be configured to support a mouse pointer on each virtual screen. To avoid conflicting with X, man:vt[4] supports a virtual device called [.filename]#/dev/sysmouse#. All mouse events received from the real mouse device are written to the man:sysmouse[4] device via man:moused[8]. To use the mouse on one or more virtual consoles, _and_ use X, see <> and set up man:moused[8]. Then edit [.filename]#/etc/X11/xorg.conf# and make sure the following lines exist: [.programlisting] .... Section "InputDevice" Option "Protocol" "SysMouse" Option "Device" "/dev/sysmouse" ..... .... Starting with Xorg version 7.4, the `InputDevice` sections in [.filename]#xorg.conf# are ignored in favor of autodetected devices. To restore the old behavior, add the following line to the `ServerLayout` or `ServerFlags` section: [.programlisting] .... Option "AutoAddDevices" "false" .... Some people prefer to use [.filename]#/dev/mouse# under X. To make this work, [.filename]#/dev/mouse# should be linked to [.filename]#/dev/sysmouse# (see man:sysmouse[4]) by adding the following line to [.filename]#/etc/devfs.conf# (see man:devfs.conf[5]): [.programlisting] .... link sysmouse mouse .... This link can be created by restarting man:devfs[5] with the following command (as `root`): [source,bash] .... # service devfs restart .... [[x-and-wheel]] === My mouse has a fancy wheel. Can I use it in X? Yes, if X is configured for a 5 button mouse. To do this, add the lines `Buttons 5` and `ZAxisMapping 4 5` to the "InputDevice" section of [.filename]#/etc/X11/xorg.conf#, as seen in this example: [.programlisting] .... Section "InputDevice" Identifier "Mouse1" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/sysmouse" Option "Buttons" "5" Option "ZAxisMapping" "4 5" EndSection .... The mouse can be enabled in Emacs by adding these lines to [.filename]#~/.emacs#: [.programlisting] .... ;; wheel mouse (global-set-key [mouse-4] 'scroll-down) (global-set-key [mouse-5] 'scroll-up) .... [[x-and-synaptic]] === My laptop has a Synaptics touchpad. Can I use it in X? Yes, after configuring a few things to make it work. In order to use the Xorg synaptics driver, first remove `moused_enable` from [.filename]#rc.conf#. To enable synaptics, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... hw.psm.synaptics_support="1" .... Add the following to [.filename]#/etc/X11/xorg.conf#: [.programlisting] .... Section "InputDevice" Identifier "Touchpad0" Driver "synaptics" Option "Protocol" "psm" Option "Device" "/dev/psm0" EndSection .... And be sure to add the following into the "ServerLayout" section: [.programlisting] .... InputDevice "Touchpad0" "SendCoreEvents" .... [[no-remote-x11]] === How do I use remote X displays? For security reasons, the default setting is to not allow a machine to remotely open a window. To enable this feature, start X with the optional `-listen_tcp` argument: [source,bash] .... % startx -listen_tcp .... [[virtual-console]] === What is a virtual console and how do I make more? Virtual consoles provide several simultaneous sessions on the same machine without doing anything complicated like setting up a network or running X. When the system starts, it will display a login prompt on the monitor after displaying all the boot messages. Type in your login name and password to start working on the first virtual console. To start another session, perhaps to look at documentation for a program or to read mail while waiting for an FTP transfer to finish, hold down kbd:[Alt] and press kbd:[F2]. This will display the login prompt for the second virtual console. To go back to the original session, press kbd:[Alt+F1]. The default FreeBSD installation has eight virtual consoles enabled. kbd:[Alt+F1], kbd:[Alt+F2], kbd:[Alt+F3], and so on will switch between these virtual consoles. To enable more of virtual consoles, edit [.filename]#/etc/ttys# (see man:ttys[5]) and add entries for [.filename]#ttyv8# to [.filename]#ttyvc#, after the comment on "Virtual terminals": [.programlisting] .... # Edit the existing entry for ttyv8 in /etc/ttys and change # "off" to "on". ttyv8 "/usr/libexec/getty Pc" xterm on secure ttyv9 "/usr/libexec/getty Pc" xterm on secure ttyva "/usr/libexec/getty Pc" xterm on secure ttyvb "/usr/libexec/getty Pc" xterm on secure .... The more virtual terminals, the more resources that are used. This can be problematic on systems with 8 MB RAM or less. Consider changing `secure` to `insecure`. [IMPORTANT] ==== In order to run an X server, at least one virtual terminal must be left to `off` for it to use. This means that only eleven of the Alt-function keys can be used as virtual consoles so that one is left for the X server. ==== For example, to run X and eleven virtual consoles, the setting for virtual terminal 12 should be: [.programlisting] .... ttyvb "/usr/libexec/getty Pc" xterm off secure .... The easiest way to activate the virtual consoles is to reboot. [[vty-from-x]] === How do I access the virtual consoles from X? Use kbd:[Ctrl+Alt+Fn] to switch back to a virtual console. Press kbd:[Ctrl+Alt+F1] to return to the first virtual console. Once at a text console, use kbd:[Alt+Fn] to move between them. To return to the X session, switch to the virtual console running X. If X was started from the command line using `startx`, the X session will attach to the next unused virtual console, not the text console from which it was invoked. For eight active virtual terminals, X will run on the ninth, so use kbd:[Alt+F9]. [[xdm-boot]] === How do I start XDM on boot? There are two schools of thought on how to start man:xdm[1]. One school starts `xdm` from [.filename]#/etc/ttys# (see man:ttys[5]) using the supplied example, while the other runs `xdm` from [.filename]#rc.local# (see man:rc[8]) or from an [.filename]#X# script in [.filename]#/usr/local/etc/rc.d#. Both are equally valid, and one may work in situations where the other does not. In both cases the result is the same: X will pop up a graphical login prompt. The man:ttys[5] method has the advantage of documenting which vty X will start on and passing the responsibility of restarting the X server on logout to man:init[8]. The man:rc[8] method makes it easy to `kill xdm` if there is a problem starting the X server. If loaded from man:rc[8], `xdm` should be started without any arguments. `xdm` must start _after_ man:getty[8] runs, or else `getty` and `xdm` will conflict, locking out the console. The best way around this is to have the script sleep 10 seconds or so then launch `xdm`. When starting `xdm` from [.filename]#/etc/ttys#, there still is a chance of conflict between `xdm` and man:getty[8]. One way to avoid this is to add the `vt` number in [.filename]#/usr/local/lib/X11/xdm/Xservers#: [.programlisting] .... :0 local /usr/local/bin/X vt4 .... The above example will direct the X server to run in [.filename]#/dev/ttyv3#. Note the number is offset by one. The X server counts the vty from one, whereas the FreeBSD kernel numbers the vty from zero. [[xconsole-failure]] === Why do I get Couldn't open console when I run xconsole? When X is started with `startx`, the permissions on [.filename]#/dev/console# will _not_ get changed, resulting in things like `xterm -C` and `xconsole` not working. This is because of the way console permissions are set by default. On a multi-user system, one does not necessarily want just any user to be able to write on the system console. For users who are logging directly onto a machine with a VTY, the man:fbtab[5] file exists to solve such problems. In a nutshell, make sure an uncommented line of the form is in [.filename]#/etc/fbtab# (see man:fbtab[5]): [.programlisting] .... /dev/ttyv0 0600 /dev/console .... It will ensure that whomever logs in on [.filename]#/dev/ttyv0# will own the console. [[ps2-x]] === Why does my PS/2 mouse misbehave under X? The mouse and the mouse driver may have become out of synchronization. In rare cases, the driver may also erroneously report synchronization errors: [.programlisting] .... psmintr: out of sync (xxxx != yyyy) .... If this happens, disable the synchronization check code by setting the driver flags for the PS/2 mouse driver to `0x100`. This can be easiest achieved by adding `hint.psm.0.flags="0x100"` to [.filename]#/boot/loader.conf# and rebooting. [[mouse-button-reverse]] === How do I reverse the mouse buttons? Type `xmodmap -e "pointer = 3 2 1"`. Add this command to [.filename]#~/.xinitrc# or [.filename]#~/.xsession# to make it happen automatically. [[install-splash]] === How do I install a splash screen and where do I find them? The detailed answer for this question can be found in the link:{handbook}#boot-splash/[Boot Time Splash Screens] section of the FreeBSD Handbook. [[windows-keys]] === Can I use the kbd:[Windows] keys on my keyboard in X? Yes. Use man:xmodmap[1] to define which functions the keys should perform. Assuming all Windows keyboards are standard, the keycodes for these three keys are the following: * 115 - kbd:[Windows] key, between the left-hand kbd:[Ctrl] and kbd:[Alt] keys * 116 - kbd:[Windows] key, to the right of kbd:[AltGr] * 117 - kbd:[Menu], to the left of the right-hand kbd:[Ctrl] To have the left kbd:[Windows] key print a comma, try this. [source,bash] .... # xmodmap -e "keycode 115 = comma" .... To have the kbd:[Windows] key-mappings enabled automatically every time X is started, either put the `xmodmap` commands in [.filename]#~/.xinitrc# or, preferably, create a [.filename]#~/.xmodmaprc# and include the `xmodmap` options, one per line, then add the following line to [.filename]#~/.xinitrc#: [.programlisting] .... xmodmap $HOME/.xmodmaprc .... For example, to map the 3 keys to be kbd:[F13], kbd:[F14], and kbd:[F15], respectively. This would make it easy to map them to useful functions within applications or the window manager. To do this, put the following in [.filename]#~/.xmodmaprc#. [.programlisting] .... keycode 115 = F13 keycode 116 = F14 keycode 117 = F15 .... For the package:x11-wm/fvwm2[] desktop manager, one could map the keys so that kbd:[F13] iconifies or de-iconifies the window the cursor is in, kbd:[F14] brings the window the cursor is in to the front or, if it is already at the front, pushes it to the back, and kbd:[F15] pops up the main Workplace menu even if the cursor is not on the desktop, which is useful when no part of the desktop is visible. The following entries in [.filename]#~/.fvwmrc# implement the aforementioned setup: [.programlisting] .... Key F13 FTIWS A Iconify Key F14 FTIWS A RaiseLower Key F15 A A Menu Workplace Nop .... [[x-3d-acceleration]] === How can I get 3D hardware acceleration for OpenGL(R)? The availability of 3D acceleration depends on the version of Xorg and the type of video chip. For an nVidia chip, use the binary drivers provided for FreeBSD by installing one of the following ports: The latest versions of nVidia cards are supported by the package:x11/nvidia-driver[] port. Older drivers are available as package:x11/nvidia-driver-[] nVidia provides detailed information on which card is supported by which driver on their web site: http://www.nvidia.com/object/IO_32667.html[http://www.nvidia.com/object/IO_32667.html]. For Matrox G200/G400, check the package:x11-drivers/xf86-video-mga[] port. For ATI Rage 128 and Radeon see man:ati[4], man:r128[4] and man:radeon[4]. [[networking]] == Networking [[diskless-booting]] === Where can I get information on diskless booting? "Diskless booting" means that the FreeBSD box is booted over a network, and reads the necessary files from a server instead of its hard disk. For full details, see link:{handbook}#network-diskless/[the Handbook entry on diskless booting]. [[router]] === Can a FreeBSD box be used as a dedicated network router? Yes. Refer to the Handbook entry on link:{handbook}#advanced-networking/[advanced networking], specifically the section on link:{handbook}#network-routing/[routing and gateways]. [[natd]] === Does FreeBSD support NAT or Masquerading? Yes. For instructions on how to use NAT over a PPP connection, see the link:{handbook}#userppp/[Handbook entry on PPP]. To use NAT over some other sort of network connection, look at the link:{handbook}#network-natd[natd] section of the Handbook. [[ethernet-aliases]] === How can I set up Ethernet aliases? If the alias is on the same subnet as an address already configured on the interface, add `netmask 0xffffffff` to this command: [source,bash] .... # ifconfig ed0 alias 192.0.2.2 netmask 0xffffffff .... Otherwise, specify the network address and netmask as usual: [source,bash] .... # ifconfig ed0 alias 172.16.141.5 netmask 0xffffff00 .... More information can be found in the FreeBSD link:{handbook}#configtuning-virtual-hosts/[Handbook]. [[nfs-linux]] === Why can I not NFS-mount from a Linux(R) box? Some versions of the Linux(R) NFS code only accept mount requests from a privileged port; try to issue the following command: [source,bash] .... # mount -o -P linuxbox:/blah /mnt .... [[exports-errors]] === Why does mountd keep telling me it can't change attributes and that I have a bad exports list on my FreeBSD NFS server? The most frequent problem is not understanding the correct format of [.filename]#/etc/exports#. Review man:exports[5] and the link:{handbook}#network-nfs/[NFS] entry in the Handbook, especially the section on link:{handbook}#configuring-nfs[configuring NFS]. [[ip-multicast]] === How do I enable IP multicast support? Install the package:net/mrouted[] package or port and add `mrouted_enable="YES"` to [.filename]#/etc/rc.conf# start this service at boot time. [[fqdn-hosts]] === Why do I have to use the FQDN for hosts on my site? See the answer in the FreeBSD link:{handbook}#mail-trouble/[Handbook]. [[network-permission-denied]] === Why do I get an error, Permission denied, for all networking operations? If the kernel is compiled with the `IPFIREWALL` option, be aware that the default policy is to deny all packets that are not explicitly allowed. If the firewall is unintentionally misconfigured, restore network operability by typing the following as `root`: [source,bash] .... # ipfw add 65534 allow all from any to any .... Consider setting `firewall_type="open"` in [.filename]#/etc/rc.conf#. For further information on configuring this firewall, see the link:{handbook}#firewalls-ipfw/[Handbook chapter]. [[ipfw-fwd]] === Why is my `ipfw` “fwd” rule to redirect a service to another machine not working? Possibly because network address translation (NAT) is needed instead of just forwarding packets. A "fwd" rule only forwards packets, it does not actually change the data inside the packet. Consider this rule: [source,bash] .... 01000 fwd 10.0.0.1 from any to foo 21 .... When a packet with a destination address of _foo_ arrives at the machine with this rule, the packet is forwarded to _10.0.0.1_, but it still has the destination address of _foo_. The destination address of the packet is not changed to _10.0.0.1_. Most machines would probably drop a packet that they receive with a destination address that is not their own. Therefore, using a "fwd" rule does not often work the way the user expects. This behavior is a feature and not a bug. See the <>, the man:natd[8] manual, or one of the several port redirecting utilities in the link:https://www.FreeBSD.org/ports/[Ports Collection] for a correct way to do this. [[service-redirect]] === How can I redirect service requests from one machine to another? FTP and other service requests can be redirected with the package:sysutils/socket[] package or port. Replace the entry for the service in [.filename]#/etc/inetd.conf# to call `socket`, as seen in this example for ftpd: [.programlisting] .... ftp stream tcp nowait nobody /usr/local/bin/socket socket ftp.example.com ftp .... where _ftp.example.com_ and _ftp_ are the host and port to redirect to, respectively. [[bandwidth-mgr-tool]] === Where can I get a bandwidth management tool? There are three bandwidth management tools available for FreeBSD. man:dummynet[4] is integrated into FreeBSD as part of man:ipfw[4]. http://www.sonycsl.co.jp/person/kjc/programs.html[ALTQ] has been integrated into FreeBSD as part of man:pf[4]. Bandwidth Manager from http://www.etinc.com/[Emerging Technologies] is a commercial product. [[bpf-not-configured]] === Why do I get /dev/bpf0: device not configured? The running application requires the Berkeley Packet Filter (man:bpf[4]), but it was removed from a custom kernel. Add this to the kernel config file and build a new kernel: [.programlisting] .... device bpf # Berkeley Packet Filter .... [[mount-smb-share]] === How do I mount a disk from a Windows(R) machine that is on my network, like smbmount in Linux(R)? Use the SMBFS toolset. It includes a set of kernel modifications and a set of userland programs. The programs and information are available as man:mount_smbfs[8] in the base system. [[icmp-response-bw-limit]] === What are these messages about: Limiting icmp/open port/closed port response in my log files? This kernel message indicates that some activity is provoking it to send a large amount of ICMP or TCP reset (RST) responses. ICMP responses are often generated as a result of attempted connections to unused UDP ports. TCP resets are generated as a result of attempted connections to unopened TCP ports. Among others, these are the kinds of activities which may cause these messages: * Brute-force denial of service (DoS) attacks (as opposed to single-packet attacks which exploit a specific vulnerability). * Port scans which attempt to connect to a large number of ports (as opposed to only trying a few well-known ports). The first number in the message indicates how many packets the kernel would have sent if the limit was not in place, and the second indicates the limit. This limit is controlled using `net.inet.icmp.icmplim`. This example sets the limit to `300` packets per second: [source,bash] .... # sysctl net.inet.icmp.icmplim=300 .... To disable these messages without disabling response limiting, use `net.inet.icmp.icmplim_output` to disable the output: [source,bash] .... # sysctl net.inet.icmp.icmplim_output=0 .... Finally, to disable response limiting completely, set `net.inet.icmp.icmplim` to `0`. Disabling response limiting is discouraged for the reasons listed above. [[unknown-hw-addr-format]] === What are these arp: unknown hardware address format error messages? This means that some device on the local Ethernet is using a MAC address in a format that FreeBSD does not recognize. This is probably caused by someone experimenting with an Ethernet card somewhere else on the network. This is most commonly seen on cable modem networks. It is harmless, and should not affect the performance of the FreeBSD system. [[arp-wrong-iface]] === Why do I keep seeing messages like: 192.168.0.10 is on fxp1 but got reply from 00:15:17:67:cf:82 on rl0, and how do I disable it? A packet is coming from outside the network unexpectedly. To disable them, set `net.link.ether.inet.log_arp_wrong_iface` to `0`. [[ipv6-only]] === How do I compile an IPv6 only kernel? Configure your kernel with these settings: [source,bash] .... include GENERIC ident GENERIC-IPV6ONLY makeoptions MKMODULESENV+="WITHOUT_INET_SUPPORT=" nooptions INET nodevice gre .... [[security]] == Security [[sandbox]] === What is a sandbox? "Sandbox" is a security term. It can mean two things: * A process which is placed inside a set of virtual walls that are designed to prevent someone who breaks into the process from being able to break into the wider system. + The process is only able to run inside the walls. Since nothing the process does in regards to executing code is supposed to be able to breach the walls, a detailed audit of its code is not needed in order to be able to say certain things about its security. + The walls might be a user ID, for example. This is the definition used in the man:security[7] and man:named[8] man pages. + Take the `ntalk` service, for example (see man:inetd[8]). This service used to run as user ID `root`. Now it runs as user ID `tty`. The `tty` user is a sandbox designed to make it more difficult for someone who has successfully hacked into the system via `ntalk` from being able to hack beyond that user ID. * A process which is placed inside a simulation of the machine. It means that someone who is able to break into the process may believe that he can break into the wider machine but is, in fact, only breaking into a simulation of that machine and not modifying any real data. + The most common way to accomplish this is to build a simulated environment in a subdirectory and then run the processes in that directory chrooted so that [.filename]#/# for that process is this directory, not the real [.filename]#/# of the system). + Another common use is to mount an underlying file system read-only and then create a file system layer on top of it that gives a process a seemingly writeable view into that file system. The process may believe it is able to write to those files, but only the process sees the effects - other processes in the system do not, necessarily. + An attempt is made to make this sort of sandbox so transparent that the user (or hacker) does not realize that he is sitting in it. UNIX(R) implements two core sandboxes. One is at the process level, and one is at the userid level. Every UNIX(R) process is completely firewalled off from every other UNIX(R) process. One process cannot modify the address space of another. A UNIX(R) process is owned by a particular userid. If the user ID is not the `root` user, it serves to firewall the process off from processes owned by other users. The user ID is also used to firewall off on-disk data. [[securelevel]] === What is securelevel? `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. To check the status of the securelevel on a running system: [source,bash] .... # 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. The securelevel of a running system cannot be lowered as this would defeat its purpose. If a task requires that the securelevel be non-positive, change the `kern_securelevel` and `kern_securelevel_enable` variables in [.filename]#/etc/rc.conf# and reboot. For more information on securelevel and the specific things all the levels do, consult man:init[8]. [WARNING] ==== Securelevel is not a silver bullet; it has many known deficiencies. More often than not, it provides a false sense of security. One of its biggest problems is that in order for it to be at all effective, all files used in the boot process up until the securelevel is set must be protected. If an attacker can get the system to execute their code prior to the securelevel being set (which happens quite late in the boot process since some things the system must do at start-up cannot be done at an elevated securelevel), its protections are invalidated. While this task of protecting all files used in the boot process is not technically impossible, if it is achieved, system maintenance will become a nightmare since one would have to take the system down, at least to single-user mode, to modify a configuration file. This point and others are often discussed on the mailing lists, particularly the {freebsd-security}. Search the archives link:https://www.FreeBSD.org/search/[here] for an extensive discussion. A more fine-grained mechanism is preferred. ==== [[toor-account]] === What is this UID 0 toor account? Have I been compromised? Do not worry. `toor` is an "alternative" superuser account, where toor is root spelled backwards. It is intended to be used with a non-standard shell so the default shell for `root` does not need to change. This is important as shells which are not part of the base distribution, but are instead installed from ports or packages, are installed in [.filename]#/usr/local/bin# which, by default, resides on a different file system. If ``root``'s shell is located in [.filename]#/usr/local/bin# and the file system containing [.filename]#/usr/local/bin#) is not mounted, `root` will not be able to log in to fix a problem and will have to reboot into single-user mode in order to enter the path to a shell. Some people use `toor` for day-to-day `root` tasks with a non-standard shell, leaving `root`, with a standard shell, for single-user mode or emergencies. By default, a user cannot log in using `toor` as it does not have a password, so log in as `root` and set a password for `toor` before using it to login. [[serial]] == Serial Communications This section answers common questions about serial communications with FreeBSD. [[serial-console-prompt]] === How do I get the boot: prompt to show on the serial console? See link:{handbook}#serialconsole-setup/[this section of the Handbook]. [[found-serial]] === How do I tell if FreeBSD found my serial ports or modem cards? As the FreeBSD kernel boots, it will probe for the serial ports for which the kernel is configured. Either watch the boot messages closely or run this command after the system is up and running: [source,bash] .... % grep -E '^(sio|uart)[0-9]' < /var/run/dmesg.boot sio0: <16550A-compatible COM port> port 0x3f8-0x3ff irq 4 flags 0x10 on acpi0 sio0: type 16550A sio1: <16550A-compatible COM port> port 0x2f8-0x2ff irq 3 on acpi0 sio1: type 16550A .... This example shows two serial ports. The first is on IRQ4, port address `0x3f8`, and has a 16550A-type UART chip. The second uses the same kind of chip but is on IRQ3 and is at port address `0x2f8`. Internal modem cards are treated just like serial ports, except that they always have a modem attached to the port. The [.filename]#GENERIC# kernel includes support for two serial ports using the same IRQ and port address settings in the above example. If these settings are not right for the system, or if there are more modem cards or serial ports than the kernel is configured for, reconfigure using the instructions in <> for more details. [[access-serial-ports]] === How do I access the serial ports on FreeBSD? (x86-specific) The third serial port, [.filename]#sio2#, or [.filename]#COM3#, is on [.filename]#/dev/cuad2# for dial-out devices, and on [.filename]#/dev/ttyd2# for dial-in devices. What is the difference between these two classes of devices? When opening [.filename]#/dev/ttydX# in blocking mode, a process will wait for the corresponding [.filename]#cuadX# device to become inactive, and then wait for the carrier detect line to go active. When the [.filename]#cuadX# device is opened, it makes sure the serial port is not already in use by the [.filename]#ttydX# device. If the port is available, it steals it from the [.filename]#ttydX# device. Also, the [.filename]#cuadX# device does not care about carrier detect. With this scheme and an auto-answer modem, remote users can log in and local users can still dial out with the same modem and the system will take care of all the conflicts. [[enable-multiport-serial]] === How do I enable support for a multi-port serial card? The section on kernel configuration provides information about configuring the kernel. For a multi-port serial card, place an man:sio[4] line for each serial port on the card in the man:device.hints[5] file. But place the IRQ specifiers on only one of the entries. All of the ports on the card should share one IRQ. For consistency, use the last serial port to specify the IRQ. Also, specify the following option in the kernel configuration file: [.programlisting] .... options COM_MULTIPORT .... The following [.filename]#/boot/device.hints# example is for an AST 4-port serial card on IRQ 12: [.programlisting] .... hint.sio.4.at="isa" hint.sio.4.port="0x2a0" hint.sio.4.flags="0x701" hint.sio.5.at="isa" hint.sio.5.port="0x2a8" hint.sio.5.flags="0x701" hint.sio.6.at="isa" hint.sio.6.port="0x2b0" hint.sio.6.flags="0x701" hint.sio.7.at="isa" hint.sio.7.port="0x2b8" hint.sio.7.flags="0x701" hint.sio.7.irq="12" .... The flags indicate that the master port has minor number `7` (`0x700`), and all the ports share an IRQ (`0x001`). [[default-serial-params]] === Can I set the default serial parameters for a port? See the link:{handbook}#serial/#serial-hw-config[Serial Communications] section in the FreeBSD Handbook. [[cannot-tip]] === Why can I not run tip or cu? The built-in man:tip[1] and man:cu[1] utilities can only access the [.filename]#/var/spool/lock# directory via user `uucp` and group `dialer`. Use the `dialer` group to control who has access to the modem or remote systems by adding user accounts to `dialer`. Alternatively, everyone can be configured to run man:tip[1] and man:cu[1] by typing: [source,bash] .... # chmod 4511 /usr/bin/cu # chmod 4511 /usr/bin/tip .... [[misc]] == Miscellaneous Questions [[more-swap]] === FreeBSD uses a lot of swap space even when the computer has free memory left. Why? FreeBSD will proactively move entirely idle, unused pages of main memory into swap in order to make more main memory available for active use. This heavy use of swap is balanced by using the extra free memory for caching. Note that while FreeBSD is proactive in this regard, it does not arbitrarily decide to swap pages when the system is truly idle. Thus, the system will not be all paged out after leaving it idle overnight. [[top-freemem]] === Why does top show very little free memory even when I have very few programs running? The simple answer is that free memory is wasted memory. Any memory that programs do not actively allocate is used within the FreeBSD kernel as disk cache. The values shown by man:top[1] labeled as `Inact` and `Laundry` are cached data at different aging levels. This cached data means the system does not have to access a slow disk again for data it has accessed recently, thus increasing overall performance. In general, a low value shown for `Free` memory in man:top[1] is good, provided it is not _very_ low. [[chmod-symlinks]] === Why will `chmod` not change the permissions on symlinks? Symlinks do not have permissions, and by default, man:chmod[1] will follow symlinks to change the permissions on the source file, if possible. For the file, [.filename]#foo# with a symlink named [.filename]#bar#, this command will always succeed. [source,bash] .... % chmod g-w bar .... However, the permissions on [.filename]#bar# will not have changed. When changing modes of the file hierarchies rooted in the files instead of the files themselves, use either `-H` or `-L` together with `-R` to make this work. See man:chmod[1] and man:symlink[7] for more information. [WARNING] ==== `-R` does a _recursive_ man:chmod[1]. Be careful about specifying directories or symlinks to directories to man:chmod[1]. To change the permissions of a directory referenced by a symlink, use man:chmod[1] without any options and follow the symlink with a trailing slash ([.filename]#/#). For example, if [.filename]#foo# is a symlink to directory [.filename]#bar#, to change the permissions of [.filename]#foo# (actually [.filename]#bar#), do something like: [source,bash] .... % chmod 555 foo/ .... With the trailing slash, man:chmod[1] will follow the symlink, [.filename]#foo#, to change the permissions of the directory, [.filename]#bar#. ==== [[dos-binaries]] === Can I run DOS binaries under FreeBSD? Yes. A DOS emulation program, package:emulators/doscmd[], is available in the FreeBSD Ports Collection. If doscmd will not suffice, package:emulators/pcemu[] emulates an 8088 and enough BIOS services to run many DOS text-mode applications. It requires the X Window System. The Ports Collection also has package:emulators/dosbox[]. The main focus of this application is emulating old DOS games using the local file system for files. [[translation]] === What do I need to do to translate a FreeBSD document into my native language? See the link:{fdp-primer}#translations/[Translation FAQ] in the FreeBSD Documentation Project Primer. [[freebsd-mail-bounces]] === Why does my email to any address at FreeBSD.org bounce? The `FreeBSD.org` mail system implements some Postfix checks on incoming mail and rejects mail that is either from misconfigured relays or otherwise appears likely to be spam. Some of the specific requirements are: * The IP address of the SMTP client must "reverse-resolve" to a forward confirmed hostname. * The fully-qualified hostname given in the SMTP conversation (either HELO or EHLO) must resolve to the IP address of the client. Other advice to help mail reach its destination include: * Mail should be sent in plain text, and messages sent to mailing lists should generally be no more than 200KB in length. * Avoid excessive cross posting. Choose _one_ mailing list which seems most relevant and send it there. If you still have trouble with email infrastructure at `FreeBSD.org`, send a note with the details to mailto:postmaster@freebsd.org[postmaster@freebsd.org]; Include a date/time interval so that logs may be reviewed - and note that we only keep one week's worth of mail logs. (Be sure to specify the time zone or offset from UTC.) [[free-account]] === Where can I find a free FreeBSD account? While FreeBSD does not provide open access to any of their servers, others do provide open access UNIX(R) systems. The charge varies and limited services may be available. http://www.arbornet.org/[Arbornet, Inc], also known as _M-Net_, has been providing open access to UNIX(R) systems since 1983. Starting on an Altos running System III, the site switched to BSD/OS in 1991. In June of 2000, the site switched again to FreeBSD. _M-Net_ can be accessed via telnet and SSH and provides basic access to the entire FreeBSD software suite. However, network access is limited to members and patrons who donate to the system, which is run as a non-profit organization. _M-Net_ also provides an bulletin board system and interactive chat. [[daemon-name]] === What is the cute little red guy's name? He does not have one, and is just called "the BSD daemon". If you insist upon using a name, call him "beastie". Note that "beastie" is pronounced "BSD". More about the BSD daemon is available on his http://www.mckusick.com/beastie/index.html[home page]. [[use-beastie]] === Can I use the BSD daemon image? Perhaps. The BSD daemon is copyrighted by Marshall Kirk McKusick. Check his http://www.mckusick.com/beastie/mainpage/copyright.html[Statement on the Use of the BSD Daemon Figure] for detailed usage terms. In summary, the image can be used in a tasteful manner, for personal use, so long as appropriate credit is given. Before using the logo commercially, contact {mckusick} for permission. More details are available on the http://www.mckusick.com/beastie/index.html[BSD Daemon's home page]. [[daemon-images]] === Do you have any BSD daemon images I could use? -Xfig and eps drawings are available under [.filename]#/usr/shared/examples/BSD_daemon/#. +Xfig and eps drawings are available under [.filename]#/usr/share/examples/BSD_daemon/#. [[glossary]] === I have seen an acronym or other term on the mailing lists and I do not understand what it means. Where should I look? Refer to the link:{handbook}#freebsd-glossary/[FreeBSD Glossary]. [[bikeshed-painting]] === Why should I care what color the bikeshed is? The really, really short answer is that you should not. The somewhat longer answer is that just because you are capable of building a bikeshed does not mean you should stop others from building one just because you do not like the color they plan to paint it. This is a metaphor indicating that you need not argue about every little feature just because you know enough to do so. Some people have commented that the amount of noise generated by a change is inversely proportional to the complexity of the change. The longer and more complete answer is that after a very long argument about whether man:sleep[1] should take fractional second arguments, {phk} posted a long message entitled link:http://www.bikeshed.com[A bike shed (any color will do) on greener grass...]. The appropriate portions of that message are quoted below. **** “What is it about this bike shed?” Some of you have asked me. It is a long story, or rather it is an old story, but it is quite short actually. C. Northcote Parkinson wrote a book in the early 1960s, called “Parkinson's Law”, which contains a lot of insight into the dynamics of management. [snip a bit of commentary on the book] In the specific example involving the bike shed, the other vital component is an atomic power-plant, I guess that illustrates the age of the book. Parkinson shows how you can go into the board of directors and get approval for building a multi-million or even billion dollar atomic power plant, but if you want to build a bike shed you will be tangled up in endless discussions. Parkinson explains that this is because an atomic plant is so vast, so expensive and so complicated that people cannot grasp it, and rather than try, they fall back on the assumption that somebody else checked all the details before it got this far. Richard P. Feynmann gives a couple of interesting, and very much to the point, examples relating to Los Alamos in his books. A bike shed on the other hand. Anyone can build one of those over a weekend, and still have time to watch the game on TV. So no matter how well prepared, no matter how reasonable you are with your proposal, somebody will seize the chance to show that he is doing his job, that he is paying attention, that he is here. In Denmark we call it “setting your fingerprint”. It is about personal pride and prestige, it is about being able to point somewhere and say “There! I did that.” It is a strong trait in politicians, but present in most people given the chance. Just think about footsteps in wet cement. --Poul-Henning Kamp on freebsd-hackers, October 2, 1999 **** [[funnies]] == The FreeBSD Funnies [[very-very-cool]] === How cool is FreeBSD? [qanda] Q::Has anyone done any temperature testing while running FreeBSD? I know Linux(R) runs cooler than DOS, but have never seen a mention of FreeBSD. It seems to run really hot. A:: No, but we have done numerous taste tests on blindfolded volunteers who have also had 250 micrograms of LSD-25 administered beforehand. 35% of the volunteers said that FreeBSD tasted sort of orange, whereas Linux(R) tasted like purple haze. Neither group mentioned any significant variances in temperature. We eventually had to throw the results of this survey out entirely anyway when we found that too many volunteers were wandering out of the room during the tests, thus skewing the results. We think most of the volunteers are at Apple now, working on their new "scratch and sniff" GUI. It is a funny old business we are in! Seriously, FreeBSD uses the HLT (halt) instruction when the system is idle thus lowering its energy consumption and therefore the heat it generates. Also if you have ACPI (Advanced Configuration and Power Interface) configured, then FreeBSD can also put the CPU into a low power mode. [[letmeoutofhere]] === Who is scratching in my memory banks?? [qanda] Q:: Is there anything "odd" that FreeBSD does when compiling the kernel which would cause the memory to make a scratchy sound? When compiling (and for a brief moment after recognizing the floppy drive upon startup, as well), a strange scratchy sound emanates from what appears to be the memory banks. A:: Yes! You will see frequent references to "daemons" in the BSD documentation, and what most people do not know is that this refers to genuine, non-corporeal entities that now possess your computer. The scratchy sound coming from your memory is actually high-pitched whispering exchanged among the daemons as they best decide how to deal with various system administration tasks. If the noise gets to you, a good `fdisk /mbr` from DOS will get rid of them, but do not be surprised if they react adversely and try to stop you. In fact, if at any point during the exercise you hear the satanic voice of Bill Gates coming from the built-in speaker, take off running and do not ever look back! Freed from the counterbalancing influence of the BSD daemons, the twin demons of DOS and Windows(R) are often able to re-assert total control over your machine to the eternal damnation of your soul. Now that you know, given a choice you would probably prefer to get used to the scratchy noises, no? [[changing-lightbulbs]] === How many FreeBSD hackers does it take to change a lightbulb? One thousand, one hundred and sixty-nine: Twenty-three to complain to -CURRENT about the lights being out; Four to claim that it is a configuration problem, and that such matters really belong on -questions; Three to submit PRs about it, one of which is misfiled under doc and consists only of "it's dark"; One to commit an untested lightbulb which breaks buildworld, then back it out five minutes later; Eight to flame the PR originators for not including patches in their PRs; Five to complain about buildworld being broken; Thirty-one to answer that it works for them, and they must have updated at a bad time; One to post a patch for a new lightbulb to -hackers; One to complain that he had patches for this three years ago, but when he sent them to -CURRENT they were just ignored, and he has had bad experiences with the PR system; besides, the proposed new lightbulb is non-reflexive; Thirty-seven to scream that lightbulbs do not belong in the base system, that committers have no right to do things like this without consulting the Community, and WHAT IS -CORE DOING ABOUT IT!? Two hundred to complain about the color of the bicycle shed; Three to point out that the patch breaks man:style[9]; Seventeen to complain that the proposed new lightbulb is under GPL; Five hundred and eighty-six to engage in a flame war about the comparative advantages of the GPL, the BSD license, the MIT license, the NPL, and the personal hygiene of unnamed FSF founders; Seven to move various portions of the thread to -chat and -advocacy; One to commit the suggested lightbulb, even though it shines dimmer than the old one; Two to back it out with a furious flame of a commit message, arguing that FreeBSD is better off in the dark than with a dim lightbulb; Forty-six to argue vociferously about the backing out of the dim lightbulb and demanding a statement from -core; Eleven to request a smaller lightbulb so it will fit their Tamagotchi if we ever decide to port FreeBSD to that platform; Seventy-three to complain about the SNR on -hackers and -chat and unsubscribe in protest; Thirteen to post "unsubscribe", "How do I unsubscribe?", or "Please remove me from the list", followed by the usual footer; One to commit a working lightbulb while everybody is too busy flaming everybody else to notice; Thirty-one to point out that the new lightbulb would shine 0.364% brighter if compiled with TenDRA (although it will have to be reshaped into a cube), and that FreeBSD should therefore switch to TenDRA instead of GCC; One to complain that the new lightbulb lacks fairings; Nine (including the PR originators) to ask "what is MFC?"; Fifty-seven to complain about the lights being out two weeks after the bulb has been changed. _{nik} adds:_ _I was laughing quite hard at this._ _And then I thought, "Hang on, shouldn't there be '1 to document it.' in that list somewhere?"_ _And then I was enlightened :-)_ _{tabthorpe}_ says: "None, _real_ FreeBSD hackers are not afraid of the dark!" [[dev-null]] === Where does data written to [.filename]#/dev/null# go? It goes into a special data sink in the CPU where it is converted to heat which is vented through the heatsink / fan assembly. This is why CPU cooling is increasingly important; as people get used to faster processors, they become careless with their data and more and more of it ends up in [.filename]#/dev/null#, overheating their CPUs. If you delete [.filename]#/dev/null# (which effectively disables the CPU data sink) your CPU may run cooler but your system will quickly become constipated with all that excess data and start to behave erratically. If you have a fast network connection you can cool down your CPU by reading data out of [.filename]#/dev/random# and sending it off somewhere; however you run the risk of overheating your network connection and [.filename]#/# or angering your ISP, as most of the data will end up getting converted to heat by their equipment, but they generally have good cooling, so if you do not overdo it you should be OK. _Paul Robinson adds:_ There are other methods. As every good sysadmin knows, it is part of standard practice to send data to the screen of interesting variety to keep all the pixies that make up your picture happy. Screen pixies (commonly mis-typed or re-named as "pixels") are categorized by the type of hat they wear (red, green or blue) and will hide or appear (thereby showing the color of their hat) whenever they receive a little piece of food. Video cards turn data into pixie-food, and then send them to the pixies - the more expensive the card, the better the food, so the better behaved the pixies are. They also need constant stimulation - this is why screen savers exist. To take your suggestions further, you could just throw the random data to console, thereby letting the pixies consume it. This causes no heat to be produced at all, keeps the pixies happy and gets rid of your data quite quickly, even if it does make things look a bit messy on your screen. Incidentally, as an ex-admin of a large ISP who experienced many problems attempting to maintain a stable temperature in a server room, I would strongly discourage people sending the data they do not want out to the network. The fairies who do the packet switching and routing get annoyed by it as well. [[punk-my-friend]] === My colleague sits at the computer too much, how can I prank her? Install package:games/sl[] and wait for her to mistype `sl` for `ls`. [[advanced]] == Advanced Topics [[learn-advanced]] === How can I learn more about FreeBSD's internals? See the link:{arch-handbook}[FreeBSD Architecture Handbook]. Additionally, much general UNIX(R) knowledge is directly applicable to FreeBSD. [[how-to-contribute]] === How can I contribute to FreeBSD? What can I do to help? We accept all types of contributions: documentation, code, and even art. See the article on link:{contributing}[Contributing to FreeBSD] for specific advice on how to do this. And thanks for the thought! [[define-snap-release]] === What are snapshots and releases? There are currently {rel-numbranch} active/semi-active branches in the FreeBSD http://svnweb.FreeBSD.org/base/[Subversion Repository]. (Earlier branches are only changed very rarely, which is why there are only {rel-numbranch} active branches of development): * {rel2-releng} AKA {rel2-stable} * {rel-releng} AKA {rel-stable} * {rel-head-releng} AKA _-CURRENT_ AKA {rel-head} `HEAD` is not an actual branch tag. It is a symbolic constant for the current, non-branched development stream known as _-CURRENT_. Right now, _-CURRENT_ is the {rel-head-relx} development stream; the {rel-stable} branch, {rel-releng}, forked off from _-CURRENT_ in {rel-relengdate} and the {rel2-stable} branch, {rel2-releng}, forked off from _-CURRENT_ in {rel2-relengdate}. [[kernel-panic-troubleshooting]] === How can I make the most of the data I see when my kernel panics? Here is typical kernel panic: [.programlisting] .... Fatal trap 12: page fault while in kernel mode fault virtual address = 0x40 fault code = supervisor read, page not present instruction pointer = 0x8:0xf014a7e5 stack pointer = 0x10:0xf4ed6f24 frame pointer = 0x10:0xf4ed6f28 code segment = base 0x0, limit 0xfffff, type 0x1b = DPL 0, pres 1, def32 1, gran 1 processor eflags = interrupt enabled, resume, IOPL = 0 current process = 80 (mount) interrupt mask = trap number = 12 panic: page fault .... This message is not enough. While the instruction pointer value is important, it is also configuration dependent as it varies depending on the kernel image. If it is a [.filename]#GENERIC# kernel image from one of the snapshots, it is possible for somebody else to track down the offending function, but for a custom kernel, only you can tell us where the fault occurred. To proceed: [.procedure] ==== . Write down the instruction pointer value. Note that the `0x8:` part at the beginning is not significant in this case: it is the `0xf0xxxxxx` part that we want. . When the system reboots, do the following: + [source,bash] .... % nm -n kernel.that.caused.the.panic | grep f0xxxxxx .... + where `f0xxxxxx` is the instruction pointer value. The odds are you will not get an exact match since the symbols in the kernel symbol table are for the entry points of functions and the instruction pointer address will be somewhere inside a function, not at the start. If you do not get an exact match, omit the last digit from the instruction pointer value and try again: + [source,bash] .... % nm -n kernel.that.caused.the.panic | grep f0xxxxx .... + If that does not yield any results, chop off another digit. Repeat until there is some sort of output. The result will be a possible list of functions which caused the panic. This is a less than exact mechanism for tracking down the point of failure, but it is better than nothing. ==== However, the best way to track down the cause of a panic is by capturing a crash dump, then using man:kgdb[1] to generate a stack trace on the crash dump. In any case, the method is this: [.procedure] ==== . Make sure that the following line is included in the kernel configuration file: + [.programlisting] .... makeoptions DEBUG=-g # Build kernel with gdb(1) debug symbols .... . Change to the [.filename]#/usr/src# directory: + [source,bash] .... # cd /usr/src .... . Compile the kernel: + [source,bash] .... # make buildkernel KERNCONF=MYKERNEL .... . Wait for man:make[1] to finish compiling. + [source,bash] .... # make installkernel KERNCONF=MYKERNEL .... . Reboot. ==== [NOTE] ==== If `KERNCONF` is not included, the [.filename]#GENERIC# kernel will instead be built and installed. ==== The man:make[1] process will have built two kernels. [.filename]#/usr/obj/usr/src/sys/MYKERNEL/kernel# and [.filename]#/usr/obj/usr/src/sys/MYKERNEL/kernel.debug#. [.filename]#kernel# was installed as [.filename]#/boot/kernel/kernel#, while [.filename]#kernel.debug# can be used as the source of debugging symbols for man:kgdb[1]. To capture a crash dump, edit [.filename]#/etc/rc.conf# and set `dumpdev` to point to either the swap partition or `AUTO`. This will cause the man:rc[8] scripts to use the man:dumpon[8] command to enable crash dumps. This command can also be run manually. After a panic, the crash dump can be recovered using man:savecore[8]; if `dumpdev` is set in [.filename]#/etc/rc.conf#, the man:rc[8] scripts will run man:savecore[8] automatically and put the crash dump in [.filename]#/var/crash#. [NOTE] ==== FreeBSD crash dumps are usually the same size as physical RAM. Therefore, make sure there is enough space in [.filename]#/var/crash# to hold the dump. Alternatively, run man:savecore[8] manually and have it recover the crash dump to another directory with more room. It is possible to limit the size of the crash dump by using `options MAXMEM=N` where _N_ is the size of kernel's memory usage in KBs. For example, for 1 GB of RAM, limit the kernel's memory usage to 128 MB, so that the crash dump size will be 128 MB instead of 1 GB. ==== Once the crash dump has been recovered , get a stack trace as follows: [source,bash] .... % kgdb /usr/obj/usr/src/sys/MYKERNEL/kernel.debug /var/crash/vmcore.0 (kgdb) backtrace .... Note that there may be several screens worth of information. Ideally, use man:script[1] to capture all of them. Using the unstripped kernel image with all the debug symbols should show the exact line of kernel source code where the panic occurred. The stack trace is usually read from the bottom up to trace the exact sequence of events that lead to the crash. man:kgdb[1] can also be used to print out the contents of various variables or structures to examine the system state at the time of the crash. [TIP] ==== If a second computer is available, man:kgdb[1] can be configured to do remote debugging, including setting breakpoints and single-stepping through the kernel code. ==== [NOTE] ==== If `DDB` is enabled and the kernel drops into the debugger, a panic and a crash dump can be forced by typing `panic` at the `ddb` prompt. It may stop in the debugger again during the panic phase. If it does, type `continue` and it will finish the crash dump. ==== [[dlsym-failure]] === Why has dlsym() stopped working for ELF executables? The ELF toolchain does not, by default, make the symbols defined in an executable visible to the dynamic linker. Consequently `dlsym()` searches on handles obtained from calls to `dlopen(NULL, flags)` will fail to find such symbols. To search, using `dlsym()`, for symbols present in the main executable of a process, link the executable using the `--export-dynamic` option to the ELF linker (man:ld[1]). [[change-kernel-address-space]] === How can I increase or reduce the kernel address space on i386? By default, the kernel address space is 1 GB (2 GB for PAE) for i386. When running a network-intensive server or using ZFS, this will probably not be enough. Add the following line to the kernel configuration file to increase available space and rebuild the kernel: [.programlisting] .... options KVA_PAGES=N .... To find the correct value of _N_, divide the desired address space size (in megabytes) by four. (For example, it is `512` for 2 GB.) [[acknowledgments]] == Acknowledgments This innocent little Frequently Asked Questions document has been written, rewritten, edited, folded, spindled, mutilated, eviscerated, contemplated, discombobulated, cogitated, regurgitated, rebuilt, castigated, and reinvigorated over the last decade, by a cast of hundreds if not thousands. Repeatedly. We wish to thank every one of the people responsible, and we encourage you to link:{contributing}[join them] in making this FAQ even better. diff --git a/documentation/content/en/books/fdp-primer/manual-pages/chapter.adoc b/documentation/content/en/books/fdp-primer/manual-pages/chapter.adoc index bc18d76671..915bf07fc7 100644 --- a/documentation/content/en/books/fdp-primer/manual-pages/chapter.adoc +++ b/documentation/content/en/books/fdp-primer/manual-pages/chapter.adoc @@ -1,488 +1,488 @@ --- title: Chapter 10. Manual Pages prev: books/fdp-primer/po-translations next: books/fdp-primer/writing-style --- [[manual-pages]] = Manual Pages :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 10 toc::[] [[manual-pages-introduction]] == Introduction _Manual pages_, commonly shortened to _man pages_, were conceived as readily-available reminders for command syntax, device driver details, or configuration file formats. They have become an extremely valuable quick-reference from the command line for users, system administrators, and programmers. Although intended as reference material rather than tutorials, the EXAMPLES sections of manual pages often provide detailed use case. Manual pages are generally shown interactively by the man:man[1] command. When the user types `man ls`, a search is performed for a manual page matching `ls`. The first matching result is displayed. [[manual-pages-sections]] == Sections Manual pages are grouped into _sections_. Each section contains manual pages for a specific category of documentation: [.informaltable] [cols="1,8", options="header"] |=== | Section Number | Category |1 |General Commands |2 |System Calls |3 |Library Functions |4 |Kernel Interfaces |5 |File Formats |6 |Games |7 |Miscellaneous |8 |System Manager |9 |Kernel Developer |=== [[manual-pages-markup]] == Markup Various markup forms and rendering programs have been used for manual pages. FreeBSD has used man:groff[7] and the newer man:mandoc[1]. Most existing FreeBSD manual pages, and all new ones, use the man:mdoc[7] form of markup. This is a simple line-based markup that is reasonably expressive. It is mostly semantic: parts of text are marked up for what they are, rather than for how they should appear when rendered. There is some appearance-based markup which is usually best avoided. Manual page source is usually interpreted and displayed to the screen interactively. The source files can be ordinary text files or compressed with man:gzip[1] to save space. Manual pages can also be rendered to other formats, including PostScript for printing or PDF generation. See man:man[1]. [[manual-pages-markup-sections]] === Manual Page Sections Manual pages are composed of several standard sections. Each section has a title in upper case, and the sections for a particular type of manual page appear in a specific order. For a category 1 General Command manual page, the sections are: [.informaltable] [cols="2,4", options="header"] |=== | Section Name | Description |NAME |Name of the command |SYNOPSIS |Format of options and arguments |DESCRIPTION |Description of purpose and usage |ENVIRONMENT |Environment settings that affect operation |EXIT STATUS |Error codes returned on exit |EXAMPLES |Examples of usage |COMPATIBILITY |Compatibility with other implementations |SEE ALSO |Cross-reference to related manual pages |STANDARDS |Compatibility with standards like POSIX |HISTORY |History of implementation |BUGS |Known bugs |AUTHORS |People who created the command or wrote the manual page. |=== Some sections are optional, and the combination of sections for a specific type of manual page vary. Examples of the most common types are shown later in this chapter. [[manual-pages-markup-macros]] === Macros man:mdoc[7] markup is based on _macros_. Lines that begin with a dot contain macro commands, each two or three letters long. For example, consider this portion of the man:ls[1] manual page: [.programlisting] .... .Dd December 1, 2015 .Dt LS 1 .Sh NAME .Nm ls .Nd list directory contents .Sh SYNOPSIS .Nm .Op Fl -libxo .Op Fl ABCFGHILPRSTUWZabcdfghiklmnopqrstuwxy1, .Op Fl D Ar format .Op Ar .Sh DESCRIPTION For each operand that names a .Ar file of a type other than directory, .Nm displays its name as well as any requested, associated information. For each operand that names a .Ar file of type directory, .Nm displays the names of files contained within that directory, as well as any requested, associated information. .... A _Document date_ and _Document title_ are defined. A _Section header_ for the NAME section is defined. Then the _Name_ of the command and a one-line _Name description_ are defined. The SYNOPSIS section begins. This section describes the command-line options and arguments accepted. _Name_ (`.Nm`) has already been defined, and repeating it here just displays the defined value in the text. An _Optional_ _Flag_ called `-libxo` is shown. The `Fl` macro adds a dash to the beginning of flags, so this appears in the manual page as `--libxo`. A long list of optional single-character flags are shown. An optional `-D` flag is defined. If the `-D` flag is given, it must be followed by an _Argument_. The argument is a _format_, a string that tells man:ls[1] what to display and how to display it. Details on the format string are given later in the manual page. A final optional argument is defined. Since no name is specified for the argument, the default of `file ...` is used. The _Section header_ for the DESCRIPTION section is defined. When rendered with the command `man ls`, the result displayed on the screen looks like this: [.programlisting] .... LS(1) FreeBSD General Commands Manual LS(1) NAME ls - list directory contents SYNOPSIS ls [--libxo] [-ABCFGHILPRSTUWZabcdfghiklmnopqrstuwxy1,] [-D format] [file ...] DESCRIPTION For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated information. For each operand that names a file of type directory, ls displays the names of files contained within that directory, as well as any requested, associated information. .... Optional values are shown inside square brackets. [[manual-pages-markup-guidelines]] === Markup Guidelines The man:mdoc[7] markup language is not very strict. For clarity and consistency, the FreeBSD Documentation project adds some additional style guidelines: Only the first letter of macros is upper case:: Always use upper case for the first letter of a macro and lower case for the remaining letters. Begin new sentences on new lines:: Start a new sentence on a new line, do not begin it on the same line as an existing sentence. Update `.Dd` when making non-trivial changes to a manual page:: The _Document date_ informs the reader about the last time the manual page was updated. It is important to update whenever non-trivial changes are made to the manual pages. Trivial changes like spelling or punctuation fixes that do not affect usage can be made without updating `.Dd`. Give examples:: Show the reader examples when possible. Even trivial examples are valuable, because what is trivial to the writer is not necessarily trivial to the reader. Three examples are a good goal. A trivial example shows the minimal requirements, a serious example shows actual use, and an in-depth example demonstrates unusual or non-obvious functionality. Include the BSD license:: Include the BSD license on new manual pages. The preferred license is available from the link:{committers-guide}[Committer's Guide]. [[manual-pages-markup-tricks]] === Markup Tricks Add a space before punctuation on a line with macros. Example: [.programlisting] .... .Sh SEE ALSO .Xr geom 4 , .Xr boot0cfg 8 , .Xr geom 8 , .Xr gptboot 8 .... Note how the commas at the end of the `.Xr` lines have been placed after a space. The `.Xr` macro expects two parameters to follow it, the name of an external manual page, and a section number. The space separates the punctuation from the section number. Without the space, the external links would incorrectly point to section `4,` or `8,`. [[manual-pages-markup-important-macros]] === Important Macros -Some very common macros will be shown here. For more usage examples, see man:mdoc[7], man:groff_mdoc[7], or search for actual use in [.filename]#/usr/shared/man/man*# directories. For example, to search for examples of the `.Bd`_Begin display_ macro: +Some very common macros will be shown here. For more usage examples, see man:mdoc[7], man:groff_mdoc[7], or search for actual use in [.filename]#/usr/share/man/man*# directories. For example, to search for examples of the `.Bd`_Begin display_ macro: [source,bash] .... % find /usr/share/man/man* | xargs zgrep '.Bd' .... [[manual-pages-markup-important-macros-organizational]] ==== Organizational Macros Some macros are used to define logical blocks of a manual page. [.informaltable] [cols="1,8", options="header"] |=== | Organizational Macro | Use |`.Sh` |Section header. Followed by the name of the section, traditionally all upper case. Think of these as chapter titles. |`.Ss` |Subsection header. Followed by the name of the subsection. Used to divide a `.Sh` section into subsections. |`.Bl` |Begin list. Start a list of items. |`.El` |End a list. |`.Bd` |Begin display. Begin a special area of text, like an indented area. |`.Ed` |End display. |=== [[manual-pages-markup-important-macros-inline]] ==== Inline Macros Many macros are used to mark up inline text. [.informaltable] [cols="1,8", options="header"] |=== | Inline Macro | Use |`.Nm` |Name. Called with a name as a parameter on the first use, then used later without the parameter to display the name that has already been defined. |`.Pa` |Path to a file. Used to mark up filenames and directory paths. |=== [[manual-pages-sample-structures]] == Sample Manual Page Structures This section shows minimal desired man page contents for several common categories of manual pages. [[manual-pages-sample-structures-section-1-8]] === Section 1 or 8 Command The preferred basic structure for a section 1 or 8 command: [.programlisting] .... .Dd August 25, 2017 .Dt EXAMPLECMD 8 .Os .Sh NAME .Nm examplecmd .Nd "command to demonstrate section 1 and 8 man pages" .Sh SYNOPSIS .Nm .Op Fl v .Sh DESCRIPTION The .Nm utility does nothing except demonstrate a trivial but complete manual page for a section 1 or 8 command. .Sh SEE ALSO .Xr exampleconf 5 .Sh AUTHORS .An Firstname Lastname Aq Mt flastname@example.com .... [[manual-pages-sample-structures-section-4]] === Section 4 Device Driver The preferred basic structure for a section 4 device driver: [.programlisting] .... .Dd August 25, 2017 .Dt EXAMPLEDRIVER 4 .Os .Sh NAME .Nm exampledriver .Nd "driver to demonstrate section 4 man pages" .Sh SYNOPSIS To compile this driver into the kernel, add this line to the kernel configuration file: .Bd -ragged -offset indent .Cd "device exampledriver" .Ed .Pp To load the driver as a module at boot, add this line to .Xr loader.conf 5 : .Bd -literal -offset indent exampledriver_load="YES" .Ed .Sh DESCRIPTION The .Nm driver provides an opportunity to show a skeleton or template file for section 4 manual pages. .Sh HARDWARE The .Nm driver supports these cards from the aptly-named Nonexistent Technologies: .Pp .Bl -bullet -compact .It NT X149.2 (single and dual port) .It NT X149.8 (single port) .El .Sh DIAGNOSTICS .Bl -diag .It "flashing green light" Something bad happened. .It "flashing red light" Something really bad happened. .It "solid black light" Power cord is unplugged. .El .Sh SEE ALSO .Xr example 8 .Sh HISTORY The .Nm device driver first appeared in .Fx 49.2 . .Sh AUTHORS .An Firstname Lastname Aq Mt flastname@example.com .... [[manual-pages-sample-structures-section-5]] === Section 5 Configuration File The preferred basic structure for a section 5 configuration file: [.programlisting] .... .Dd August 25, 2017 .Dt EXAMPLECONF 5 .Os .Sh NAME .Nm example.conf .Nd "config file to demonstrate section 5 man pages" .Sh DESCRIPTION .Nm is an example configuration file. .Sh SEE ALSO .Xr example 8 .Sh AUTHORS .An Firstname Lastname Aq Mt flastname@example.com .... [[manual-pages-testing]] == Testing Testing a new manual page can be challenging. Fortunately there are some tools that can assist in the task. Some of them, like man:man[1], do not look in the current directory. It is a good idea to prefix the filename with `./` if the new manual page is in the current directory. An absolute path can also be used. Use man:mandoc[1]'s linter to check for parsing errors: [source,bash] .... % mandoc -T lint ./mynewmanpage.8 .... Use package:textproc/igor[] to proofread the manual page: [source,bash] .... % igor ./mynewmanpage.8 .... Use man:man[1] to check the final result of your changes: [source,bash] .... % man ./mynewmanpage.8 .... You can use man:col[1] to filter the output of man:man[1] and get rid of the backspace characters before loading the result in your favorite editor for spell checking: [source,bash] .... % man ./mynewmanpage.8 | col -b | vim -R - .... Spell-checking with fully-featured dictionaries is encouraged, and can be accomplished by using package:textproc/hunspell[] or package:textproc/aspell[] combined with package:textproc/en-hunspell[] or package:textproc/en-aspell[], respectively. For instance: [source,bash] .... % aspell check --lang=en --mode=nroff ./mynewmanpage.8 .... [[manual-pages-examples-as-templates]] == Example Manual Pages to Use as Templates Some manual pages are suitable as in-depth examples. [.informaltable] [cols="1,4", options="header"] |=== | Manual Page | Path to Source Location |man:cp[1] |[.filename]#/usr/src/bin/cp/cp.1# |man:vt[4] |[.filename]#/usr/src/share/man/man4/vt.4# |man:crontab[5] |[.filename]#/usr/src/usr.sbin/cron/crontab/crontab.5# |man:gpart[8] |[.filename]#/usr/src/sbin/geom/class/part/gpart.8# |=== [[manual-pages-resources]] == Resources Resources for manual page writers: * man:man[1] * man:mandoc[1] * man:groff_mdoc[7] * http://manpages.bsd.lv/mdoc.html[Practical UNIX Manuals: mdoc] * http://manpages.bsd.lv/history.html[History of UNIX Manpages] diff --git a/documentation/content/en/books/fdp-primer/translations/chapter.adoc b/documentation/content/en/books/fdp-primer/translations/chapter.adoc index 117a0e8f0e..795df33834 100644 --- a/documentation/content/en/books/fdp-primer/translations/chapter.adoc +++ b/documentation/content/en/books/fdp-primer/translations/chapter.adoc @@ -1,205 +1,205 @@ --- title: Chapter 8. Translations prev: books/fdp-primer/rosetta next: books/fdp-primer/po-translations --- [[translations]] = Translations :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 8 include::shared/en/teams.adoc[] include::shared/en/mailing-lists.adoc[] toc::[] This is the FAQ for people translating the FreeBSD documentation (FAQ, Handbook, tutorials, manual pages, and others) to different languages. It is _very_ heavily based on the translation FAQ from the FreeBSD German Documentation Project, originally written by Frank Gründer mailto:elwood@mc5sys.in-berlin.de[elwood@mc5sys.in-berlin.de] and translated back to English by Bernd Warken mailto:bwarken@mayn.de[bwarken@mayn.de]. == What do i18n and l10n mean? i18n means internationalization and l10n means localization. They are just a convenient shorthand. i18n can be read as "i" followed by 18 letters, followed by "n". Similarly, l10n is "l" followed by 10 letters, followed by "n". == Is there a mailing list for translators? Yes. Different translation groups have their own mailing lists. The https://www.freebsd.org/docproj/translations[list of translation projects] has more information about the mailing lists and web sites run by each translation project. In addition there is mailto:freebsd-translators@freebsd.org[freebsd-translators@freebsd.org] for general translation discussion. == Are more translators needed? Yes. The more people that work on translation the faster it gets done, and the faster changes to the English documentation are mirrored in the translated documents. You do not have to be a professional translator to be able to help. == What languages do I need to know? Ideally, you will have a good knowledge of written English, and obviously you will need to be fluent in the language you are translating to. English is not strictly necessary. For example, you could do a Hungarian translation of the FAQ from the Spanish translation. == What software do I need to know? It is strongly recommended that you maintain a local copy of the FreeBSD Git repository (at least the documentation part). This can be done by running: [source,bash] .... % git clone https://cgit.FreeBSD.org/doc.git doc .... https://cgit.FreeBSD.org/[cgit.FreeBSD.org] is a public `git` server. [NOTE] ==== This will require the package:git-lite[] package to be installed. ==== You should be comfortable using git. This will allow you to see what has changed between different versions of the files that make up the documentation. For example, to view the differences between revisions `r33733` and `r33734` of [.filename]#content/en/books/fdp-primer/book.adoc#, run: [source,bash] .... % git diff -r33733:33734 content/en/books/fdp-primer/book.adoc .... Please see the complete explanation of using Git in FreeBSD in the link:{handbook}[FreeBSD Handbook]. == How do I find out who else might be translating to the same language? The https://www.FreeBSD.org/docproj/translations/[Documentation Project translations page] lists the translation efforts that are currently known about. If others are already working on translating documentation to your language, please do not duplicate their efforts. Instead, contact them to see how you can help. If no one is listed on that page as translating for your language, then send a message to the {freebsd-doc} in case someone else is thinking of doing a translation, but has not announced it yet. == No one else is translating to my language. What do I do? Congratulations, you have just started the "FreeBSD _your-language-here_ Documentation Translation Project". Welcome aboard. First, decide whether or not you have got the time to spare. Since you are the only person working on your language at the moment it is going to be your responsibility to publicize your work and coordinate any volunteers that might want to help you. Write an email to the Documentation Project mailing list, announcing that you are going to translate the documentation, so the Documentation Project translations page can be maintained. If there is already someone in your country providing FreeBSD mirroring services you should contact them and ask if you can have some webspace for your project, and possibly an email address or mailing list services. Then pick a document and start translating. It is best to start with something fairly small - either the FAQ, or one of the tutorials. == I have translated some documentation, where do I send it? That depends. If you are already working with a translation team (such as the Japanese team, or the German team) then they will have their own procedures for handling submitted documentation, and these will be outlined on their web pages. If you are the only person working on a particular language (or you are responsible for a translation project and want to submit your changes back to the FreeBSD project) then you should send your translation to the FreeBSD project (see the next question). == I am the only person working on translating to this language, how do I submit my translation? First, make sure your translation is organized properly. This means that it should drop into the existing documentation tree and build straight away. -Currently, the FreeBSD documentation is stored in a top level directory called [.filename]#head/#. Directories below this are named according to the language code they are written in, as defined in ISO639 ([.filename]#/usr/shared/misc/iso639# on a version of FreeBSD newer than 20th January 1999). +Currently, the FreeBSD documentation is stored in a top level directory called [.filename]#head/#. Directories below this are named according to the language code they are written in, as defined in ISO639 ([.filename]#/usr/share/misc/iso639# on a version of FreeBSD newer than 20th January 1999). If your language can be encoded in different ways (for example, Chinese) then there should be directories below this, one for each encoding format you have provided. Finally, you should have directories for each document. For example, a hypothetical Swedish translation might look like: [.programlisting] .... head/ content/ sv/ books/ faq/ book.adoc .... `sv` is the name of the translation, in [.filename]#lang# form. Note the two Makefiles, which will be used to build the documentation. Use man:tar[1] and man:gzip[1] to compress up your documentation, and send it to the project. [source,bash] .... % cd doc % tar cf swedish-docs.tar sv % gzip -9 swedish-docs.tar .... Put [.filename]#swedish-docs.tar.gz# somewhere. If you do not have access to your own webspace (perhaps your ISP does not let you have any) then you can email {doceng}, and arrange to email the files when it is convenient. Either way, you should use Bugzilla to submit a report indicating that you have submitted the documentation. It would be very helpful if you could get other people to look over your translation and double check it first, since it is unlikely that the person committing it will be fluent in the language. Someone (probably the Documentation Project Manager, currently {doceng}) will then take your translation and confirm that it builds. In particular, the following things will be looked at: . Does `make` in the [.filename]#root# directory work correctly? If there are any problems then whoever is looking at the submission will get back to you to work them out. If there are no problems your translation will be committed as soon as possible. == Can I include language or country specific text in my translation? We would prefer that you did not. For example, suppose that you are translating the Handbook to Korean, and want to include a section about retailers in Korea in your Handbook. There is no real reason why that information should not be in the English (or German, or Spanish, or Japanese, or ...) versions as well. It is feasible that an English speaker in Korea might try to pick up a copy of FreeBSD whilst over there. It also helps increase FreeBSD's perceived presence around the globe, which is not a bad thing. If you have country specific information, please submit it as a change to the English Handbook (using Bugzilla) and then translate the change back to your language in the translated Handbook. Thanks. === Addressing the reader In the English documents, the reader is addressed as "you", there is no formal/informal distinction as there is in some languages. If you are translating to a language which does distinguish, use whichever form is typically used in other technical documentation in your language. If in doubt, use a mildly polite form. === Do I need to include any additional information in my translations? Yes. The header of the English version of each document will look something like this: [.programlisting] .... --- title: Why you should use a BSD style license for your Open Source Project releaseinfo: "$FreeBSD: head/en_US.ISO8859-1/articles/bsdl-gpl/article.xml 53942 2020-03-01 12:23:40Z carlavilla $" trademarks: ["freebsd", "intel", "general"] --- = Why you should use a BSD style license for your Open Source Project .... The exact boilerplate may change, but it will always include a $FreeBSD$ line and the phrase `The FreeBSD Documentation Project`. Note that the $FreeBSD$ part is expanded automatically by Git, so it should be empty (just `$FreeBSD$`) for new files. Your translated documents should include their own FreeBSD line, and change the `FreeBSD Documentation Project` line to `The FreeBSD _language_ Documentation Project`. In addition, you should add a third line which indicates which revision of the English text this is based on. So, the Spanish version of this file might start: [.programlisting] .... --- title: Soporte para segundos intercalares en FreeBSD releaseinfo: "$FreeBSD: head/es_ES.ISO8859-1/articles/leap-seconds/article.xml 53090 2019-06-01 17:52:59Z carlavilla $" --- = Soporte para segundos intercalares en FreeBSD .... diff --git a/documentation/content/en/books/handbook/advanced-networking/_index.adoc b/documentation/content/en/books/handbook/advanced-networking/_index.adoc index 28c608f755..3d2306d21c 100644 --- a/documentation/content/en/books/handbook/advanced-networking/_index.adoc +++ b/documentation/content/en/books/handbook/advanced-networking/_index.adoc @@ -1,2821 +1,2821 @@ --- title: Chapter 32. Advanced Networking part: IV. Network Communication prev: books/handbook/firewalls next: books/handbook/partv --- [[advanced-networking]] = Advanced Networking :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 32 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/advanced-networking/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/advanced-networking/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/advanced-networking/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[advanced-networking-synopsis]] == Synopsis This chapter covers a number of advanced networking topics. After reading this chapter, you will know: * The basics of gateways and routes. * How to set up USB tethering. * How to set up IEEE(R) 802.11 and Bluetooth(R) devices. * How to make FreeBSD act as a bridge. * How to set up network PXE booting. * How to set up IPv6 on a FreeBSD machine. * How to enable and utilize the features of the Common Address Redundancy Protocol (CARP) in FreeBSD. * How to configure multiple VLANs on FreeBSD. * Configure bluetooth headset. Before reading this chapter, you should: * Understand the basics of the [.filename]#/etc/rc# scripts. * Be familiar with basic network terminology. * Know how to configure and install a new FreeBSD kernel (crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]). * Know how to install additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [[network-routing]] == Gateways and Routes _Routing_ is the mechanism that allows a system to find the network path to another system. A _route_ is a defined pair of addresses which represent the "destination" and a "gateway". The route indicates that when trying to get to the specified destination, send the packets through the specified gateway. There are three types of destinations: individual hosts, subnets, and "default". The "default route" is used if no other routes apply. There are also three types of gateways: individual hosts, interfaces, also called links, and Ethernet hardware (MAC) addresses. Known routes are stored in a routing table. This section provides an overview of routing basics. It then demonstrates how to configure a FreeBSD system as a router and offers some troubleshooting tips. [[network-routing-default]] === Routing Basics To view the routing table of a FreeBSD system, use man:netstat[1]: [source,bash] .... % netstat -r Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default outside-gw UGS 37 418 em0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 re0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 .... The entries in this example are as follows: default:: The first route in this table specifies the `default` route. When the local system needs to make a connection to a remote host, it checks the routing table to determine if a known path exists. If the remote host matches an entry in the table, the system checks to see if it can connect using the interface specified in that entry. + If the destination does not match an entry, or if all known paths fail, the system uses the entry for the default route. For hosts on a local area network, the `Gateway` field in the default route is set to the system which has a direct connection to the Internet. When reading this entry, verify that the `Flags` column indicates that the gateway is usable (`UG`). + The default route for a machine which itself is functioning as the gateway to the outside world will be the gateway machine at the Internet Service Provider (ISP). localhost:: The second route is the `localhost` route. The interface specified in the `Netif` column for `localhost` is [.filename]#lo0#, also known as the loopback device. This indicates that all traffic for this destination should be internal, rather than sending it out over the network. MAC address:: The addresses beginning with `0:e0:` are MAC addresses. FreeBSD will automatically identify any hosts, `test0` in the example, on the local Ethernet and add a route for that host over the Ethernet interface, [.filename]#re0#. This type of route has a timeout, seen in the `Expire` column, which is used if the host does not respond in a specific amount of time. When this happens, the route to this host will be automatically deleted. These hosts are identified using the Routing Information Protocol (RIP), which calculates routes to local hosts based upon a shortest path determination. subnet:: FreeBSD will automatically add subnet routes for the local subnet. In this example, `10.20.30.255` is the broadcast address for the subnet `10.20.30` and `example.com` is the domain name associated with that subnet. The designation `link#1` refers to the first Ethernet card in the machine. + Local network hosts and local subnets have their routes automatically configured by a daemon called man:routed[8]. If it is not running, only routes which are statically defined by the administrator will exist. host:: The `host1` line refers to the host by its Ethernet address. Since it is the sending host, FreeBSD knows to use the loopback interface ([.filename]#lo0#) rather than the Ethernet interface. + The two `host2` lines represent aliases which were created using man:ifconfig[8]. The `=>` symbol after the [.filename]#lo0# interface says that an alias has been set in addition to the loopback address. Such routes only show up on the host that supports the alias and all other hosts on the local network will have a `link#1` line for such routes. 224:: The final line (destination subnet `224`) deals with multicasting. Various attributes of each route can be seen in the `Flags` column. <> summarizes some of these flags and their meanings: [[routeflags]] .Commonly Seen Routing Table Flags [cols="1,1", frame="none", options="header"] |=== | Command | Purpose |U |The route is active (up). |H |The route destination is a single host. |G |Send anything for this destination on to this gateway, which will figure out from there where to send it. |S |This route was statically configured. |C |Clones a new route based upon this route for machines to connect to. This type of route is normally used for local networks. |W |The route was auto-configured based upon a local area network (clone) route. |L |Route involves references to Ethernet (link) hardware. |=== On a FreeBSD system, the default route can defined in [.filename]#/etc/rc.conf# by specifying the IP address of the default gateway: [.programlisting] .... defaultrouter="10.20.30.1" .... It is also possible to manually add the route using `route`: [source,bash] .... # route add default 10.20.30.1 .... Note that manually added routes will not survive a reboot. For more information on manual manipulation of network routing tables, refer to man:route[8]. [[network-static-routes]] === Configuring a Router with Static Routes A FreeBSD system can be configured as the default gateway, or router, for a network if it is a dual-homed system. A dual-homed system is a host which resides on at least two different networks. Typically, each network is connected to a separate network interface, though IP aliasing can be used to bind multiple addresses, each on a different subnet, to one physical interface. In order for the system to forward packets between interfaces, FreeBSD must be configured as a router. Internet standards and good engineering practice prevent the FreeBSD Project from enabling this feature by default, but it can be configured to start at boot by adding this line to [.filename]#/etc/rc.conf#: [.programlisting] .... gateway_enable="YES" # Set to YES if this host will be a gateway .... To enable routing now, set the man:sysctl[8] variable `net.inet.ip.forwarding` to `1`. To stop routing, reset this variable to `0`. The routing table of a router needs additional routes so it knows how to reach other networks. Routes can be either added manually using static routes or routes can be automatically learned using a routing protocol. Static routes are appropriate for small networks and this section describes how to add a static routing entry for a small network. [NOTE] ==== For large networks, static routes quickly become unscalable. FreeBSD comes with the standard BSD routing daemon man:routed[8], which provides the routing protocols RIP, versions 1 and 2, and IRDP. Support for the BGP and OSPF routing protocols can be installed using the package:net/zebra[] package or port. ==== Consider the following network: image::static-routes.png[] In this scenario, `RouterA` is a FreeBSD machine that is acting as a router to the rest of the Internet. It has a default route set to `10.0.0.1` which allows it to connect with the outside world. `RouterB` is already configured to use `192.168.1.1` as its default gateway. Before adding any static routes, the routing table on `RouterA` looks like this: [source,bash] .... % netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0.0/24 link#1 UC 0 0 xl0 192.168.1.0/24 link#2 UC 0 0 xl1 .... With the current routing table, `RouterA` does not have a route to the `192.168.2.0/24` network. The following command adds the `Internal Net 2` network to ``RouterA``'s routing table using `192.168.1.2` as the next hop: [source,bash] .... # route add -net 192.168.2.0/24 192.168.1.2 .... Now, `RouterA` can reach any host on the `192.168.2.0/24` network. However, the routing information will not persist if the FreeBSD system reboots. If a static route needs to be persistent, add it to [.filename]#/etc/rc.conf#: [.programlisting] .... # Add Internal Net 2 as a persistent static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" .... The `static_routes` configuration variable is a list of strings separated by a space, where each string references a route name. The variable `route_internalnet2` contains the static route for that route name. Using more than one string in `static_routes` creates multiple static routes. The following shows an example of adding static routes for the `192.168.0.0/24` and `192.168.1.0/24` networks: [.programlisting] .... static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" .... [[network-routing-troubleshooting]] === Troubleshooting When an address space is assigned to a network, the service provider configures their routing tables so that all traffic for the network will be sent to the link for the site. But how do external sites know to send their packets to the network's ISP? There is a system that keeps track of all assigned address spaces and defines their point of connection to the Internet backbone, or the main trunk lines that carry Internet traffic across the country and around the world. Each backbone machine has a copy of a master set of tables, which direct traffic for a particular network to a specific backbone carrier, and from there down the chain of service providers until it reaches a particular network. It is the task of the service provider to advertise to the backbone sites that they are the point of connection, and thus the path inward, for a site. This is known as route propagation. Sometimes, there is a problem with route propagation and some sites are unable to connect. Perhaps the most useful command for trying to figure out where routing is breaking down is `traceroute`. It is useful when `ping` fails. When using `traceroute`, include the address of the remote host to connect to. The output will show the gateway hosts along the path of the attempt, eventually either reaching the target host, or terminating because of a lack of connection. For more information, refer to man:traceroute[8]. [[network-routing-multicast]] === Multicast Considerations FreeBSD natively supports both multicast applications and multicast routing. Multicast applications do not require any special configuration in order to run on FreeBSD. Support for multicast routing requires that the following option be compiled into a custom kernel: [.programlisting] .... options MROUTING .... The multicast routing daemon, mrouted can be installed using the package:net/mrouted[] package or port. This daemon implements the DVMRP multicast routing protocol and is configured by editing [.filename]#/usr/local/etc/mrouted.conf# in order to set up the tunnels and DVMRP. The installation of mrouted also installs map-mbone and mrinfo, as well as their associated man pages. Refer to these for configuration examples. [NOTE] ==== DVMRP has largely been replaced by the PIM protocol in many multicast installations. Refer to man:pim[4] for more information. ==== [[network-wireless]] == Wireless Networking === Wireless Networking Basics Most wireless networks are based on the IEEE(R) 802.11 standards. A basic wireless network consists of multiple stations communicating with radios that broadcast in either the 2.4GHz or 5GHz band, though this varies according to the locale and is also changing to enable communication in the 2.3GHz and 4.9GHz ranges. 802.11 networks are organized in two ways. In _infrastructure mode_, one station acts as a master with all the other stations associating to it, the network is known as a BSS, and the master station is termed an access point (AP). In a BSS, all communication passes through the AP; even when one station wants to communicate with another wireless station, messages must go through the AP. In the second form of network, there is no master and stations communicate directly. This form of network is termed an IBSS and is commonly known as an _ad-hoc network_. 802.11 networks were first deployed in the 2.4GHz band using protocols defined by the IEEE(R) 802.11 and 802.11b standard. These specifications include the operating frequencies and the MAC layer characteristics, including framing and transmission rates, as communication can occur at various rates. Later, the 802.11a standard defined operation in the 5GHz band, including different signaling mechanisms and higher transmission rates. Still later, the 802.11g standard defined the use of 802.11a signaling and transmission mechanisms in the 2.4GHz band in such a way as to be backwards compatible with 802.11b networks. Separate from the underlying transmission techniques, 802.11 networks have a variety of security mechanisms. The original 802.11 specifications defined a simple security protocol called WEP. This protocol uses a fixed pre-shared key and the RC4 cryptographic cipher to encode data transmitted on a network. Stations must all agree on the fixed key in order to communicate. This scheme was shown to be easily broken and is now rarely used except to discourage transient users from joining networks. Current security practice is given by the IEEE(R) 802.11i specification that defines new cryptographic ciphers and an additional protocol to authenticate stations to an access point and exchange keys for data communication. Cryptographic keys are periodically refreshed and there are mechanisms for detecting and countering intrusion attempts. Another security protocol specification commonly used in wireless networks is termed WPA, which was a precursor to 802.11i. WPA specifies a subset of the requirements found in 802.11i and is designed for implementation on legacy hardware. Specifically, WPA requires only the TKIP cipher that is derived from the original WEP cipher. 802.11i permits use of TKIP but also requires support for a stronger cipher, AES-CCM, for encrypting data. The AES cipher was not required in WPA because it was deemed too computationally costly to be implemented on legacy hardware. The other standard to be aware of is 802.11e. It defines protocols for deploying multimedia applications, such as streaming video and voice over IP (VoIP), in an 802.11 network. Like 802.11i, 802.11e also has a precursor specification termed WME (later renamed WMM) that has been defined by an industry group as a subset of 802.11e that can be deployed now to enable multimedia applications while waiting for the final ratification of 802.11e. The most important thing to know about 802.11e and WME/WMM is that it enables prioritized traffic over a wireless network through Quality of Service (QoS) protocols and enhanced media access protocols. Proper implementation of these protocols enables high speed bursting of data and prioritized traffic flow. FreeBSD supports networks that operate using 802.11a, 802.11b, and 802.11g. The WPA and 802.11i security protocols are likewise supported (in conjunction with any of 11a, 11b, and 11g) and QoS and traffic prioritization required by the WME/WMM protocols are supported for a limited set of wireless devices. [[network-wireless-quick-start]] === Quick Start Connecting a computer to an existing wireless network is a very common situation. This procedure shows the steps required. [.procedure] . Obtain the SSID (Service Set Identifier) and PSK (Pre-Shared Key) for the wireless network from the network administrator. . Identify the wireless adapter. The FreeBSD [.filename]#GENERIC# kernel includes drivers for many common wireless adapters. If the wireless adapter is one of those models, it will be shown in the output from man:ifconfig[8]: + [source,bash] .... % ifconfig | grep -B3 -i wireless .... + On FreeBSD 11 or higher, use this command instead: + [source,bash] .... % sysctl net.wlan.devices .... + If a wireless adapter is not listed, an additional kernel module might be required, or it might be a model not supported by FreeBSD. + This example shows the Atheros `ath0` wireless adapter. . Add an entry for this network to [.filename]#/etc/wpa_supplicant.conf#. If the file does not exist, create it. Replace _myssid_ and _mypsk_ with the SSID and PSK provided by the network administrator. + [.programlisting] .... network={ ssid="myssid" psk="mypsk" } .... . Add entries to [.filename]#/etc/rc.conf# to configure the network on startup: + [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA SYNCDHCP" .... . Restart the computer, or restart the network service to connect to the network: + [source,bash] .... # service netif restart .... [[network-wireless-basic]] === Basic Setup ==== Kernel Configuration To use wireless networking, a wireless networking card is needed and the kernel needs to be configured with the appropriate wireless networking support. The kernel is separated into multiple modules so that only the required support needs to be configured. The most commonly used wireless devices are those that use parts made by Atheros. These devices are supported by man:ath[4] and require the following line to be added to [.filename]#/boot/loader.conf#: [.programlisting] .... if_ath_load="YES" .... The Atheros driver is split up into three separate pieces: the driver (man:ath[4]), the hardware support layer that handles chip-specific functions (man:ath_hal[4]), and an algorithm for selecting the rate for transmitting frames. When this support is loaded as kernel modules, any dependencies are automatically handled. To load support for a different type of wireless device, specify the module for that device. This example is for devices based on the Intersil Prism parts (man:wi[4]) driver: [.programlisting] .... if_wi_load="YES" .... [NOTE] ==== The examples in this section use an man:ath[4] device and the device name in the examples must be changed according to the configuration. A list of available wireless drivers and supported adapters can be found in the FreeBSD Hardware Notes, available on the https://www.FreeBSD.org/releases/[Release Information] page of the FreeBSD website. If a native FreeBSD driver for the wireless device does not exist, it may be possible to use the Windows(R) driver with the help of the crossref:config[config-network-ndis,NDIS] driver wrapper. ==== In addition, the modules that implement cryptographic support for the security protocols to use must be loaded. These are intended to be dynamically loaded on demand by the man:wlan[4] module, but for now they must be manually configured. The following modules are available: man:wlan_wep[4], man:wlan_ccmp[4], and man:wlan_tkip[4]. The man:wlan_ccmp[4] and man:wlan_tkip[4] drivers are only needed when using the WPA or 802.11i security protocols. If the network does not use encryption, man:wlan_wep[4] support is not needed. To load these modules at boot time, add the following lines to [.filename]#/boot/loader.conf#: [.programlisting] .... wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" .... Once this information has been added to [.filename]#/boot/loader.conf#, reboot the FreeBSD box. Alternately, load the modules by hand using man:kldload[8]. [NOTE] ==== For users who do not want to use modules, it is possible to compile these drivers into the kernel by adding the following lines to a custom kernel configuration file: [.programlisting] .... device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath .... With this information in the kernel configuration file, recompile the kernel and reboot the FreeBSD machine. ==== Information about the wireless device should appear in the boot messages, like this: [source,bash] .... ath0: mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 .... ==== Setting the Correct Region Since the regulatory situation is different in various parts of the world, it is necessary to correctly set the domains that apply to your location to have the correct information about what channels can be used. The available region definitions can be found in [.filename]#/etc/regdomain.xml#. To set the data at runtime, use `ifconfig`: [source,bash] .... # ifconfig wlan0 regdomain ETSI country AT .... To persist the settings, add it to [.filename]#/etc/rc.conf#: [source,bash] .... # sysrc create_args_wlan0="country AT regdomain ETSI" .... === Infrastructure Mode Infrastructure (BSS) mode is the mode that is typically used. In this mode, a number of wireless access points are connected to a wired network. Each wireless network has its own name, called the SSID. Wireless clients connect to the wireless access points. ==== FreeBSD Clients ===== How to Find Access Points To scan for available networks, use man:ifconfig[8]. This request may take a few moments to complete as it requires the system to switch to each available wireless frequency and probe for available access points. Only the superuser can initiate a scan: [source,bash] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA .... [NOTE] ==== The interface must be `up` before it can scan. Subsequent scan requests do not require the interface to be marked as up again. ==== The output of a scan request lists each BSS/IBSS network found. Besides listing the name of the network, the `SSID`, the output also shows the `BSSID`, which is the MAC address of the access point. The `CAPS` field identifies the type of each network and the capabilities of the stations operating there: .Station Capability Codes [cols="1,1", frame="none", options="header"] |=== | Capability Code | Meaning |`E` |Extended Service Set (ESS). Indicates that the station is part of an infrastructure network rather than an IBSS/ad-hoc network. |`I` |IBSS/ad-hoc network. Indicates that the station is part of an ad-hoc network rather than an ESS network. |`P` |Privacy. Encryption is required for all data frames exchanged within the BSS using cryptographic means such as WEP, TKIP or AES-CCMP. |`S` |Short Preamble. Indicates that the network is using short preambles, defined in 802.11b High Rate/DSSS PHY, and utilizes a 56 bit sync field rather than the 128 bit field used in long preamble mode. |`s` |Short slot time. Indicates that the 802.11g network is using a short slot time because there are no legacy (802.11b) stations present. |=== One can also display the current list of known networks with: [source,bash] .... # ifconfig wlan0 list scan .... This information may be updated automatically by the adapter or manually with a `scan` request. Old data is automatically removed from the cache, so over time this list may shrink unless more scans are done. ===== Basic Settings This section provides a simple example of how to make the wireless network adapter work in FreeBSD without encryption. Once familiar with these concepts, it is strongly recommend to use <> to set up the wireless network. There are three basic steps to configure a wireless network: select an access point, authenticate the station, and configure an IP address. The following sections discuss each step. ====== Selecting an Access Point Most of the time, it is sufficient to let the system choose an access point using the builtin heuristics. This is the default behavior when an interface is marked as up or it is listed in [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... If there are multiple access points, a specific one can be selected by its SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here DHCP" .... In an environment where there are multiple access points with the same SSID, which is often done to simplify roaming, it may be necessary to associate to one specific device. In this case, the BSSID of the access point can be specified, with or without the SSID: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here bssid xx:xx:xx:xx:xx:xx DHCP" .... There are other ways to constrain the choice of an access point, such as limiting the set of frequencies the system will scan on. This may be useful for a multi-band wireless card as scanning all the possible channels can be time-consuming. To limit operation to a specific band, use the `mode` parameter: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid your_ssid_here DHCP" .... This example will force the card to operate in 802.11g, which is defined only for 2.4GHz frequencies so any 5GHz channels will not be considered. This can also be achieved with the `channel` parameter, which locks operation to one specific frequency, and the `chanlist` parameter, to specify a list of channels for scanning. More information about these parameters can be found in man:ifconfig[8]. ====== Authentication Once an access point is selected, the station needs to authenticate before it can pass data. Authentication can happen in several ways. The most common scheme, open authentication, allows any station to join the network and communicate. This is the authentication to use for test purposes the first time a wireless network is setup. Other schemes require cryptographic handshakes to be completed before data traffic can flow, either using pre-shared keys or secrets, or more complex schemes that involve backend services such as RADIUS. Open authentication is the default setting. The next most common setup is WPA-PSK, also known as WPA Personal, which is described in <>. [NOTE] ==== If using an Apple(R) AirPort(R) Extreme base station for an access point, shared-key authentication together with a WEP key needs to be configured. This can be configured in [.filename]#/etc/rc.conf# or by using man:wpa_supplicant[8]. For a single AirPort(R) base station, access can be configured with: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" .... In general, shared key authentication should be avoided because it uses the WEP key material in a highly-constrained manner, making it even easier to crack the key. If WEP must be used for compatibility with legacy devices, it is better to use WEP with `open` authentication. More information regarding WEP can be found in <>. ==== ====== Getting an IP Address with DHCP Once an access point is selected and the authentication parameters are set, an IP address must be obtained in order to communicate. Most of the time, the IP address is obtained via DHCP. To achieve that, edit [.filename]#/etc/rc.conf# and add `DHCP` to the configuration for the device: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="DHCP" .... The wireless interface is now ready to bring up: [source,bash] .... # service netif start .... Once the interface is running, use man:ifconfig[8] to see the status of the interface [.filename]#ath0#: [source,bash] .... # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... The `status: associated` line means that it is connected to the wireless network. The `bssid 00:13:46:49:41:76` is the MAC address of the access point and `authmode OPEN` indicates that the communication is not encrypted. ====== Static IP Address If an IP address cannot be obtained from a DHCP server, set a fixed IP address. Replace the `DHCP` keyword shown above with the address information. Be sure to retain any other parameters for selecting the access point: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" .... [[network-wireless-wpa]] ===== WPA Wi-Fi Protected Access (WPA) is a security protocol used together with 802.11 networks to address the lack of proper authentication and the weakness of WEP. WPA leverages the 802.1X authentication protocol and uses one of several ciphers instead of WEP for data integrity. The only cipher required by WPA is the Temporary Key Integrity Protocol (TKIP). TKIP is a cipher that extends the basic RC4 cipher used by WEP by adding integrity checking, tamper detection, and measures for responding to detected intrusions. TKIP is designed to work on legacy hardware with only software modification. It represents a compromise that improves security but is still not entirely immune to attack. WPA also specifies the AES-CCMP cipher as an alternative to TKIP, and that is preferred when possible. For this specification, the term WPA2 or RSN is commonly used. WPA defines authentication and encryption protocols. Authentication is most commonly done using one of two techniques: by 802.1X and a backend authentication service such as RADIUS, or by a minimal handshake between the station and the access point using a pre-shared secret. The former is commonly termed WPA Enterprise and the latter is known as WPA Personal. Since most people will not set up a RADIUS backend server for their wireless network, WPA-PSK is by far the most commonly encountered configuration for WPA. The control of the wireless connection and the key negotiation or authentication with a server is done using man:wpa_supplicant[8]. This program requires a configuration file, [.filename]#/etc/wpa_supplicant.conf#, to run. More information regarding this file can be found in man:wpa_supplicant.conf[5]. [[network-wireless-wpa-wpa-psk]] ====== WPA-PSK WPA-PSK, also known as WPA Personal, is based on a pre-shared key (PSK) which is generated from a given password and used as the master key in the wireless network. This means every wireless user will share the same key. WPA-PSK is intended for small networks where the use of an authentication server is not possible or desired. [WARNING] ==== Always use strong passwords that are sufficiently long and made from a rich alphabet so that they will not be easily guessed or attacked. ==== The first step is the configuration of [.filename]#/etc/wpa_supplicant.conf# with the SSID and the pre-shared key of the network: [.programlisting] .... network={ ssid="freebsdap" psk="freebsdmall" } .... Then, in [.filename]#/etc/rc.conf#, indicate that the wireless device configuration will be done with WPA and the IP address will be obtained with DHCP: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,bash] .... # service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... Or, try to configure the interface manually using the information in [.filename]#/etc/wpa_supplicant.conf#: [source,bash] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] .... The next operation is to launch man:dhclient[8] to get the IP address from the DHCP server: [source,bash] .... # dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [NOTE] ==== If [.filename]#/etc/rc.conf# has an `ifconfig_wlan0="DHCP"` entry, man:dhclient[8] will be launched automatically after man:wpa_supplicant[8] associates with the access point. ==== If DHCP is not possible or desired, set a static IP address after man:wpa_supplicant[8] has authenticated the station: [source,bash] .... # ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 # ifconfig wlan0 wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... When DHCP is not used, the default gateway and the nameserver also have to be manually set: [source,bash] .... # route add default your_default_router # echo "nameserver your_DNS_server" >> /etc/resolv.conf .... [[network-wireless-wpa-eap-tls]] ====== WPA with EAP-TLS The second way to use WPA is with an 802.1X backend authentication server. In this case, WPA is called WPA Enterprise to differentiate it from the less secure WPA Personal. Authentication in WPA Enterprise is based on the Extensible Authentication Protocol (EAP). EAP does not come with an encryption method. Instead, EAP is embedded inside an encrypted tunnel. There are many EAP authentication methods, but EAP-TLS, EAP-TTLS, and EAP-PEAP are the most common. EAP with Transport Layer Security (EAP-TLS) is a well-supported wireless authentication protocol since it was the first EAP method to be certified by the http://www.wi-fi.org/[Wi-Fi Alliance]. EAP-TLS requires three certificates to run: the certificate of the Certificate Authority (CA) installed on all machines, the server certificate for the authentication server, and one client certificate for each wireless client. In this EAP method, both the authentication server and wireless client authenticate each other by presenting their respective certificates, and then verify that these certificates were signed by the organization's CA. As previously, the configuration is done via [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" <.> proto=RSN <.> key_mgmt=WPA-EAP <.> eap=TLS <.> identity="loader" <.> ca_cert="/etc/certs/cacert.pem" <.> client_cert="/etc/certs/clientcert.pem" <.> private_key="/etc/certs/clientkey.pem" <.> private_key_passwd="freebsdmallclient" <.> } .... <.> This field indicates the network name (SSID). <.> This example uses the RSN IEEE(R) 802.11i protocol, also known as WPA2. <.> The `key_mgmt` line refers to the key management protocol to use. In this example, it is WPA using EAP authentication. <.> This field indicates the EAP method for the connection. <.> The `identity` field contains the identity string for EAP. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> The `client_cert` line gives the pathname to the client certificate file. This certificate is unique to each wireless client of the network. <.> The `private_key` field is the pathname to the client certificate private key file. <.> The `private_key_passwd` field contains the passphrase for the private key. Then, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,bash] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... It is also possible to bring up the interface manually using man:wpa_supplicant[8] and man:ifconfig[8]. [[network-wireless-wpa-eap-ttls]] ====== WPA with EAP-TTLS With EAP-TLS, both the authentication server and the client need a certificate. With EAP-TTLS, a client certificate is optional. This method is similar to a web server which creates a secure SSL tunnel even if visitors do not have client-side certificates. EAP-TTLS uses an encrypted TLS tunnel for safe transport of the authentication data. The required configuration can be added to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase2="auth=MD5" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field specifies the authentication method used in the encrypted TLS tunnel. In this example, EAP with MD5-Challenge is used. The "inner authentication" phase is often called "phase2". Next, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... The next step is to bring up the interface: [source,bash] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wpa-eap-peap]] ====== WPA with EAP-PEAP [NOTE] ==== PEAPv0/EAP-MSCHAPv2 is the most common PEAP method. In this chapter, the term PEAP is used to refer to that method. ==== Protected EAP (PEAP) is designed as an alternative to EAP-TTLS and is the most used EAP standard after EAP-TLS. In a network with mixed operating systems, PEAP should be the most supported standard after EAP-TLS. PEAP is similar to EAP-TTLS as it uses a server-side certificate to authenticate clients by creating an encrypted TLS tunnel between the client and the authentication server, which protects the ensuing exchange of authentication information. PEAP authentication differs from EAP-TTLS as it broadcasts the username in the clear and only the password is sent in the encrypted TLS tunnel. EAP-TTLS will use the TLS tunnel for both the username and password. Add the following lines to [.filename]#/etc/wpa_supplicant.conf# to configure the EAP-PEAP related settings: [.programlisting] .... network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP <.> identity="test" <.> password="test" <.> ca_cert="/etc/certs/cacert.pem" <.> phase1="peaplabel=0" <.> phase2="auth=MSCHAPV2" <.> } .... <.> This field specifies the EAP method for the connection. <.> The `identity` field contains the identity string for EAP authentication inside the encrypted TLS tunnel. <.> The `password` field contains the passphrase for the EAP authentication. <.> The `ca_cert` field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. <.> This field contains the parameters for the first phase of authentication, the TLS tunnel. According to the authentication server used, specify a specific label for authentication. Most of the time, the label will be "client EAP encryption" which is set by using `peaplabel=0`. More information can be found in man:wpa_supplicant.conf[5]. <.> This field specifies the authentication protocol used in the encrypted TLS tunnel. In the case of PEAP, it is `auth=MSCHAPV2`. Add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" .... Then, bring up the interface: [source,bash] .... # service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL .... [[network-wireless-wep]] ===== WEP Wired Equivalent Privacy (WEP) is part of the original 802.11 standard. There is no authentication mechanism, only a weak form of access control which is easily cracked. WEP can be set up using man:ifconfig[8]: [source,bash] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 .... * The `weptxkey` specifies which WEP key will be used in the transmission. This example uses the third key. This must match the setting on the access point. When unsure which key is used by the access point, try `1` (the first key) for this value. * The `wepkey` selects one of the WEP keys. It should be in the format _index:key_. Key `1` is used by default; the index only needs to be set when using a key other than the first key. + [NOTE] ==== Replace the `0x3456789012` with the key configured for use on the access point. ==== Refer to man:ifconfig[8] for further information. The man:wpa_supplicant[8] facility can be used to configure a wireless interface with WEP. The example above can be set up by adding the following lines to [.filename]#/etc/wpa_supplicant.conf#: [.programlisting] .... network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } .... Then: [source,bash] .... # wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76 .... === Ad-hoc Mode IBSS mode, also called ad-hoc mode, is designed for point to point connections. For example, to establish an ad-hoc network between the machines `A` and `B`, choose two IP addresses and a SSID. On `A`: [source,bash] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... The `adhoc` parameter indicates that the interface is running in IBSS mode. `B` should now be able to detect `A`: [source,bash] .... # ifconfig wlan0 create wlandev ath0 wlanmode adhoc # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME .... The `I` in the output confirms that `A` is in ad-hoc mode. Now, configure `B` with a different IP address: [source,bash] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst .... Both `A` and `B` are now ready to exchange information. [[network-wireless-ap]] === FreeBSD Host Access Points FreeBSD can act as an Access Point (AP) which eliminates the need to buy a hardware AP or run an ad-hoc network. This can be particularly useful when a FreeBSD machine is acting as a gateway to another network such as the Internet. [[network-wireless-ap-basic]] ==== Basic Settings Before configuring a FreeBSD machine as an AP, the kernel must be configured with the appropriate networking support for the wireless card as well as the security protocols being used. For more details, see <>. [NOTE] ==== The NDIS driver wrapper for Windows(R) drivers does not currently support AP operation. Only native FreeBSD wireless drivers support AP mode. ==== Once wireless networking support is loaded, check if the wireless device supports the host-based access point mode, also known as hostap mode: [source,bash] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 list caps drivercaps=6f85edc1 cryptocaps=1f .... This output displays the card's capabilities. The `HOSTAP` word confirms that this wireless card can act as an AP. Various supported ciphers are also listed: WEP, TKIP, and AES. This information indicates which security protocols can be used on the AP. The wireless device can only be put into hostap mode during the creation of the network pseudo-device, so a previously created device must be destroyed first: [source,bash] .... # ifconfig wlan0 destroy .... then regenerated with the correct option before setting the other parameters: [source,bash] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 .... Use man:ifconfig[8] again to see the status of the [.filename]#wlan0# interface: [source,bash] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... The `hostap` parameter indicates the interface is running in the host-based access point mode. The interface configuration can be done automatically at boot time by adding the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" .... ==== Host-based Access Point Without Authentication or Encryption Although it is not recommended to run an AP without any authentication or encryption, this is a simple way to check if the AP is working. This configuration is also important for debugging client issues. Once the AP is configured, initiate a scan from another wireless machine to find the AP: [source,bash] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME .... The client machine found the AP and can be associated with it: [source,bash] .... # ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst .... [[network-wireless-ap-wpa]] ==== WPA2 Host-based Access Point This section focuses on setting up a FreeBSD access point using the WPA2 security protocol. More details regarding WPA and the configuration of WPA-based wireless clients can be found in <>. The man:hostapd[8] daemon is used to deal with client authentication and key management on the WPA2-enabled AP. The following configuration operations are performed on the FreeBSD machine acting as the AP. Once the AP is correctly working, man:hostapd[8] can be automatically started at boot with this line in [.filename]#/etc/rc.conf#: [.programlisting] .... hostapd_enable="YES" .... Before trying to configure man:hostapd[8], first configure the basic settings introduced in <>. ===== WPA2-PSK WPA2-PSK is intended for small networks where the use of a backend authentication server is not possible or desired. The configuration is done in [.filename]#/etc/hostapd.conf#: [.programlisting] .... interface=wlan0 <.> debug=1 <.> ctrl_interface=/var/run/hostapd <.> ctrl_interface_group=wheel <.> ssid=freebsdap <.> wpa=2 <.> wpa_passphrase=freebsdmall <.> wpa_key_mgmt=WPA-PSK <.> wpa_pairwise=CCMP <.> .... <.> Wireless interface used for the access point. <.> Level of verbosity used during the execution of man:hostapd[8]. A value of `1` represents the minimal level. <.> Pathname of the directory used by man:hostapd[8] to store domain socket files for communication with external programs such as man:hostapd_cli[8]. The default value is used in this example. <.> The group allowed to access the control interface files. <.> The wireless network name, or SSID, that will appear in wireless scans. <.> Enable WPA and specify which WPA authentication protocol will be required. A value of `2` configures the AP for WPA2 and is recommended. Set to `1` only if the obsolete WPA is required. <.> ASCII passphrase for WPA authentication. <.> The key management protocol to use. This example sets WPA-PSK. <.> Encryption algorithms accepted by the access point. In this example, only the CCMP (AES) cipher is accepted. CCMP is an alternative to TKIP and is strongly preferred when possible. TKIP should be allowed only when there are stations incapable of using CCMP. The next step is to start man:hostapd[8]: [source,bash] .... # service hostapd forcestart .... [source,bash] .... # ifconfig wlan0 wlan0: flags=8943 metric 0 mtu 1500 ether 04:f0:21:16:8e:10 inet6 fe80::6f0:21ff:fe16:8e10%wlan0 prefixlen 64 scopeid 0x9 nd6 options=21 media: IEEE 802.11 Wireless Ethernet autoselect mode 11na status: running ssid No5ignal channel 36 (5180 MHz 11a ht/40+) bssid 04:f0:21:16:8e:10 country US ecm authmode WPA2/802.11i privacy MIXED deftxkey 2 AES-CCM 2:128-bit AES-CCM 3:128-bit txpower 17 mcastrate 6 mgmtrate 6 scanvalid 60 ampdulimit 64k ampdudensity 8 shortgi wme burst dtimperiod 1 -dfs groups: wlan .... Once the AP is running, the clients can associate with it. See <> for more details. It is possible to see the stations associated with the AP using `ifconfig _wlan0_ list sta`. ==== WEP Host-based Access Point It is not recommended to use WEP for setting up an AP since there is no authentication mechanism and the encryption is easily cracked. Some legacy wireless cards only support WEP and these cards will only support an AP without authentication or encryption. The wireless device can now be put into hostap mode and configured with the correct SSID and IP address: [source,bash] .... # ifconfig wlan0 create wlandev ath0 wlanmode hostap # ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g .... * The `weptxkey` indicates which WEP key will be used in the transmission. This example uses the third key as key numbering starts with `1`. This parameter must be specified in order to encrypt the data. * The `wepkey` sets the selected WEP key. It should be in the format _index:key_. If the index is not given, key `1` is set. The index needs to be set when using keys other than the first key. Use man:ifconfig[8] to see the status of the [.filename]#wlan0# interface: [source,bash] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs .... From another wireless machine, it is now possible to initiate a scan to find the AP: [source,bash] .... # ifconfig wlan0 create wlandev ath0 # ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS .... In this example, the client machine found the AP and can associate with it using the correct parameters. See <> for more details. === Using Both Wired and Wireless Connections A wired connection provides better performance and reliability, while a wireless connection provides flexibility and mobility. Laptop users typically want to roam seamlessly between the two types of connections. On FreeBSD, it is possible to combine two or even more network interfaces together in a "failover" fashion. This type of configuration uses the most preferred and available connection from a group of network interfaces, and the operating system switches automatically when the link state changes. Link aggregation and failover is covered in <> and an example for using both wired and wireless connections is provided at <>. === Troubleshooting This section describes a number of steps to help troubleshoot common wireless networking problems. * If the access point is not listed when scanning, check that the configuration has not limited the wireless device to a limited set of channels. * If the device cannot associate with an access point, verify that the configuration matches the settings on the access point. This includes the authentication scheme and any security protocols. Simplify the configuration as much as possible. If using a security protocol such as WPA or WEP, configure the access point for open authentication and no security to see if traffic will pass. + Debugging support is provided by man:wpa_supplicant[8]. Try running this utility manually with `-dd` and look at the system logs. * Once the system can associate with the access point, diagnose the network configuration using tools like man:ping[8]. * There are many lower-level debugging tools. Debugging messages can be enabled in the 802.11 protocol support layer using man:wlandebug[8]. For example, to enable console messages related to scanning for access points and the 802.11 protocol handshakes required to arrange communication: + [source,bash] .... # wlandebug -i wlan0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000 .... + Many useful statistics are maintained by the 802.11 layer and `wlanstats`, found in [.filename]#/usr/src/tools/tools/net80211#, will dump this information. These statistics should display all errors identified by the 802.11 layer. However, some errors are identified in the device drivers that lie below the 802.11 layer so they may not show up. To diagnose device-specific problems, refer to the drivers' documentation. If the above information does not help to clarify the problem, submit a problem report and include output from the above tools. [[network-usb-tethering]] == USB Tethering Many cellphones provide the option to share their data connection over USB (often called "tethering"). This feature uses one of RNDIS, CDC, or a custom Apple(R) iPhone(R)/iPad(R) protocol. * Android(TM) devices generally use the man:urndis[4] driver. * Apple(R) devices use the man:ipheth[4] driver. * Older devices will often use the man:cdce[4] driver. Before attaching a device, load the appropriate driver into the kernel: [source,bash] .... # kldload if_urndis # kldload if_cdce # kldload if_ipheth .... Once the device is attached ``ue``_0_ will be available for use like a normal network device. Be sure that the "USB tethering" option is enabled on the device. To make this change permanent and load the driver as a module at boot time, place the appropriate line of the following in [.filename]#/boot/loader.conf#: [source,bash] .... if_urndis_load="YES" if_cdce_load="YES" if_ipheth_load="YES" .... [[network-bluetooth]] == Bluetooth Bluetooth is a wireless technology for creating personal networks operating in the 2.4 GHz unlicensed band, with a range of 10 meters. Networks are usually formed ad-hoc from portable devices such as cellular phones, handhelds, and laptops. Unlike Wi-Fi wireless technology, Bluetooth offers higher level service profiles, such as FTP-like file servers, file pushing, voice transport, serial line emulation, and more. This section describes the use of a USB Bluetooth dongle on a FreeBSD system. It then describes the various Bluetooth protocols and utilities. === Loading Bluetooth Support The Bluetooth stack in FreeBSD is implemented using the man:netgraph[4] framework. A broad variety of Bluetooth USB dongles is supported by man:ng_ubt[4]. Broadcom BCM2033 based Bluetooth devices are supported by the man:ubtbcmfw[4] and man:ng_ubt[4] drivers. The 3Com Bluetooth PC Card 3CRWB60-A is supported by the man:ng_bt3c[4] driver. Serial and UART based Bluetooth devices are supported by man:sio[4], man:ng_h4[4], and man:hcseriald[8]. Before attaching a device, determine which of the above drivers it uses, then load the driver. For example, if the device uses the man:ng_ubt[4] driver: [source,bash] .... # kldload ng_ubt .... If the Bluetooth device will be attached to the system during system startup, the system can be configured to load the module at boot time by adding the driver to [.filename]#/boot/loader.conf#: [.programlisting] .... ng_ubt_load="YES" .... Once the driver is loaded, plug in the USB dongle. If the driver load was successful, output similar to the following should appear on the console and in [.filename]#/var/log/messages#: [source,bash] .... ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 .... To start and stop the Bluetooth stack, use its startup script. It is a good idea to stop the stack before unplugging the device. Starting the bluetooth stack might require man:hcsecd[8] to be started. When starting the stack, the output should be similar to the following: [source,bash] .... # service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 .... === Finding Other Bluetooth Devices The Host Controller Interface (HCI) provides a uniform method for accessing Bluetooth baseband capabilities. In FreeBSD, a netgraph HCI node is created for each Bluetooth device. For more details, refer to man:ng_hci[4]. One of the most common tasks is discovery of Bluetooth devices within RF proximity. This operation is called _inquiry_. Inquiry and other HCI related operations are done using man:hccontrol[8]. The example below shows how to find out which Bluetooth devices are in range. The list of devices should be displayed in a few seconds. Note that a remote device will only answer the inquiry if it is set to _discoverable_ mode. [source,bash] .... % hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] .... The `BD_ADDR` is the unique address of a Bluetooth device, similar to the MAC address of a network card. This address is needed for further communication with a device and it is possible to assign a human readable name to a `BD_ADDR`. Information regarding the known Bluetooth hosts is contained in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the human readable name that was assigned to the remote device: [source,bash] .... % hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 .... If an inquiry is performed on a remote Bluetooth device, it will find the computer as "your.host.name (ubt0)". The name assigned to the local device can be changed at any time. Remote devices can be assigned aliases in [.filename]#/etc/bluetooth/hosts#. More information about [.filename]#/etc/bluetooth/hosts# file might be found in man:bluetooth.hosts[5]. The Bluetooth system provides a point-to-point connection between two Bluetooth units, or a point-to-multipoint connection which is shared among several Bluetooth devices. The following example shows how to create a connection to a remote device: [source,bash] .... % hccontrol -n ubt0hci create_connection BT_ADDR .... `create_connection` accepts `BT_ADDR` as well as host aliases in [.filename]#/etc/bluetooth/hosts#. The following example shows how to obtain the list of active baseband connections for the local device: [source,bash] .... % hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN .... A _connection handle_ is useful when termination of the baseband connection is required, though it is normally not required to do this by hand. The stack will automatically terminate inactive baseband connections. [source,bash] .... # hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] .... Type `hccontrol help` for a complete listing of available HCI commands. Most of the HCI commands do not require superuser privileges. === Device Pairing By default, Bluetooth communication is not authenticated, and any device can talk to any other device. A Bluetooth device, such as a cellular phone, may choose to require authentication to provide a particular service. Bluetooth authentication is normally done with a _PIN code_, an ASCII string up to 16 characters in length. The user is required to enter the same PIN code on both devices. Once the user has entered the PIN code, both devices will generate a _link key_. After that, the link key can be stored either in the devices or in a persistent storage. Next time, both devices will use the previously generated link key. This procedure is called _pairing_. Note that if the link key is lost by either device, the pairing must be repeated. The man:hcsecd[8] daemon is responsible for handling Bluetooth authentication requests. The default configuration file is [.filename]#/etc/bluetooth/hcsecd.conf#. An example section for a cellular phone with the PIN code set to `1234` is shown below: [.programlisting] .... device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } .... The only limitation on PIN codes is length. Some devices, such as Bluetooth headsets, may have a fixed PIN code built in. The `-d` switch forces man:hcsecd[8] to stay in the foreground, so it is easy to see what is happening. Set the remote device to receive pairing and initiate the Bluetooth connection to the remote device. The remote device should indicate that pairing was accepted and request the PIN code. Enter the same PIN code listed in [.filename]#hcsecd.conf#. Now the computer and the remote device are paired. Alternatively, pairing can be initiated on the remote device. The following line can be added to [.filename]#/etc/rc.conf# to configure man:hcsecd[8] to start automatically on system start: [.programlisting] .... hcsecd_enable="YES" .... The following is a sample of the man:hcsecd[8] daemon output: [.programlisting] .... hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 .... === Network Access with PPP Profiles A Dial-Up Networking (DUN) profile can be used to configure a cellular phone as a wireless modem for connecting to a dial-up Internet access server. It can also be used to configure a computer to receive data calls from a cellular phone. Network access with a PPP profile can be used to provide LAN access for a single Bluetooth device or multiple Bluetooth devices. It can also provide PC to PC connection using PPP networking over serial cable emulation. In FreeBSD, these profiles are implemented with man:ppp[8] and the man:rfcomm_pppd[8] wrapper which converts a Bluetooth connection into something PPP can use. Before a profile can be used, a new PPP label must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. In this example, man:rfcomm_pppd[8] is used to open a connection to a remote device with a `BD_ADDR` of `00:80:37:29:19:a4` on a DUNRFCOMM channel: [source,bash] .... # rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup .... The actual channel number will be obtained from the remote device using the SDP protocol. It is possible to specify the RFCOMM channel by hand, and in this case man:rfcomm_pppd[8] will not perform the SDP query. Use man:sdpcontrol[8] to find out the RFCOMM channel on the remote device. In order to provide network access with the PPPLAN service, man:sdpd[8] must be running and a new entry for LAN clients must be created in [.filename]#/etc/ppp/ppp.conf#. Consult man:rfcomm_pppd[8] for examples. Finally, start the RFCOMMPPP server on a valid RFCOMM channel number. The RFCOMMPPP server will automatically register the Bluetooth LAN service with the local SDP daemon. The example below shows how to start the RFCOMMPPP server. [source,bash] .... # rfcomm_pppd -s -C 7 -l rfcomm-server .... === Bluetooth Protocols This section provides an overview of the various Bluetooth protocols, their function, and associated utilities. ==== Logical Link Control and Adaptation Protocol (L2CAP) The Logical Link Control and Adaptation Protocol (L2CAP) provides connection-oriented and connectionless data services to upper layer protocols. L2CAP permits higher level protocols and applications to transmit and receive L2CAP data packets up to 64 kilobytes in length. L2CAP is based around the concept of _channels_. A channel is a logical connection on top of a baseband connection, where each channel is bound to a single protocol in a many-to-one fashion. Multiple channels can be bound to the same protocol, but a channel cannot be bound to multiple protocols. Each L2CAP packet received on a channel is directed to the appropriate higher level protocol. Multiple channels can share the same baseband connection. In FreeBSD, a netgraph L2CAP node is created for each Bluetooth device. This node is normally connected to the downstream Bluetooth HCI node and upstream Bluetooth socket nodes. The default name for the L2CAP node is "devicel2cap". For more details refer to man:ng_l2cap[4]. A useful command is man:l2ping[8], which can be used to ping other devices. Some Bluetooth implementations might not return all of the data sent to them, so `0 bytes` in the following example is normal. [source,bash] .... # l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 .... The man:l2control[8] utility is used to perform various operations on L2CAP nodes. This example shows how to obtain the list of logical connections (channels) and the list of baseband connections for the local device: [source,bash] .... % l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN % l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN .... Another diagnostic tool is man:btsockstat[1]. It is similar to man:netstat[1], but for Bluetooth network-related data structures. The example below shows the same logical connection as man:l2control[8] above. [source,bash] .... % btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN .... ==== Radio Frequency Communication (RFCOMM) The RFCOMM protocol provides emulation of serial ports over the L2CAP protocol. RFCOMM is a simple transport protocol, with additional provisions for emulating the 9 circuits of RS-232 (EIATIA-232-E) serial ports. It supports up to 60 simultaneous connections (RFCOMM channels) between two Bluetooth devices. For the purposes of RFCOMM, a complete communication path involves two applications running on the communication endpoints with a communication segment between them. RFCOMM is intended to cover applications that make use of the serial ports of the devices in which they reside. The communication segment is a direct connect Bluetooth link from one device to another. RFCOMM is only concerned with the connection between the devices in the direct connect case, or between the device and a modem in the network case. RFCOMM can support other configurations, such as modules that communicate via Bluetooth wireless technology on one side and provide a wired interface on the other side. In FreeBSD, RFCOMM is implemented at the Bluetooth sockets layer. ==== Service Discovery Protocol (SDP) The Service Discovery Protocol (SDP) provides the means for client applications to discover the existence of services provided by server applications as well as the attributes of those services. The attributes of a service include the type or class of service offered and the mechanism or protocol information needed to utilize the service. SDP involves communication between a SDP server and a SDP client. The server maintains a list of service records that describe the characteristics of services associated with the server. Each service record contains information about a single service. A client may retrieve information from a service record maintained by the SDP server by issuing a SDP request. If the client, or an application associated with the client, decides to use a service, it must open a separate connection to the service provider in order to utilize the service. SDP provides a mechanism for discovering services and their attributes, but it does not provide a mechanism for utilizing those services. Normally, a SDP client searches for services based on some desired characteristics of the services. However, there are times when it is desirable to discover which types of services are described by an SDP server's service records without any prior information about the services. This process of looking for any offered services is called _browsing_. The Bluetooth SDP server, man:sdpd[8], and command line client, man:sdpcontrol[8], are included in the standard FreeBSD installation. The following example shows how to perform a SDP browse query. [source,bash] .... % sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 .... Note that each service has a list of attributes, such as the RFCOMM channel. Depending on the service, the user might need to make note of some of the attributes. Some Bluetooth implementations do not support service browsing and may return an empty list. In this case, it is possible to search for the specific service. The example below shows how to search for the OBEX Object Push (OPUSH) service: [source,bash] .... % sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH .... Offering services on FreeBSD to Bluetooth clients is done with the man:sdpd[8] server. The following line can be added to [.filename]#/etc/rc.conf#: [.programlisting] .... sdpd_enable="YES" .... Then the man:sdpd[8] daemon can be started with: [source,bash] .... # service sdpd start .... The local server application that wants to provide a Bluetooth service to remote clients will register the service with the local SDP daemon. An example of such an application is man:rfcomm_pppd[8]. Once started, it will register the Bluetooth LAN service with the local SDP daemon. The list of services registered with the local SDP server can be obtained by issuing a SDP browse query via the local control channel: [source,bash] .... # sdpcontrol -l browse .... ==== OBEX Object Push (OPUSH) Object Exchange (OBEX) is a widely used protocol for simple file transfers between mobile devices. Its main use is in infrared communication, where it is used for generic file transfers between notebooks or PDAs, and for sending business cards or calendar entries between cellular phones and other devices with Personal Information Manager (PIM) applications. The OBEX server and client are implemented by obexapp, which can be installed using the package:comms/obexapp[] package or port. The OBEX client is used to push and/or pull objects from the OBEX server. An example object is a business card or an appointment. The OBEX client can obtain the RFCOMM channel number from the remote device via SDP. This can be done by specifying the service name instead of the RFCOMM channel number. Supported service names are: `IrMC`, `FTRN`, and `OPUSH`. It is also possible to specify the RFCOMM channel as a number. Below is an example of an OBEX session where the device information object is pulled from the cellular phone, and a new object, the business card, is pushed into the phone's directory. [source,bash] .... % obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt devinfo-t39.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) .... In order to provide the OPUSH service, man:sdpd[8] must be running and a root folder, where all incoming objects will be stored, must be created. The default path to the root folder is [.filename]#/var/spool/obex#. Finally, start the OBEX server on a valid RFCOMM channel number. The OBEX server will automatically register the OPUSH service with the local SDP daemon. The example below shows how to start the OBEX server. [source,bash] .... # obexapp -s -C 10 .... ==== Serial Port Profile (SPP) The Serial Port Profile (SPP) allows Bluetooth devices to perform serial cable emulation. This profile allows legacy applications to use Bluetooth as a cable replacement, through a virtual serial port abstraction. In FreeBSD, man:rfcomm_sppd[1] implements SPP and a pseudo tty is used as a virtual serial port abstraction. The example below shows how to connect to a remote device's serial port service. A RFCOMM channel does not have to be specified as man:rfcomm_sppd[1] can obtain it from the remote device via SDP. To override this, specify a RFCOMM channel on the command line. [source,bash] .... # rfcomm_sppd -a 00:07:E0:00:0B:CA -t rfcomm_sppd[94692]: Starting on /dev/pts/6... /dev/pts/6 .... Once connected, the pseudo tty can be used as serial port: [source,bash] .... # cu -l /dev/pts/6 .... The pseudo tty is printed on stdout and can be read by wrapper scripts: [.programlisting] .... PTS=`rfcomm_sppd -a 00:07:E0:00:0B:CA -t` cu -l $PTS .... === Troubleshooting By default, when FreeBSD is accepting a new connection, it tries to perform a role switch and become master. Some older Bluetooth devices which do not support role switching will not be able to connect. Since role switching is performed when a new connection is being established, it is not possible to ask the remote device if it supports role switching. However, there is a HCI option to disable role switching on the local side: [source,bash] .... # hccontrol -n ubt0hci write_node_role_switch 0 .... To display Bluetooth packets, use the third-party package hcidump, which can be installed using the package:comms/hcidump[] package or port. This utility is similar to man:tcpdump[1] and can be used to display the contents of Bluetooth packets on the terminal and to dump the Bluetooth packets to a file. [[network-bridging]] == Bridging It is sometimes useful to divide a network, such as an Ethernet segment, into network segments without having to create IP subnets and use a router to connect the segments together. A device that connects two networks together in this fashion is called a "bridge". A bridge works by learning the MAC addresses of the devices on each of its network interfaces. It forwards traffic between networks only when the source and destination MAC addresses are on different networks. In many respects, a bridge is like an Ethernet switch with very few ports. A FreeBSD system with multiple network interfaces can be configured to act as a bridge. Bridging can be useful in the following situations: Connecting Networks:: The basic operation of a bridge is to join two or more network segments. There are many reasons to use a host-based bridge instead of networking equipment, such as cabling constraints or firewalling. A bridge can also connect a wireless interface running in hostap mode to a wired network and act as an access point. Filtering/Traffic Shaping Firewall:: A bridge can be used when firewall functionality is needed without routing or Network Address Translation (NAT). + An example is a small company that is connected via DSL or ISDN to an ISP. There are thirteen public IP addresses from the ISP and ten computers on the network. In this situation, using a router-based firewall is difficult because of subnetting issues. A bridge-based firewall can be configured without any IP addressing issues. Network Tap:: A bridge can join two network segments in order to inspect all Ethernet frames that pass between them using man:bpf[4] and man:tcpdump[1] on the bridge interface or by sending a copy of all frames out an additional interface known as a span port. Layer 2 VPN:: Two Ethernet networks can be joined across an IP link by bridging the networks to an EtherIP tunnel or a man:tap[4] based solution such as OpenVPN. Layer 2 Redundancy:: A network can be connected together with multiple links and use the Spanning Tree Protocol (STP) to block redundant paths. This section describes how to configure a FreeBSD system as a bridge using man:if_bridge[4]. A netgraph bridging driver is also available, and is described in man:ng_bridge[4]. [NOTE] ==== Packet filtering can be used with any firewall package that hooks into the man:pfil[9] framework. The bridge can be used as a traffic shaper with man:altq[4] or man:dummynet[4]. ==== === Enabling the Bridge In FreeBSD, man:if_bridge[4] is a kernel module which is automatically loaded by man:ifconfig[8] when creating a bridge interface. It is also possible to compile bridge support into a custom kernel by adding `device if_bridge` to the custom kernel configuration file. The bridge is created using interface cloning. To create the bridge interface: [source,bash] .... # ifconfig bridge create bridge0 # ifconfig bridge0 bridge0: flags=8802 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 .... When a bridge interface is created, it is automatically assigned a randomly generated Ethernet address. The `maxaddr` and `timeout` parameters control how many MAC addresses the bridge will keep in its forwarding table and how many seconds before each entry is removed after it is last seen. The other parameters control how STP operates. Next, specify which network interfaces to add as members of the bridge. For the bridge to forward packets, all member interfaces and the bridge need to be up: [source,bash] .... # ifconfig bridge0 addm fxp0 addm fxp1 up # ifconfig fxp0 up # ifconfig fxp1 up .... The bridge can now forward Ethernet frames between [.filename]#fxp0# and [.filename]#fxp1#. Add the following lines to [.filename]#/etc/rc.conf# so the bridge is created at startup: [.programlisting] .... cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" .... If the bridge host needs an IP address, set it on the bridge interface, not on the member interfaces. The address can be set statically or via DHCP. This example sets a static IP address: [source,bash] .... # ifconfig bridge0 inet 192.168.0.1/24 .... It is also possible to assign an IPv6 address to a bridge interface. To make the changes permanent, add the addressing information to [.filename]#/etc/rc.conf#. [NOTE] ==== When packet filtering is enabled, bridged packets will pass through the filter inbound on the originating interface on the bridge interface, and outbound on the appropriate interfaces. Either stage can be disabled. When direction of the packet flow is important, it is best to firewall on the member interfaces rather than the bridge itself. The bridge has several configurable settings for passing non-IP and IP packets, and layer2 firewalling with man:ipfw[8]. See man:if_bridge[4] for more information. ==== === Enabling Spanning Tree For an Ethernet network to function properly, only one active path can exist between two devices. The STP protocol detects loops and puts redundant links into a blocked state. Should one of the active links fail, STP calculates a different tree and enables one of the blocked paths to restore connectivity to all points in the network. The Rapid Spanning Tree Protocol (RSTP or 802.1w) provides backwards compatibility with legacy STP. RSTP provides faster convergence and exchanges information with neighboring switches to quickly transition to forwarding mode without creating loops. FreeBSD supports RSTP and STP as operating modes, with RSTP being the default mode. STP can be enabled on member interfaces using man:ifconfig[8]. For a bridge with [.filename]#fxp0# and [.filename]#fxp1# as the current interfaces, enable STP with: [source,bash] .... # ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843 metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7 port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role designated state forwarding .... This bridge has a spanning tree ID of `00:01:02:4b:d4:50` and a priority of `32768`. As the `root id` is the same, it indicates that this is the root bridge for the tree. Another bridge on the network also has STP enabled: [source,bash] .... bridge0: flags=8843 metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7 port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7 port 5 priority 128 path cost 200000 proto rstp role designated state forwarding .... The line `root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4` shows that the root bridge is `00:01:02:4b:d4:50` and has a path cost of `400000` from this bridge. The path to the root bridge is via `port 4` which is [.filename]#fxp0#. === Bridge Interface Parameters Several `ifconfig` parameters are unique to bridge interfaces. This section summarizes some common uses for these parameters. The complete list of available parameters is described in man:ifconfig[8]. private:: A private interface does not forward any traffic to any other port that is also designated as a private interface. The traffic is blocked unconditionally so no Ethernet frames will be forwarded, including ARP packets. If traffic needs to be selectively blocked, a firewall should be used instead. span:: A span port transmits a copy of every Ethernet frame received by the bridge. The number of span ports configured on a bridge is unlimited, but if an interface is designated as a span port, it cannot also be used as a regular bridge port. This is most useful for snooping a bridged network passively on another host connected to one of the span ports of the bridge. For example, to send a copy of all frames out the interface named [.filename]#fxp4#: + [source,bash] .... # ifconfig bridge0 span fxp4 .... sticky:: If a bridge member interface is marked as sticky, dynamically learned address entries are treated as static entries in the forwarding cache. Sticky entries are never aged out of the cache or replaced, even if the address is seen on a different interface. This gives the benefit of static address entries without the need to pre-populate the forwarding table. Clients learned on a particular segment of the bridge cannot roam to another segment. + An example of using sticky addresses is to combine the bridge with VLANs in order to isolate customer networks without wasting IP address space. Consider that `CustomerA` is on `vlan100`, `CustomerB` is on `vlan101`, and the bridge has the address `192.168.0.1`: + [source,bash] .... # ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 # ifconfig bridge0 inet 192.168.0.1/24 .... + In this example, both clients see `192.168.0.1` as their default gateway. Since the bridge cache is sticky, one host cannot spoof the MAC address of the other customer in order to intercept their traffic. + Any communication between the VLANs can be blocked using a firewall or, as seen in this example, private interfaces: + [source,bash] .... # ifconfig bridge0 private vlan100 private vlan101 .... + The customers are completely isolated from each other and the full `/24` address range can be allocated without subnetting. + The number of unique source MAC addresses behind an interface can be limited. Once the limit is reached, packets with unknown source addresses are dropped until an existing host cache entry expires or is removed. + The following example sets the maximum number of Ethernet devices for `CustomerA` on `vlan100` to 10: + [source,bash] .... # ifconfig bridge0 ifmaxaddr vlan100 10 .... Bridge interfaces also support monitor mode, where the packets are discarded after man:bpf[4] processing and are not processed or forwarded further. This can be used to multiplex the input of two or more interfaces into a single man:bpf[4] stream. This is useful for reconstructing the traffic for network taps that transmit the RX/TX signals out through two separate interfaces. For example, to read the input from four network interfaces as one stream: [source,bash] .... # ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up # tcpdump -i bridge0 .... === SNMP Monitoring The bridge interface and STP parameters can be monitored via man:bsnmpd[1] which is included in the FreeBSD base system. The exported bridge MIBs conform to IETF standards so any SNMP client or monitoring package can be used to retrieve the data. To enable monitoring on the bridge, uncomment this line in [.filename]#/etc/snmpd.config# by removing the beginning `#` symbol: [.programlisting] .... begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" .... Other configuration settings, such as community names and access lists, may need to be modified in this file. See man:bsnmpd[1] and man:snmp_bridge[3] for more information. Once these edits are saved, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... bsnmpd_enable="YES" .... Then, start man:bsnmpd[1]: [source,bash] .... # service bsnmpd start .... The following examples use the Net-SNMP software (package:net-mgmt/net-snmp[]) to query a bridge from a client system. The package:net-mgmt/bsnmptools[] port can also be used. From the SNMP client which is running Net-SNMP, add the following lines to [.filename]#$HOME/.snmp/snmp.conf# in order to import the bridge MIB definitions: [.programlisting] .... -mibdirs +/usr/shared/snmp/mibs +mibdirs +/usr/share/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB .... To monitor a single bridge using the IETF BRIDGE-MIB (RFC4188): [source,bash] .... % snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) .... The `dot1dStpTopChanges.0` value is two, indicating that the STP bridge topology has changed twice. A topology change means that one or more links in the network have changed or failed and a new tree has been calculated. The `dot1dStpTimeSinceTopologyChange.0` value will show when this happened. To monitor multiple bridge interfaces, the private BEGEMOT-BRIDGE-MIB can be used: [source,bash] .... % snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 .... To change the bridge interface being monitored via the `mib-2.dot1dBridge` subtree: [source,bash] .... % snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 .... [[network-aggregation]] == Link Aggregation and Failover FreeBSD provides the man:lagg[4] interface which can be used to aggregate multiple network interfaces into one virtual interface in order to provide failover and link aggregation. Failover allows traffic to continue to flow as long as at least one aggregated network interface has an established link. Link aggregation works best on switches which support LACP, as this protocol distributes traffic bi-directionally while responding to the failure of individual links. The aggregation protocols supported by the lagg interface determine which ports are used for outgoing traffic and whether or not a specific port accepts incoming traffic. The following protocols are supported by man:lagg[4]: failover:: This mode sends and receives traffic only through the master port. If the master port becomes unavailable, the next active port is used. The first interface added to the virtual interface is the master port and all subsequently added interfaces are used as failover devices. If failover to a non-master port occurs, the original port becomes master once it becomes available again. fec / loadbalance:: Cisco(R) Fast EtherChannel(R) (FEC) is found on older Cisco(R) switches. It provides a static setup and does not negotiate aggregation with the peer or exchange frames to monitor the link. If the switch supports LACP, that should be used instead. lacp:: The IEEE(R) 802.3ad Link Aggregation Control Protocol (LACP) negotiates a set of aggregable links with the peer into one or more Link Aggregated Groups (LAGs). Each LAG is composed of ports of the same speed, set to full-duplex operation, and traffic is balanced across the ports in the LAG with the greatest total speed. Typically, there is only one LAG which contains all the ports. In the event of changes in physical connectivity, LACP will quickly converge to a new configuration. + LACP balances outgoing traffic across the active ports based on hashed protocol header information and accepts incoming traffic from any active port. The hash includes the Ethernet source and destination address and, if available, the VLAN tag, and the IPv4 or IPv6 source and destination address. roundrobin:: This mode distributes outgoing traffic using a round-robin scheduler through all active ports and accepts incoming traffic from any active port. Since this mode violates Ethernet frame ordering, it should be used with caution. === Configuration Examples This section demonstrates how to configure a Cisco(R) switch and a FreeBSD system for LACP load balancing. It then shows how to configure two Ethernet interfaces in failover mode as well as how to configure failover mode between an Ethernet and a wireless interface. [[networking-lacp-aggregation-cisco]] .LACP Aggregation with a Cisco(R) Switch [example] ==== This example connects two man:fxp[4] Ethernet interfaces on a FreeBSD machine to the first two Ethernet ports on a Cisco(R) switch as a single load balanced and fault tolerant link. More interfaces can be added to increase throughput and fault tolerance. Replace the names of the Cisco(R) ports, Ethernet devices, channel group number, and IP address shown in the example to match the local configuration. Frame ordering is mandatory on Ethernet links and any traffic between two stations always flows over the same physical link, limiting the maximum speed to that of one interface. The transmit algorithm attempts to use as much information as it can to distinguish different traffic flows and balance the flows across the available interfaces. On the Cisco(R) switch, add the _FastEthernet0/1_ and _FastEthernet0/2_ interfaces to channel group _1_: [source,bash] .... interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp .... On the FreeBSD system, create the man:lagg[4] interface using the physical interfaces _fxp0_ and _fxp1_ and bring the interfaces up with an IP address of _10.0.0.3/24_: [source,bash] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 .... Next, verify the status of the virtual interface: [source,bash] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.3 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c laggport: fxp0 flags=1c .... Ports marked as `ACTIVE` are part of the LAG that has been negotiated with the remote switch. Traffic will be transmitted and received through these active ports. Add `-v` to the above command to view the LAG identifiers. To see the port status on the Cisco(R) switch: [source,bash] .... switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D .... For more detail, type `show lacp neighbor detail`. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf# on the FreeBSD system: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" .... ==== [[networking-lagg-failover]] .Failover Mode [example] ==== Failover mode can be used to switch over to a secondary interface if the link is lost on the master interface. To configure failover, make sure that the underlying physical interfaces are up, then create the man:lagg[4] interface. In this example, _fxp0_ is the master interface, _fxp1_ is the secondary interface, and the virtual interface is assigned an IP address of _10.0.0.15/24_: [source,bash] .... # ifconfig fxp0 up # ifconfig fxp1 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 .... The virtual interface should look something like this: [source,bash] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5 .... Traffic will be transmitted and received on _fxp0_. If the link is lost on _fxp0_, _fxp1_ will become the active link. If the link is restored on the master interface, it will once again become the active link. To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" .... ==== [[networking-lagg-wired-and-wireless]] .Failover Mode Between Ethernet and Wireless Interfaces [example] ==== For laptop users, it is usually desirable to configure the wireless device as a secondary which is only used when the Ethernet connection is not available. With man:lagg[4], it is possible to configure a failover which prefers the Ethernet connection for both performance and security reasons, while maintaining the ability to transfer data over the wireless connection. This is achieved by overriding the Ethernet interface's MAC address with that of the wireless interface. [NOTE] **** In theory, either the Ethernet or wireless MAC address can be changed to match the other. However, some popular wireless interfaces lack support for overriding the MAC address. We therefore recommend overriding the Ethernet MAC address for this purpose. **** [NOTE] **** If the driver for the wireless interface is not loaded in the `GENERIC` or custom kernel, and the computer is running FreeBSD {rel121-current}, load the corresponding [.filename]#.ko# in [.filename]#/boot/loader.conf# by adding `*driver_load="YES"*` to that file and rebooting. Another, better way is to load the driver in [.filename]#/etc/rc.conf# by adding it to `kld_list` (see man:rc.conf[5] for details) in that file and rebooting. This is needed because otherwise the driver is not loaded yet at the time the man:lagg[4] interface is set up. **** In this example, the Ethernet interface, _re0_, is the master and the wireless interface, _wlan0_, is the failover. The _wlan0_ interface was created from the _ath0_ physical wireless interface, and the Ethernet interface will be configured with the MAC address of the wireless interface. First, determine the MAC address of the wireless interface: [source,bash] .... # ifconfig wlan0 wlan0: flags=8843 metric 0 mtu 1500 ether b8:ee:65:5b:32:59 groups: wlan ssid Bbox-A3BD2403 channel 6 (2437 MHz 11g ht/20) bssid 00:37:b7:56:4b:60 regdomain ETSI country FR indoor ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 2:128-bit txpower 30 bmiss 7 scanvalid 60 protmode CTS ampdulimit 64k ampdudensity 8 shortgi -stbctx stbcrx -ldpc wme burst roaming MANUAL media: IEEE 802.11 Wireless Ethernet MCS mode 11ng status: associated nd6 options=29 .... Replace _wlan0_ to match the system's wireless interface name. The `ether` line will contain the MAC address of the specified interface. Now, change the MAC address of the Ethernet interface: [source,bash] .... # ifconfig re0 ether b8:ee:65:5b:32:59 .... Bring the wireless interface up (replacing _FR_ with your own 2-letter country code), but do not set an IP address: [source,bash] .... # ifconfig wlan0 create wlandev ath0 country FR ssid my_router up .... Make sure the _re0_ interface is up, then create the man:lagg[4] interface with _re0_ as master with failover to _wlan0_: [source,bash] .... # ifconfig re0 up # ifconfig lagg0 create # ifconfig lagg0 up laggproto failover laggport re0 laggport wlan0 .... The virtual interface should look something like this: [source,bash] .... # ifconfig lagg0 lagg0: flags=8843 metric 0 mtu 1500 options=8 ether b8:ee:65:5b:32:59 laggproto failover lagghash l2,l3,l4 laggport: re0 flags=5 laggport: wlan0 flags=0<> groups: lagg media: Ethernet autoselect status: active .... Then, start the DHCP client to obtain an IP address: [source,bash] .... # dhclient lagg0 .... To retain this configuration across reboots, add the following entries to [.filename]#/etc/rc.conf#: [.programlisting] .... ifconfig_re0="ether b8:ee:65:5b:32:59" wlans_ath0="wlan0" ifconfig_wlan0="WPA" create_args_wlan0="country FR" cloned_interfaces="lagg0" ifconfig_lagg0="up laggproto failover laggport re0 laggport wlan0 DHCP" .... ==== [[network-diskless]] == Diskless Operation with PXE The Intel(R) Preboot eXecution Environment (PXE) allows an operating system to boot over the network. For example, a FreeBSD system can boot over the network and operate without a local disk, using file systems mounted from an NFS server. PXE support is usually available in the BIOS. To use PXE when the machine starts, select the `Boot from network` option in the BIOS setup or type a function key during system initialization. In order to provide the files needed for an operating system to boot over the network, a PXE setup also requires properly configured DHCP, TFTP, and NFS servers, where: * Initial parameters, such as an IP address, executable boot filename and location, server name, and root path are obtained from the DHCP server. * The operating system loader file is booted using TFTP. * The file systems are loaded using NFS. When a computer PXE boots, it receives information over DHCP about where to obtain the initial boot loader file. After the host computer receives this information, it downloads the boot loader via TFTP and then executes the boot loader. In FreeBSD, the boot loader file is [.filename]#/boot/pxeboot#. After [.filename]#/boot/pxeboot# executes, the FreeBSD kernel is loaded and the rest of the FreeBSD bootup sequence proceeds, as described in crossref:boot[boot,The FreeBSD Booting Process]. This section describes how to configure these services on a FreeBSD system so that other systems can PXE boot into FreeBSD. Refer to man:diskless[8] for more information. [CAUTION] ==== As described, the system providing these services is insecure. It should live in a protected area of a network and be untrusted by other hosts. ==== [[network-pxe-nfs]] === Setting Up the PXE Environment The steps shown in this section configure the built-in NFS and TFTP servers. The next section demonstrates how to install and configure the DHCP server. In this example, the directory which will contain the files used by PXE users is [.filename]#/b/tftpboot/FreeBSD/install#. It is important that this directory exists and that the same directory name is set in both [.filename]#/etc/inetd.conf# and [.filename]#/usr/local/etc/dhcpd.conf#. [NOTE] ==== The command examples below assume use of the man:sh[1] shell. man:csh[1] and man:tcsh[1] users will need to start a man:sh[1] shell or adapt the commands to man:csh[1] syntax. ==== [.procedure] . Create the root directory which will contain a FreeBSD installation to be NFS mounted: + [source,bash] .... # export NFSROOTDIR=/b/tftpboot/FreeBSD/install # mkdir -p ${NFSROOTDIR} .... . Enable the NFS server by adding this line to [.filename]#/etc/rc.conf#: + [.programlisting] .... nfs_server_enable="YES" .... . Export the diskless root directory via NFS by adding the following to [.filename]#/etc/exports#: + [.programlisting] .... /b -ro -alldirs -maproot=root .... . Start the NFS server: + [source,bash] .... # service nfsd start .... . Enable man:inetd[8] by adding the following line to [.filename]#/etc/rc.conf#: + [.programlisting] .... inetd_enable="YES" .... . Uncomment the following line in [.filename]#/etc/inetd.conf# by making sure it does not start with a `#` symbol: + [.programlisting] .... tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /b/tftpboot .... + [NOTE] ==== Some PXE versions require the TCP version of TFTP. In this case, uncomment the second `tftp` line which contains `stream tcp`. ==== . Start man:inetd[8]: + [source,bash] .... # service inetd start .... . Install the base system into [.filename]#${NFSROOTDIR}#, either by decompressing the official archives or by rebuilding the FreeBSD kernel and userland (refer to crossref:cutting-edge[makeworld,“Updating FreeBSD from Source”] for more detailed instructions, but do not forget to add `DESTDIR=_${NFSROOTDIR}_` when running the `make installkernel` and `make installworld` commands. . Test that the TFTP server works and can download the boot loader which will be obtained via PXE: + [source,bash] .... # tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... . Edit [.filename]#${NFSROOTDIR}/etc/fstab# and create an entry to mount the root file system over NFS: + [.programlisting] .... # Device Mountpoint FSType Options Dump Pass myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 .... + Replace _myhost.example.com_ with the hostname or IP address of the NFS server. In this example, the root file system is mounted read-only in order to prevent NFS clients from potentially deleting the contents of the root file system. . Set the root password in the PXE environment for client machines which are PXE booting : + [source,bash] .... # chroot ${NFSROOTDIR} # passwd .... . If needed, enable man:ssh[1] root logins for client machines which are PXE booting by editing [.filename]#${NFSROOTDIR}/etc/ssh/sshd_config# and enabling `PermitRootLogin`. This option is documented in man:sshd_config[5]. . Perform any other needed customizations of the PXE environment in [.filename]#${NFSROOTDIR}#. These customizations could include things like installing packages or editing the password file with man:vipw[8]. When booting from an NFS root volume, [.filename]#/etc/rc# detects the NFS boot and runs [.filename]#/etc/rc.initdiskless#. In this case, [.filename]#/etc# and [.filename]#/var# need to be memory backed file systems so that these directories are writable but the NFS root directory is read-only: [source,bash] .... # chroot ${NFSROOTDIR} # mkdir -p conf/base # tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc # tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var .... When the system boots, memory file systems for [.filename]#/etc# and [.filename]#/var# will be created and mounted and the contents of the [.filename]#cpio.gz# files will be copied into them. By default, these file systems have a maximum capacity of 5 megabytes. If your archives do not fit, which is usually the case for [.filename]#/var# when binary packages have been installed, request a larger size by putting the number of 512 byte sectors needed (e.g., 5 megabytes is 10240 sectors) in [.filename]#${NFSROOTDIR}/conf/base/etc/md_size# and [.filename]#${NFSROOTDIR}/conf/base/var/md_size# files for [.filename]#/etc# and [.filename]#/var# file systems respectively. [[network-pxe-setting-up-dhcp]] === Configuring the DHCP Server The DHCP server does not need to be the same machine as the TFTP and NFS server, but it needs to be accessible in the network. DHCP is not part of the FreeBSD base system but can be installed using the package:net/isc-dhcp43-server[] port or package. Once installed, edit the configuration file, [.filename]#/usr/local/etc/dhcpd.conf#. Configure the `next-server`, `filename`, and `root-path` settings as seen in this example: [.programlisting] .... subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3 ; option subnet-mask 255.255.255.0 ; option routers 192.168.0.1 ; option broadcast-address 192.168.0.255 ; option domain-name-servers 192.168.35.35, 192.168.35.36 ; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1 ; # path of boot loader obtained via tftp filename "FreeBSD/install/boot/pxeboot" ; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/" ; } .... The `next-server` directive is used to specify the IP address of the TFTP server. The `filename` directive defines the path to [.filename]#/boot/pxeboot#. A relative filename is used, meaning that [.filename]#/b/tftpboot# is not included in the path. The `root-path` option defines the path to the NFS root file system. Once the edits are saved, enable DHCP at boot time by adding the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... dhcpd_enable="YES" .... Then start the DHCP service: [source,bash] .... # service isc-dhcpd start .... === Debugging PXE Problems Once all of the services are configured and started, PXE clients should be able to automatically load FreeBSD over the network. If a particular client is unable to connect, when that client machine boots up, enter the BIOS configuration menu and confirm that it is set to boot from the network. This section describes some troubleshooting tips for isolating the source of the configuration problem should no clients be able to PXE boot. [.procedure] **** . Use the package:net/wireshark[] package or port to debug the network traffic involved during the PXE booting process, which is illustrated in the diagram below. + .PXE Booting Process with NFS Root Mount image::pxe-nfs.png[] + 1. Client broadcasts a DHCPDISCOVER message. + 2. The DHCP server responds with the IP address, next-server, filename, and root-path values. + 3. The client sends a TFTP request to next-server, asking to retrieve filename. + 4. The TFTP server responds and sends filename to client. + 5. The client executes filename, which is pxeboot(8), which then loads the kernel. When the kernel executes, the root file system specified by root-path is mounted over NFS. + . On the TFTP server, read [.filename]#/var/log/xferlog# to ensure that [.filename]#pxeboot# is being retrieved from the correct location. To test this example configuration: + [source,bash] .... # tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds .... + The `BUGS` sections in man:tftpd[8] and man:tftp[1] document some limitations with TFTP. . Make sure that the root file system can be mounted via NFS. To test this example configuration: + [source,bash] .... # mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt .... **** [[network-ipv6]] == IPv6 IPv6 is the new version of the well known IP protocol, also known as IPv4. IPv6 provides several advantages over IPv4 as well as many new features: * Its 128-bit address space allows for 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses. This addresses the IPv4 address shortage and eventual IPv4 address exhaustion. * Routers only store network aggregation addresses in their routing tables, thus reducing the average space of a routing table to 8192 entries. This addresses the scalability issues associated with IPv4, which required every allocated block of IPv4 addresses to be exchanged between Internet routers, causing their routing tables to become too large to allow efficient routing. * Address autoconfiguration (http://www.ietf.org/rfc/rfc2462.txt[RFC2462]). * Mandatory multicast addresses. * Built-in IPsec (IP security). * Simplified header structure. * Support for mobile IP. * IPv6-to-IPv4 transition mechanisms. FreeBSD includes the http://www.kame.net/[http://www.kame.net/] IPv6 reference implementation and comes with everything needed to use IPv6. This section focuses on getting IPv6 configured and running. === Background on IPv6 Addresses There are three different types of IPv6 addresses: Unicast:: A packet sent to a unicast address arrives at the interface belonging to the address. Anycast:: These addresses are syntactically indistinguishable from unicast addresses but they address a group of interfaces. The packet destined for an anycast address will arrive at the nearest router interface. Anycast addresses are only used by routers. Multicast:: These addresses identify a group of interfaces. A packet destined for a multicast address will arrive at all interfaces belonging to the multicast group. The IPv4 broadcast address, usually `xxx.xxx.xxx.255`, is expressed by multicast addresses in IPv6. When reading an IPv6 address, the canonical form is represented as `x:x:x:x:x:x:x:x`, where each `x` represents a 16 bit hex value. An example is `FEBC:A574:382B:23C1:AA49:4592:4EFE:9982`. Often, an address will have long substrings of all zeros. A `::` (double colon) can be used to replace one substring per address. Also, up to three leading ``0``s per hex value can be omitted. For example, `fe80::1` corresponds to the canonical form `fe80:0000:0000:0000:0000:0000:0000:0001`. A third form is to write the last 32 bits using the well known IPv4 notation. For example, `2002::10.0.0.1` corresponds to the hexadecimal canonical representation `2002:0000:0000:0000:0000:0000:0a00:0001`, which in turn is equivalent to `2002::a00:1`. To view a FreeBSD system's IPv6 address, use man:ifconfig[8]: [source,bash] .... # ifconfig .... [.programlisting] .... rl0: flags=8943 mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active .... In this example, the [.filename]#rl0# interface is using `fe80::200:21ff:fe03:8e1%rl0`, an auto-configured link-local address which was automatically generated from the MAC address. Some IPv6 addresses are reserved. A summary of these reserved addresses is seen in <>: [[reservedip6]] .Reserved IPv6 Addresses [cols="1,1,1,1", frame="none", options="header"] |=== | IPv6 address | Prefixlength (Bits) | Description | Notes |`::` |128 bits |unspecified |Equivalent to `0.0.0.0` in IPv4. |`::1` |128 bits |loopback address |Equivalent to `127.0.0.1` in IPv4. |`::00:xx:xx:xx:xx` |96 bits |embedded IPv4 |The lower 32 bits are the compatible IPv4 address. |`::ff:xx:xx:xx:xx` |96 bits |IPv4 mapped IPv6 address |The lower 32 bits are the IPv4 address for hosts which do not support IPv6. |`fe80::/10` |10 bits |link-local |Equivalent to 169.254.0.0/16 in IPv4. |`fc00::/7` |7 bits |unique-local |Unique local addresses are intended for local communication and are only routable within a set of cooperating sites. |`ff00::` |8 bits |multicast | |``2000::-3fff::`` |3 bits |global unicast |All global unicast addresses are assigned from this pool. The first 3 bits are `001`. |=== For further information on the structure of IPv6 addresses, refer to http://www.ietf.org/rfc/rfc3513.txt[RFC3513]. === Configuring IPv6 To configure a FreeBSD system as an IPv6 client, add these two lines to [.filename]#rc.conf#: [.programlisting] .... ifconfig_rl0_ipv6="inet6 accept_rtadv" rtsold_enable="YES" .... The first line enables the specified interface to receive router advertisement messages. The second line enables the router solicitation daemon, man:rtsol[8]. If the interface needs a statically assigned IPv6 address, add an entry to specify the static address and associated prefix length: [.programlisting] .... ifconfig_rl0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" .... To assign a default router, specify its address: [.programlisting] .... ipv6_defaultrouter="2001:db8:4672:6565::1" .... === Connecting to a Provider In order to connect to other IPv6 networks, one must have a provider or a tunnel that supports IPv6: * Contact an Internet Service Provider to see if they offer IPv6. * http://www.tunnelbroker.net[Hurricane Electric] offers tunnels with end-points all around the globe. [NOTE] ==== Install the package:net/freenet6[] package or port for a dial-up connection. ==== This section demonstrates how to take the directions from a tunnel provider and convert them into [.filename]#/etc/rc.conf# settings that will persist through reboots. The first [.filename]#/etc/rc.conf# entry creates the generic tunneling interface [.filename]#gif0#: [.programlisting] .... cloned_interfaces="gif0" .... Next, configure that interface with the IPv4 addresses of the local and remote endpoints. Replace `_MY_IPv4_ADDR_` and `_REMOTE_IPv4_ADDR_` with the actual IPv4 addresses: [.programlisting] .... create_args_gif0="tunnel MY_IPv4_ADDR REMOTE_IPv4_ADDR" .... To apply the IPv6 address that has been assigned for use as the IPv6 tunnel endpoint, add this line, replacing `_MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR_` with the assigned address: [.programlisting] .... ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" .... Then, set the default route for the other side of the IPv6 tunnel. Replace `_MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR_` with the default gateway address assigned by the provider: [.programlisting] .... ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" .... If the FreeBSD system will route IPv6 packets between the rest of the network and the world, enable the gateway using this line: [.programlisting] .... ipv6_gateway_enable="YES" .... === Router Advertisement and Host Auto Configuration This section demonstrates how to setup man:rtadvd[8] to advertise the IPv6 default route. To enable man:rtadvd[8], add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... rtadvd_enable="YES" .... It is important to specify the interface on which to do IPv6 router advertisement. For example, to tell man:rtadvd[8] to use [.filename]#rl0#: [.programlisting] .... rtadvd_interfaces="rl0" .... Next, create the configuration file, [.filename]#/etc/rtadvd.conf# as seen in this example: [.programlisting] .... rl0:\ :addrs#1:addr="2001:db8:1f11:246::":prefixlen#64:tc=ether: .... Replace [.filename]#rl0# with the interface to be used and `2001:db8:1f11:246::` with the prefix of the allocation. For a dedicated `/64` subnet, nothing else needs to be changed. Otherwise, change the `prefixlen#` to the correct value. === IPv6 and IPv6 Address Mapping When IPv6 is enabled on a server, there may be a need to enable IPv4 mapped IPv6 address communication. This compatibility option allows for IPv4 addresses to be represented as IPv6 addresses. Permitting IPv6 applications to communicate with IPv4 and vice versa may be a security issue. This option may not be required in most cases and is available only for compatibility. This option will allow IPv6-only applications to work with IPv4 in a dual stack environment. This is most useful for third party applications which may not support an IPv6-only environment. To enable this feature, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... ipv6_ipv4mapping="YES" .... Reviewing the information in RFC 3493, section 3.6 and 3.7 as well as RFC 4038 section 4.2 may be useful to some administrators. [[carp]] == Common Address Redundancy Protocol (CARP) The Common Address Redundancy Protocol (CARP) allows multiple hosts to share the same IP address and Virtual Host ID (VHID) in order to provide _high availability_ for one or more services. This means that one or more hosts can fail, and the other hosts will transparently take over so that users do not see a service failure. In addition to the shared IP address, each host has its own IP address for management and configuration. All of the machines that share an IP address have the same VHID. The VHID for each virtual IP address must be unique across the broadcast domain of the network interface. High availability using CARP is built into FreeBSD, though the steps to configure it vary slightly depending upon the FreeBSD version. This section provides the same example configuration for versions before and equal to or after FreeBSD 10. This example configures failover support with three hosts, all with unique IP addresses, but providing the same web content. It has two different masters named `hosta.example.org` and `hostb.example.org`, with a shared backup named `hostc.example.org`. These machines are load balanced with a Round Robin DNS configuration. The master and backup machines are configured identically except for their hostnames and management IP addresses. These servers must have the same configuration and run the same services. When the failover occurs, requests to the service on the shared IP address can only be answered correctly if the backup server has access to the same content. The backup machine has two additional CARP interfaces, one for each of the master content server's IP addresses. When a failure occurs, the backup server will pick up the failed master machine's IP address. [[carp-10x]] === Using CARP on FreeBSD 10 and Later Enable boot-time support for CARP by adding an entry for the [.filename]#carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... carp_load="YES" .... To load the module now without rebooting: [source,bash] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... device carp .... The hostname, management IP address and subnet mask, shared IP address, and VHID are all set by adding entries to [.filename]#/etc/rc.conf#. This example is for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32" .... The next set of entries are for `hostb.example.org`. Since it represents a second master, it uses a different shared IP address and VHID. However, the passwords specified with `pass` must be identical as CARP will only listen to and accept advertisements from machines with the correct password. [.programlisting] .... hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32" .... The third machine, `hostc.example.org`, is configured to handle failover from either master. This machine is configured with two CARPVHIDs, one to handle the virtual IP address for each of the master hosts. The CARP advertising skew, `advskew`, is set to ensure that the backup host advertises later than the master, since `advskew` controls the order of precedence when there are multiple backup servers. [.programlisting] .... hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" .... Having two CARPVHIDs configured means that `hostc.example.org` will notice if either of the master servers becomes unavailable. If a master fails to advertise before the backup server, the backup server will pick up the shared IP address until the master becomes available again. [NOTE] ==== If the original master server becomes available again, `hostc.example.org` will not release the virtual IP address back to it automatically. For this to happen, preemption has to be enabled. The feature is disabled by default, it is controlled via the man:sysctl[8] variable `net.inet.carp.preempt`. The administrator can force the backup server to return the IP address to the master: [source,bash] .... # ifconfig em0 vhid 1 state backup .... ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. CARP functionality can be controlled via several man:sysctl[8] variables documented in the man:carp[4] manual pages. Other actions can be triggered from CARP events by using man:devd[8]. [[carp-9x]] === Using CARP on FreeBSD 9 and Earlier The configuration for these versions of FreeBSD is similar to the one described in the previous section, except that a CARP device must first be created and referred to in the configuration. Enable boot-time support for CARP by loading the [.filename]#if_carp.ko# kernel module in [.filename]#/boot/loader.conf#: [.programlisting] .... if_carp_load="YES" .... To load the module now without rebooting: [source,bash] .... # kldload carp .... For users who prefer to use a custom kernel, include the following line in the custom kernel configuration file and compile the kernel as described in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... device carp .... Next, on each host, create a CARP device: [source,bash] .... # ifconfig carp0 create .... Set the hostname, management IP address, the shared IP address, and VHID by adding the required lines to [.filename]#/etc/rc.conf#. Since a virtual CARP device is used instead of an alias, the actual subnet mask of `/24` is used instead of `/32`. Here are the entries for `hosta.example.org`: [.programlisting] .... hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" .... On `hostb.example.org`: [.programlisting] .... hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" .... The third machine, `hostc.example.org`, is configured to handle failover from either of the master hosts: [.programlisting] .... hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" .... [NOTE] ==== Preemption is disabled in the [.filename]#GENERIC# FreeBSD kernel. If preemption has been enabled with a custom kernel, `hostc.example.org` may not release the IP address back to the original content server. The administrator can force the backup server to return the IP address to the master with the command: [source,bash] .... # ifconfig carp0 down && ifconfig carp0 up .... This should be done on the [.filename]#carp# interface which corresponds to the correct host. ==== Once the configuration is complete, either restart networking or reboot each system. High availability is now enabled. [[network-vlan]] == VLANs VLANs are a way of virtually dividing up a network into many different subnetworks, also referred to as segmenting. Each segment will have its own broadcast domain and be isolated from other VLANs. On FreeBSD, VLANs must be supported by the network card driver. To see which drivers support vlans, refer to the man:vlan[4] manual page. When configuring a VLAN, a couple pieces of information must be known. First, which network interface? Second, what is the VLAN tag? To configure VLANs at run time, with a NIC of `em0` and a VLAN tag of `5` the command would look like this: [source,bash] .... # ifconfig em0.5 create vlan 5 vlandev em0 inet 192.168.20.20/24 .... [NOTE] ==== See how the interface name includes the NIC driver name and the VLAN tag, separated by a period? This is a best practice to make maintaining the VLAN configuration easy when many VLANs are present on a machine. ==== To configure VLANs at boot time, [.filename]#/etc/rc.conf# must be updated. To duplicate the configuration above, the following will need to be added: [.programlisting] .... vlans_em0="5" ifconfig_em0_5="inet 192.168.20.20/24" .... Additional VLANs may be added, by simply adding the tag to the `vlans_em0` field and adding an additional line configuring the network on that VLAN tag's interface. It is useful to assign a symbolic name to an interface so that when the associated hardware is changed, only a few configuration variables need to be updated. For example, security cameras need to be run over VLAN 1 on `em0`. Later, if the `em0` card is replaced with a card that uses the man:ixgb[4] driver, all references to `em0.1` will not have to change to `ixgb0.1`. To configure VLAN `5`, on the NIC `em0`, assign the interface name `cameras`, and assign the interface an IP address of `_192.168.20.20_` with a `24`-bit prefix, use this command: [source,bash] .... # ifconfig em0.5 create vlan 5 vlandev em0 name cameras inet 192.168.20.20/24 .... For an interface named `video`, use the following: [source,bash] .... # ifconfig video.5 create vlan 5 vlandev video name cameras inet 192.168.20.20/24 .... To apply the changes at boot time, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... vlans_video="cameras" create_args_cameras="vlan 5" ifconfig_cameras="inet 192.168.20.20/24" .... diff --git a/documentation/content/en/books/handbook/basics/_index.adoc b/documentation/content/en/books/handbook/basics/_index.adoc index ecec5d87ab..67787332e9 100644 --- a/documentation/content/en/books/handbook/basics/_index.adoc +++ b/documentation/content/en/books/handbook/basics/_index.adoc @@ -1,1544 +1,1544 @@ --- title: Chapter 3. FreeBSD basics part: Part I. Getting Started prev: books/handbook/bsdinstall next: books/handbook/ports --- [[basics]] = FreeBSD basics :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 3 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/basics/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/basics/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/basics/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[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: [source,bash] .... FreeBSD/amd64 (pc3.example.org) (ttyv0) login: .... The first line contains some information about the system. The `amd64` indicates that the system in this example is running a 64-bit version of FreeBSD. The hostname is `pc3.example.org`, and [.filename]#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 name "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 ([.filename]#ttyv0#), kbd:[Alt+F2] to access the first virtual console ([.filename]#ttyv1#), kbd:[Alt+F3] to access the second virtual console ([.filename]#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 [.filename]#/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 [.filename]#ttyv5# through [.filename]#ttyv8#. _Do not_ comment out the line for the system console [.filename]#ttyv0#. Note that the last virtual console ([.filename]#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 [.filename]#/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,bash] .... # 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,bash] .... # 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,bash] .... # vidcontrol MODE_279 .... If the new video mode is acceptable, it can be permanently set on boot by adding it to [.filename]#/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`. [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 [.filename]#/dev# in the group. ==== `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 [.filename]#/home/username# or [.filename]#/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,bash] .... % 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="1,1", frame="none", options="header"] |=== | 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. |=== [[users-adduser]] ==== `adduser` -The recommended program for adding new users is man:adduser[8]. When a new user is added, this program automatically updates [.filename]#/etc/passwd# and [.filename]#/etc/group#. It also creates a home directory for the new user, copies in the default configuration files from [.filename]#/usr/shared/skel#, and can optionally mail the new user a welcome message. This utility must be run as the superuser. +The recommended program for adding new users is man:adduser[8]. When a new user is added, this program automatically updates [.filename]#/etc/passwd# and [.filename]#/etc/group#. It also creates a home directory for the new user, copies in the default configuration files from [.filename]#/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,bash] .... # adduser Username: jru Full name: J. Random User Uid (Leave empty for default): Login group [jru]: Login group is jru. Invite jru into other groups? []: wheel Login class [default]: Shell (sh csh tcsh zsh nologin) [sh]: zsh Home directory [/home/jru]: Home directory permissions (Leave empty for default): Use password-based authentication? [yes]: Use an empty password? (yes/no) [no]: Use a random password? (yes/no) [no]: Enter password: Enter password again: Lock out the account after creation? [no]: Username : jru Password : **** Full Name : J. Random User Uid : 1001 Class : Groups : jru wheel Home : /home/jru Shell : /usr/local/bin/zsh Locked : no OK? (yes/no): yes adduser: INFO: Successfully added (jru) to the user database. Add another user? (yes/no): no Goodbye! # .... ==== [NOTE] ==== Since the password is not echoed when typed, be careful to not mistype the password when creating the user account. ==== [[users-rmuser]] ==== `rmuser` 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. . Kills all processes owned by the user. . Removes the user from the system's local password file. . Optionally removes the user's home directory, if it is owned by the user. . Removes the incoming mail files belonging to the user from [.filename]#/var/mail#. . Removes all files owned by the user from temporary file storage areas such as [.filename]#/tmp#. . Finally, removes the username from all groups to which it belongs in [.filename]#/etc/group#. If a group becomes empty and the group name is the same as the username, the group is removed. This complements the per-user unique groups created by man:adduser[8]. man:rmuser[8] cannot be used to remove superuser accounts since that is almost always an indication of massive destruction. By default, an interactive mode is used, as shown in the following example. .`rmuser` Interactive Account Removal [example] ==== [source,bash] .... # rmuser jru Matching password entry: jru:*:1001:1001::0:0:J. Random User:/home/jru:/usr/local/bin/zsh Is this the entry you wish to remove? y Remove user's home directory (/home/jru)? y Removing user (jru): mailspool home passwd. # .... ==== [[users-chpass]] ==== `chpass` Any user can use man:chpass[1] to change their default shell and personal information associated with their user account. The superuser can use this utility to change additional account information for any user. When passed no options, aside from an optional username, man:chpass[1] displays an editor containing user information. When the user exits from the editor, the user database is updated with the new information. [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,bash] .... #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,bash] .... #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]] ==== `passwd` 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,bash] .... % passwd Changing local password for jru. Old password: New password: Retype new password: passwd: updating the database... passwd: done .... ==== The superuser can change any user's password by specifying the username when running man:passwd[1]. When this utility is run as the superuser, it will not prompt for the user's current password. This allows the password to be changed when a user cannot remember the original password. .Changing Another User's Password as the Superuser [example] ==== [source,bash] .... # passwd jru 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]] ==== `pw` The man:pw[8] utility can create, remove, modify, and display users and groups. It functions as a front end to the system user and group files. man:pw[8] has a very powerful set of command line options that make it suitable for use in shell scripts, but new users may find it more complicated than the other commands presented in this section. [[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 [.filename]#/etc/group#. This is a plain text file with four colon-delimited fields. The first field is the group name, the second is the encrypted password, the third the GID, and the fourth the comma-delimited list of members. For a more complete description of the syntax, refer to man:group[5]. The superuser can modify [.filename]#/etc/group# using a text editor. Alternatively, man:pw[8] can be used to add and edit groups. For example, to add a group called `teamtwo` and then confirm that it exists: .Adding a Group Using man:pw[8] [example] ==== [source,bash] .... # pw groupadd teamtwo # pw groupshow teamtwo teamtwo:*:1100: .... ==== In this example, `1100` is the GID of `teamtwo`. Right now, `teamtwo` has no members. This command will add `jru` as a member of `teamtwo`. .Adding User Accounts to a New Group Using man:pw[8] [example] ==== [source,bash] .... # pw groupmod teamtwo -M jru # pw groupshow teamtwo 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 [.filename]#/etc/group# and does not attempt to read additional data from [.filename]#/etc/passwd#. .Adding a New Member to a Group Using man:pw[8] [example] ==== [source,bash] .... # pw groupmod teamtwo -m db # pw groupshow teamtwo 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,bash] .... % id jru uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo) .... ==== In this example, `jru` is a member of the groups `jru` and `teamtwo`. For more information about this command and the format of [.filename]#/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 to man:ls[1] to view a long directory listing that includes a column of information about a file's permissions for the owner, group, and everyone else. For example, an `ls -l` in an arbitrary directory may show: [source,bash] .... % ls -l total 530 -rw-r--r-- 1 root wheel 512 Sep 5 12:31 myfile -rw-r--r-- 1 root wheel 512 Sep 5 12:31 otherfile -rw-r--r-- 1 root wheel 7680 Sep 5 12:31 email.txt .... The first (leftmost) character in the first column indicates whether this file is a regular file, a directory, a special character device, a socket, or any other special pseudo-file device. In this example, the `-` indicates a regular file. The next three characters, `rw-` in this example, give the permissions for the owner of the file. The next three characters, `r--`, give the permissions for the group that the file belongs to. The final three characters, `r--`, give the permissions for the rest of the world. A dash means that the permission is turned off. In this example, the permissions are set so the owner can read and write to the file, the group can read the file, and the rest of the world can only read the file. According to the table above, the permissions for this file would be `644`, where each digit represents the three parts of the file's permission. How does the system control permissions on devices? FreeBSD treats most hardware devices as a file that programs can open, read, and write data to. These special device files are stored in [.filename]#/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 other users from accessing _FILE_: [source,bash] .... % 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,bash] .... % 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 [.filename]#file1#, issue the following command: [source,bash] .... # chflags sunlink file1 .... To disable the system undeletable flag, put a "no" in front of the `sunlink`: [source,bash] .... # chflags nosunlink file1 .... To view the flags of a file, use `-lo` with man:ls[1]: [source,bash] .... # 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 set by prefixing a permission set with the number four (4) as shown in the following example: [source,bash] .... # chmod 4755 suidexample.sh .... The permissions on [.filename]#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,bash] .... Changing local password for trhodes Old Password: .... In terminal B: [source,bash] .... # ps aux | grep passwd .... [source,bash] .... trhodes 5232 0.0 0.2 3420 1608 0 R+ 2:10AM 0:00.00 grep passwd root 5211 0.0 0.2 3620 1724 2 I+ 2:09AM 0:00.01 passwd .... Although man:passwd[1] is run as a normal user, it is using the effective UID of `root`. The `setgid` permission performs the same function as the `setuid` permission; except that it alters the group settings. When an application or utility executes with this setting, it will be granted the permissions based on the group that owns the file, not the user who started the process. To set the `setgid` permission on a file, provide man:chmod[1] with a leading two (2): [source,bash] .... # chmod 2755 sgidexample.sh .... In the following listing, notice that the `s` is now in the field designated for the group permission settings: [source,bash] .... -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 [.filename]#/tmp#, by users who do not own the file. To utilize this permission, prefix the permission set with a one (1): [source,bash] .... # chmod 1777 /tmp .... The `sticky bit` permission will display as a `t` at the very end of the permission set: [source,bash] .... # ls -al / | grep tmp .... [source,bash] .... 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 [.filename]#/usr/#, [.filename]#/var/#, [.filename]#/tmp/#, [.filename]#/mnt/#, and [.filename]#/cdrom/#. These directories are usually referenced to entries in [.filename]#/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 [.filename]#/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. [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Directory | Description |[.filename]#/# |Root directory of the file system. |[.filename]#/bin/# |User utilities fundamental to both single-user and multi-user environments. |[.filename]#/boot/# |Programs and configuration files used during operating system bootstrap. |[.filename]#/boot/defaults/# |Default boot configuration files. Refer to man:loader.conf[5] for details. |[.filename]#/dev/# |Device nodes. Refer to man:intro[4] for details. |[.filename]#/etc/# |System configuration files and scripts. |[.filename]#/etc/defaults/# |Default system configuration files. Refer to man:rc[8] for details. |[.filename]#/etc/mail/# |Configuration files for mail transport agents such as man:sendmail[8]. |[.filename]#/etc/periodic/# |Scripts that run daily, weekly, and monthly, via man:cron[8]. Refer to man:periodic[8] for details. |[.filename]#/etc/ppp/# |man:ppp[8] configuration files. |[.filename]#/mnt/# |Empty directory commonly used by system administrators as a temporary mount point. |[.filename]#/proc/# |Process file system. Refer to man:procfs[5], man:mount_procfs[8] for details. |[.filename]#/rescue/# |Statically linked programs for emergency recovery as described in man:rescue[8]. |[.filename]#/root/# |Home directory for the `root` account. |[.filename]#/sbin/# |System programs and administration utilities fundamental to both single-user and multi-user environments. |[.filename]#/tmp/# |Temporary files which are usually _not_ preserved across a system reboot. A memory-based file system is often mounted at [.filename]#/tmp#. This can be automated using the tmpmfs-related variables of man:rc.conf[5] or with an entry in [.filename]#/etc/fstab#; refer to man:mdmfs[8] for details. |[.filename]#/usr/# |The majority of user utilities and applications. |[.filename]#/usr/bin/# |Common utilities, programming tools, and applications. |[.filename]#/usr/include/# |Standard C include files. |[.filename]#/usr/lib/# |Archive libraries. |[.filename]#/usr/libdata/# |Miscellaneous utility data files. |[.filename]#/usr/libexec/# |System daemons and system utilities executed by other programs. |[.filename]#/usr/local/# |Local executables and libraries. Also used as the default destination for the FreeBSD ports framework. Within [.filename]#/usr/local#, the general layout sketched out by man:hier[7] for [.filename]#/usr# should be used. Exceptions are the man directory, which is directly under [.filename]#/usr/local# rather than under [.filename]#/usr/local/share#, and the ports documentation is in [.filename]#share/doc/port#. |[.filename]#/usr/obj/# |Architecture-specific target tree produced by building the [.filename]#/usr/src# tree. |[.filename]#/usr/ports/# |The FreeBSD Ports Collection (optional). |[.filename]#/usr/sbin/# |System daemons and system utilities executed by users. -|[.filename]#/usr/shared/# +|[.filename]#/usr/share/# |Architecture-independent files. |[.filename]#/usr/src/# |BSD and/or local source files. |[.filename]#/var/# |Multi-purpose log, temporary, transient, and spool files. A memory-based file system is sometimes mounted at [.filename]#/var#. This can be automated using the varmfs-related variables in man:rc.conf[5] or with an entry in [.filename]#/etc/fstab#; refer to man:mdmfs[8] for details. |[.filename]#/var/log/# |Miscellaneous system log files. |[.filename]#/var/mail/# |User mailbox files. |[.filename]#/var/spool/# |Miscellaneous printer and mail system spooling directories. |[.filename]#/var/tmp/# |Temporary files which are usually preserved across a system reboot, unless [.filename]#/var# is a memory-based file system. |[.filename]#/var/yp/# |NIS maps. |=== [[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 [.filename]#readme.txt# and [.filename]#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 [.filename]#foo# contains a directory [.filename]#bar# which contains the file [.filename]#readme.txt#, the full name, or _path_, to the file is [.filename]#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 [.filename]#c:\foo\bar\readme.txt# on FreeBSD. 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[] 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[] Any files that are in the `B1` or `B2` directories can be reached with the path [.filename]#/A1/B1# or [.filename]#/A1/B2# as necessary. Any files that were in [.filename]#/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[] and the paths would be [.filename]#/A2/B1# and [.filename]#/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[] Or `C` could be mounted directly on to the `A` file system, under the `A1` directory: image::example-dir5.png[] 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 [.filename]#/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. ==== File systems are contained in partitions. This does not have the same meaning as the common usage of the term partition (for example, MS-DOS(R) partition), because of FreeBSD's UNIX(R) heritage. Each partition is identified by a letter from `a` through to `h`. Each partition can contain only one file system, which means that file systems are often described by either their typical mount point in the file system hierarchy, or the letter of the partition they are contained in. 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. Some partitions have certain conventions associated with them. [.informaltable] [cols="1,1", frame="none", options="header"] |=== | Partition | Convention |`a` |Normally contains the root file system. |`b` |Normally contains swap space. |`c` |Normally the same size as the enclosing slice. This allows utilities that need to work on the entire slice, such as a bad block scanner, to work on the `c` partition. A file system would not normally be created on this partition. |`d` |Partition `d` used to have a special meaning associated with it, although that is now gone and `d` may work as any normal partition. |=== Disks in FreeBSD are divided into slices, referred to in Windows(R) as partitions, which are numbered from 1 to 4. These are then divided into partitions, which contain file systems, and are labeled using letters. 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. Slices, "dangerously dedicated" physical drives, and other drives contain _partitions_, which are represented as letters from `a` to `h`. This letter is appended to the device name, so "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 slices, disk numbering starts at 0. Common codes are listed in <>. When referring to a partition, include the disk name, `s`, the slice number, and then the partition letter. Examples are shown in <>. <> shows a conceptual model of a disk layout. When installing FreeBSD, configure the disk slices, create partitions within the slice to be used for FreeBSD, create a file system or swap space in each partition, and decide where each file system will be mounted. [[disks-naming]] .Disk Device Names [cols="1,1", frame="none", options="header"] |=== | Drive Type | Drive Device Name |SATA and IDE hard drives |`ada` or `ad` |SCSI hard drives and USB storage devices |`da` |SATA and IDECD-ROM drives |`cd` or `acd` |SCSICD-ROM drives |`cd` |Floppy drives |`fd` |Assorted non-standard CD-ROM drives |`mcd` for Mitsumi CD-ROM and `scd` for Sony CD-ROM devices |SCSI tape drives |`sa` |IDE tape drives |`ast` |RAID drives |Examples include `aacd` for Adaptec(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, [.filename]#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 [.filename]#/var/#, `e` for [.filename]#/tmp/#, and `f` for [.filename]#/usr/#. Partition letter `c` refers to the entire slice, and so is not used for ordinary partitions. image::disk-layout.png[] ==== [[mount-unmount]] == Mounting and Unmounting File Systems The file system is best visualized as a tree, rooted, as it were, at [.filename]#/#. [.filename]#/dev#, [.filename]#/usr#, and the other directories in the root directory are branches, which may have their own branches, such as [.filename]#/usr/local#, and so on. There are various reasons to house some of these directories on separate file systems. [.filename]#/var# contains the directories [.filename]#log/#, [.filename]#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 [.filename]#/var# from [.filename]#/# 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 [.filename]#fstab# File During the boot process (crossref:boot[boot,The FreeBSD Booting Process]), file systems listed in [.filename]#/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 file systems should be checked. File systems that should be skipped should have their `passno` set to zero. The root file system needs to be checked before everything else and should have its `passno` set to one. The other file systems should be set to values greater than one. If more than one file system has the same `passno`, man:fsck[8] will attempt to check file systems in parallel if possible. Refer to man:fstab[5] for more information on the format of [.filename]#/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,bash] .... # mount device 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 [.filename]#/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,bash] .... % ps PID TT STAT TIME COMMAND 8203 0 Ss 0:00.59 /bin/csh 8895 0 R+ 0:00.00 ps .... The output from man:ps[1] is organized into a number of columns. The `PID` column displays the process ID. PIDs are assigned starting at 1, go up to 99999, then wrap around back to the beginning. However, a PID is not reassigned if it is already in use. The `TT` column shows the tty the program is running on and `STAT` shows the program's state. `TIME` is the amount of time the program has been running on the CPU. This is usually not the elapsed time since the program was started, as most programs spend a lot of time waiting for things to happen before they need to spend time on the CPU. Finally, `COMMAND` is the command that was used to start the program. A number of different options are available to change the information that is displayed. One of the most useful sets is `auxww`, where `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,bash] .... % top last pid: 9609; load averages: 0.56, 0.45, 0.36 up 0+00:20:03 10:21:46 107 processes: 2 running, 104 sleeping, 1 zombie CPU: 6.2% user, 0.1% nice, 8.2% system, 0.4% interrupt, 85.1% idle Mem: 541M Active, 450M Inact, 1333M Wired, 4064K Cache, 1498M Free ARC: 992M Total, 377M MFU, 589M MRU, 250K Anon, 5280K Header, 21M Other Swap: 2048M Total, 2048M Free PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAND 557 root 1 -21 r31 136M 42296K select 0 2:20 9.96% Xorg 8198 dru 2 52 0 449M 82736K select 3 0:08 5.96% kdeinit4 8311 dru 27 30 0 1150M 187M uwait 1 1:37 0.98% firefox 431 root 1 20 0 14268K 1728K select 0 0:06 0.98% moused 9551 dru 1 21 0 16600K 2660K CPU3 3 0:01 0.98% top 2357 dru 4 37 0 718M 141M select 0 0:21 0.00% kdeinit4 8705 dru 4 35 0 480M 98M select 2 0:20 0.00% kdeinit4 8076 dru 6 20 0 552M 113M uwait 0 0:12 0.00% soffice.bin 2623 root 1 30 10 12088K 1636K select 3 0:09 0.00% powerd 2338 dru 1 20 0 440M 84532K select 1 0:06 0.00% kwin 1427 dru 5 22 0 605M 86412K select 1 0:05 0.00% kdeinit4 .... The output is split into two sections. The header (the first five or six lines) shows the PID of the last process to run, the system load averages (which are a measure of how busy the system is), the system uptime (time since the last reboot) and the current time. The other figures in the header relate to how many processes are running, how much memory and swap space has been used, and how much time the system is spending in different CPU states. If the ZFS file system module has been loaded, an `ARC` line indicates how much data was read from the memory cache instead of from disk. Below the header is a series of columns containing similar information to the output from man:ps[1], such as the PID, username, amount of CPU time, and the command that started the process. By default, man:top[1] also displays the amount of memory space taken by the process. This is split into two columns: one for total size and one for resident size. Total size is how much memory the application has needed and the resident size is how much it is actually using now. man:top[1] automatically updates the display every two seconds. A different interval can be specified with `-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. [.procedure] **** .Procedure: Sending a Signal to a Process This example shows how to send a signal to man:inetd[8]. The man:inetd[8] configuration file is [.filename]#/etc/inetd.conf#, and man:inetd[8] will re-read this configuration file when it is sent a `SIGHUP`. . Find the PID of the process to send the signal to using man:pgrep[1]. In this example, the PID for man:inetd[8] is 198: + [source,bash] .... % pgrep -l inetd 198 inetd -wW .... + . Use man:kill[1] to send the signal. As man:inetd[8] is owned by `root`, use man:su[1] to become `root` first. + [source,bash] .... % su Password: # /bin/kill -s HUP 198 .... Like most UNIX(R) commands, man:kill[1] will not print any output if it is successful. If a signal is sent to a process not owned by that user, the message `kill: _PID_: Operation not permitted` will be displayed. Mistyping the PID will either send the signal to the wrong process, which could have negative results, or will send the signal to a PID that is not currently in use, resulting in the error `kill: _PID_: No such process`. [NOTE] ==== *Why Use `/bin/kill`?:* + Many shells provide `kill` as a built in command, meaning that the shell will send the signal directly, rather than running [.filename]#/bin/kill#. Be aware that different shells have a different syntax for specifying the name of the signal to send. Rather than try to learn all of them, it can be simpler to specify `/bin/kill`. ==== **** When sending other signals, substitute `TERM` or `KILL` with the name of the signal. [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 [.filename]#foobar# and [.filename]#football#. To delete [.filename]#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 [.filename]#foobar# and [.filename]#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="1,1", frame="none", options="header"] |=== | 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 [.filename]#/usr/local/bin/emacs# for the man:tcsh[1] shell: [source,bash] .... % setenv EDITOR /usr/local/bin/emacs .... The equivalent command for `bash` would be: [source,bash] .... % 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,bash] .... % chsh -s /usr/local/bin/bash .... [NOTE] ==== The new shell _must_ be present in [.filename]#/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,bash] .... # 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,bash] .... % ls > directory_listing.txt .... The directory contents will now be listed in [.filename]#directory_listing.txt#. Some commands can be used to read input, such as man:sort[1]. To sort this listing, redirect the input: [source,bash] .... % 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,bash] .... % 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,bash] .... % cat directory_listing.txt | sort | less .... In that example, the contents of [.filename]#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 are saved to [.filename]#/var/run/dmesg.boot#. Each device has a device name and number. For example, [.filename]#ada0# is the first SATA hard drive, while [.filename]#kbd0# represents the keyboard. Most devices in FreeBSD must be accessed through special files called device nodes, which are located in [.filename]#/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,bash] .... % man command .... where _command_ is the name of the command to learn about. For example, to learn more about man:ls[1], type: [source,bash] .... % 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,bash] .... % 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,bash] .... % 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 [.filename]#/usr/bin#, type: [source,bash] .... % cd /usr/bin % man -f * | more .... or [source,bash] .... % cd /usr/bin % 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,bash] .... % info .... For a brief introduction, type `h`. For a quick command reference, type `?`. diff --git a/documentation/content/en/books/handbook/bibliography/_index.adoc b/documentation/content/en/books/handbook/bibliography/_index.adoc index 6908533790..15cbd02d02 100644 --- a/documentation/content/en/books/handbook/bibliography/_index.adoc +++ b/documentation/content/en/books/handbook/bibliography/_index.adoc @@ -1,151 +1,151 @@ --- title: Appendix B. Bibliography part: Part V. Appendices prev: books/handbook/mirrors next: books/handbook/eresources --- [appendix] [[bibliography]] = Bibliography :doctype: book :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: B include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] While manual pages provide a definitive reference for individual pieces of the FreeBSD operating system, they seldom illustrate how to put the pieces together to make the whole operating system run smoothly. For this, there is no substitute for a good book or users' manual on UNIX(R) system administration. [[bibliography-freebsd]] == Books Specific to FreeBSD International books: * http://jdli.tw.FreeBSD.org/publication/book/freebsd2/index.htm[Using FreeBSD] (in Traditional Chinese), published by http://www.drmaster.com.tw/[Drmaster], 1997. ISBN 9-578-39435-7. * FreeBSD Unleashed (Simplified Chinese translation), published by http://www.hzbook.com/[China Machine Press]. ISBN 7-111-10201-0. * FreeBSD From Scratch Second Edition (in Simplified Chinese), published by China Machine Press. ISBN 7-111-10286-X. * FreeBSD Handbook Second Edition (Simplified Chinese translation), published by http://www.ptpress.com.cn/[Posts & Telecom Press]. ISBN 7-115-10541-3. * FreeBSD & Windows (in Simplified Chinese), published by http://www.tdpress.com/[China Railway Publishing House]. ISBN 7-113-03845-X * FreeBSD Internet Services HOWTO (in Simplified Chinese), published by China Railway Publishing House. ISBN 7-113-03423-3 * FreeBSD (in Japanese), published by CUTT. ISBN 4-906391-22-2 C3055 P2400E. * http://www.shoeisha.com/book/Detail.asp?bid=650[Complete Introduction to FreeBSD] (in Japanese), published by http://www.shoeisha.co.jp/[Shoeisha Co., Ltd]. ISBN 4-88135-473-6 P3600E. * http://www.ascii.co.jp/pb/book1/shinkan/detail/1322785.html[Personal UNIX Starter Kit FreeBSD] (in Japanese), published by http://www.ascii.co.jp/[ASCII]. ISBN 4-7561-1733-3 P3000E. * FreeBSD Handbook (Japanese translation), published by http://www.ascii.co.jp/[ASCII]. ISBN 4-7561-1580-2 P3800E. * FreeBSD mit Methode (in German), published by http://www.cul.de[Computer und Literatur Verlag]/Vertrieb Hanser, 1998. ISBN 3-932311-31-0. * http://www.mitp.de/vmi/mitp/detail/pWert/1343/[FreeBSD de Luxe] (in German), published by http://www.mitp.de[Verlag Modere Industrie], 2003. ISBN 3-8266-1343-0. * http://www.pc.mycom.co.jp/FreeBSD/install-manual.html[FreeBSD Install and Utilization Manual] (in Japanese), published by http://www.pc.mycom.co.jp/[Mainichi Communications Inc.], 1998. ISBN 4-8399-0112-0. * Onno W Purbo, Dodi Maryanto, Syahrial Hubbany, Widjil Widodo _http://maxwell.itb.ac.id/[Building Internet Server with FreeBSD]_ (in Indonesia Language), published by http://www.elexmedia.co.id/[Elex Media Komputindo]. * Absolute BSD: The Ultimate Guide to FreeBSD (Traditional Chinese translation), published by http://www.grandtech.com.tw/[GrandTech Press], 2003. ISBN 986-7944-92-5. * http://www.twbsd.org/cht/book/[The FreeBSD 6.0 Book] (in Traditional Chinese), published by Drmaster, 2006. ISBN 9-575-27878-X. English language books: * http://www.absoluteFreeBSD.com/[Absolute FreeBSD, 2nd Edition: The Complete Guide to FreeBSD], published by http://www.nostarch.com/[No Starch Press], 2007. ISBN: 978-1-59327-151-0 * http://www.freebsdmall.com/cgi-bin/fm/bsdcomp[The Complete FreeBSD], published by http://www.oreilly.com/[O'Reilly], 2003. ISBN: 0596005164 * http://www.freebsd-corp-net-guide.com/[The FreeBSD Corporate Networker's Guide], published by http://www.awl.com/aw/[Addison-Wesley], 2000. ISBN: 0201704811 * http://andrsn.stanford.edu/FreeBSD/introbook/[FreeBSD: An Open-Source Operating System for Your Personal Computer], published by The Bit Tree Press, 2001. ISBN: 0971204500 * Teach Yourself FreeBSD in 24 Hours, published by http://www.samspublishing.com/[Sams], 2002. ISBN: 0672324245 * FreeBSD 6 Unleashed, published by http://www.samspublishing.com/[Sams], 2006. ISBN: 0672328755 * FreeBSD: The Complete Reference, published by http://books.mcgraw-hill.com[McGrawHill], 2003. ISBN: 0072224096 [[bibliography-userguides]] == Users' Guides * Ohio State University has written a http://www.cs.duke.edu/csl/docs/unix_course/[UNIX Introductory Course] which is available online in HTML and PostScript format. + An Italian https://www.FreeBSD.org/doc/it_IT.ISO8859-15/books/unix-introduction/[translation] of this document is available as part of the FreeBSD Italian Documentation Project. * http://www.jp.FreeBSD.org/[Jpman Project, Japan FreeBSD Users Group]. FreeBSD User's Reference Manual (Japanese translation). http://www.pc.mycom.co.jp/[Mainichi Communications Inc.], 1998. ISBN4-8399-0088-4 P3800E. * http://www.ed.ac.uk/[Edinburgh University] has written an http://www.ed.ac.uk/information-services/help-consultancy/is-skills/catalogue/program-op-sys-catalogue/unix1[Online Guide] for newcomers to the UNIX environment. [[bibliography-adminguides]] == Administrators' Guides * http://www.jp.FreeBSD.org/[Jpman Project, Japan FreeBSD Users Group]. FreeBSD System Administrator's Manual (Japanese translation). http://www.pc.mycom.co.jp/[Mainichi Communications Inc.], 1998. ISBN4-8399-0109-0 P3300E. * Dreyfus, Emmanuel. http://www.eyrolles.com/Informatique/Livre/9782212114638/[Cahiers de l'Admin: BSD] 2nd Ed. (in French), Eyrolles, 2004. ISBN 2-212-11463-X [[bibliography-programmers]] == Programmers' Guides * Computer Systems Research Group, UC Berkeley. _4.4BSD Programmer's Reference Manual_. O'Reilly & Associates, Inc., 1994. ISBN 1-56592-078-3 * Computer Systems Research Group, UC Berkeley. _4.4BSD Programmer's Supplementary Documents_. O'Reilly & Associates, Inc., 1994. ISBN 1-56592-079-1 * Harbison, Samuel P. and Steele, Guy L. Jr. _C: A Reference Manual_. 4th Ed. Prentice Hall, 1995. ISBN 0-13-326224-3 * Kernighan, Brian and Dennis M. Ritchie. _The C Programming Language_. 2nd Ed. PTR Prentice Hall, 1988. ISBN 0-13-110362-8 * Lehey, Greg. _Porting UNIX Software_. O'Reilly & Associates, Inc., 1995. ISBN 1-56592-126-7 * Plauger, P. J. _The Standard C Library_. Prentice Hall, 1992. ISBN 0-13-131509-9 * Spinellis, Diomidis. http://www.spinellis.gr/codereading/[Code Reading: The Open Source Perspective]. Addison-Wesley, 2003. ISBN 0-201-79940-5 * Spinellis, Diomidis. http://www.spinellis.gr/codequality/[Code Quality: The Open Source Perspective]. Addison-Wesley, 2006. ISBN 0-321-16607-8 * Stevens, W. Richard and Stephen A. Rago. _Advanced Programming in the UNIX Environment_. 2nd Ed. Reading, Mass. : Addison-Wesley, 2005. ISBN 0-201-43307-9 * Stevens, W. Richard. _UNIX Network Programming_. 2nd Ed, PTR Prentice Hall, 1998. ISBN 0-13-490012-X [[bibliography-osinternals]] == Operating System Internals * Andleigh, Prabhat K. _UNIX System Architecture_. Prentice-Hall, Inc., 1990. ISBN 0-13-949843-5 * Jolitz, William. "Porting UNIX to the 386". _Dr. Dobb's Journal_. January 1991-July 1992. * Leffler, Samuel J., Marshall Kirk McKusick, Michael J Karels and John Quarterman _The Design and Implementation of the 4.3BSD UNIX Operating System_. Reading, Mass. : Addison-Wesley, 1989. ISBN 0-201-06196-1 * Leffler, Samuel J., Marshall Kirk McKusick, _The Design and Implementation of the 4.3BSD UNIX Operating System: Answer Book_. Reading, Mass. : Addison-Wesley, 1991. ISBN 0-201-54629-9 * McKusick, Marshall Kirk, Keith Bostic, Michael J Karels, and John Quarterman. _The Design and Implementation of the 4.4BSD Operating System_. Reading, Mass. : Addison-Wesley, 1996. ISBN 0-201-54979-4 + (Chapter 2 of this book is available link:{design-44bsd}[online] as part of the FreeBSD Documentation Project.) * Marshall Kirk McKusick, George V. Neville-Neil _The Design and Implementation of the FreeBSD Operating System_. Boston, Mass. : Addison-Wesley, 2004. ISBN 0-201-70245-2 * Marshall Kirk McKusick, George V. Neville-Neil, Robert N. M. Watson _The Design and Implementation of the FreeBSD Operating System, 2nd Ed._. Westford, Mass. : Pearson Education, Inc., 2014. ISBN 0-321-96897-2 * Stevens, W. Richard. _TCP/IP Illustrated, Volume 1: The Protocols_. Reading, Mass. : Addison-Wesley, 1996. ISBN 0-201-63346-9 * Schimmel, Curt. _Unix Systems for Modern Architectures_. Reading, Mass. : Addison-Wesley, 1994. ISBN 0-201-63338-8 * Stevens, W. Richard. _TCP/IP Illustrated, Volume 3: TCP for Transactions, HTTP, NNTP and the UNIX Domain Protocols_. Reading, Mass. : Addison-Wesley, 1996. ISBN 0-201-63495-3 * Vahalia, Uresh. _UNIX Internals -- The New Frontiers_. Prentice Hall, 1996. ISBN 0-13-101908-2 * Wright, Gary R. and W. Richard Stevens. _TCP/IP Illustrated, Volume 2: The Implementation_. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-63354-X [[bibliography-security]] == Security Reference * Cheswick, William R. and Steven M. Bellovin. _Firewalls and Internet Security: Repelling the Wily Hacker_. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-63357-4 * Garfinkel, Simson. _PGP Pretty Good Privacy_ O'Reilly & Associates, Inc., 1995. ISBN 1-56592-098-8 [[bibliography-hardware]] == Hardware Reference * Anderson, Don and Tom Shanley. _Pentium Processor System Architecture_. 2nd Ed. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-40992-5 * Ferraro, Richard F. _Programmer's Guide to the EGA, VGA, and Super VGA Cards_. 3rd ed. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-62490-7 * Intel Corporation publishes documentation on their CPUs, chipsets and standards on their http://developer.intel.com/[developer web site], usually as PDF files. * Shanley, Tom. _80486 System Architecture_. 3rd Ed. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-40994-1 * Shanley, Tom. _ISA System Architecture_. 3rd Ed. Reading, Mass. : Addison-Wesley, 1995. ISBN 0-201-40996-8 * Shanley, Tom. _PCI System Architecture_. 4th Ed. Reading, Mass. : Addison-Wesley, 1999. ISBN 0-201-30974-2 * Van Gilluwe, Frank. _The Undocumented PC_, 2nd Ed. Reading, Mass: Addison-Wesley Pub. Co., 1996. ISBN 0-201-47950-8 * Messmer, Hans-Peter. _The Indispensable PC Hardware Book_, 4th Ed. Reading, Mass : Addison-Wesley Pub. Co., 2002. ISBN 0-201-59616-4 [[bibliography-history]] == UNIX(R) History * Lion, John _Lion's Commentary on UNIX, 6th Ed. With Source Code_. ITP Media Group, 1996. ISBN 1573980137 * Raymond, Eric S. _The New Hacker's Dictionary, 3rd edition_. MIT Press, 1996. ISBN 0-262-68092-0. Also known as the http://www.catb.org/~esr/jargon/html/index.html[Jargon File] * Salus, Peter H. _A quarter century of UNIX_. Addison-Wesley Publishing Company, Inc., 1994. ISBN 0-201-54777-5 * Simon Garfinkel, Daniel Weise, Steven Strassmann. _The UNIX-HATERS Handbook_. IDG Books Worldwide, Inc., 1994. ISBN 1-56884-203-1. Out of print, but available http://www.simson.net/ref/ugh.pdf[online]. * Don Libes, Sandy Ressler _Life with UNIX_ - special edition. Prentice-Hall, Inc., 1989. ISBN 0-13-536657-7 -* _The BSD family tree_. https://svnweb.freebsd.org/base/head/shared/misc/bsd-family-tree?view=co[https://svnweb.freebsd.org/base/head/shared/misc/bsd-family-tree?view=co] or link:file://localhost/usr/shared/misc/bsd-family-tree[/usr/shared/misc/bsd-family-tree] on a FreeBSD machine. +* _The BSD family tree_. https://svnweb.freebsd.org/base/head/shared/misc/bsd-family-tree?view=co[https://svnweb.freebsd.org/base/head/shared/misc/bsd-family-tree?view=co] or link:file://localhost/usr/share/misc/bsd-family-tree[/usr/share/misc/bsd-family-tree] on a FreeBSD machine. * _Networked Computer Science Technical Reports Library_. * _Old BSD releases from the Computer Systems Research group (CSRG)_. http://www.mckusick.com/csrg/[http://www.mckusick.com/csrg/]: The 4CD set covers all BSD versions from 1BSD to 4.4BSD and 4.4BSD-Lite2 (but not 2.11BSD, unfortunately). The last disk also holds the final sources plus the SCCS files. * Kernighan, Brian _Unix: A History and a Memoir_. Kindle Direct Publishing, 2020. ISBN 978-169597855-3 [[bibliography-journals]] == Periodicals, Journals, and Magazines * http://www.admin-magazin.de/[Admin Magazin] (in German), published by Medialinx AG. ISSN: 2190-1066 * http://www.bsdmag.org/[BSD Magazine], published by Software Press Sp. z o.o. SK. ISSN: 1898-9144 * http://www.bsdnow.tv/[BSD Now - Video Podcast], published by Jupiter Broadcasting LLC * http://bsdtalk.blogspot.com/[BSD Talk Podcast], by Will Backman * http://freebsdjournal.com/[FreeBSD Journal], published by S&W Publishing, sponsored by The FreeBSD Foundation. ISBN: 978-0-615-88479-0 :sectnums: :sectnumlevels: 6 diff --git a/documentation/content/en/books/handbook/config/_index.adoc b/documentation/content/en/books/handbook/config/_index.adoc index 76174b2a3b..d44ac80d4a 100644 --- a/documentation/content/en/books/handbook/config/_index.adoc +++ b/documentation/content/en/books/handbook/config/_index.adoc @@ -1,1520 +1,1520 @@ --- title: Chapter 12. Configuration and Tuning part: Part III. System Administration prev: books/handbook/partiii next: books/handbook/boot --- [[config-tuning]] = Configuration and Tuning :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 12 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/x11/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/x11/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/x11/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[config-synopsis]] == Synopsis One of the important aspects of FreeBSD is proper system configuration. This chapter explains much of the FreeBSD configuration process, including some of the parameters which can be set to tune a FreeBSD system. After reading this chapter, you will know: * The basics of [.filename]#rc.conf# configuration and [.filename]#/usr/local/etc/rc.d# startup scripts. * How to configure and test a network card. * How to configure virtual hosts on network devices. * How to use the various configuration files in [.filename]#/etc#. * How to tune FreeBSD using man:sysctl[8] variables. * How to tune disk performance and modify kernel limitations. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Be familiar with the basics of kernel configuration and compilation (crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]). [[configtuning-starting-services]] == Starting Services Many users install third party software on FreeBSD from the Ports Collection and require the installed services to be started upon system initialization. Services, such as package:mail/postfix[] or package:www/apache22[] are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting third party software. In FreeBSD, most included services, such as man:cron[8], are started through the system startup scripts. === Extended Application Configuration Now that FreeBSD includes [.filename]#rc.d#, configuration of application startup is easier and provides more features. Using the key words discussed in <>, applications can be set to start after certain other services and extra flags can be passed through [.filename]#/etc/rc.conf# in place of hard coded flags in the startup script. A basic script may look similar to the following: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... This script will ensure that the provided `utility` will be started after the `DAEMON` pseudo-service. It also provides a method for setting and tracking the process ID (PID). This application could then have the following line placed in [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... This method allows for easier manipulation of command line arguments, inclusion of the default functions provided in [.filename]#/etc/rc.subr#, compatibility with man:rcorder[8], and provides for easier configuration via [.filename]#rc.conf#. === Using Services to Start Services Other services can be started using man:inetd[8]. Working with man:inetd[8] and its configuration is described in depth in crossref:network-servers[network-inetd,“The inetd Super-Server”]. In some cases, it may make more sense to use man:cron[8] to start system services. This approach has a number of advantages as man:cron[8] runs these processes as the owner of the man:crontab[5]. This allows regular users to start and maintain their own applications. The `@reboot` feature of man:cron[8], may be used in place of the time specification. This causes the job to run when man:cron[8] is started, normally during system initialization. [[configtuning-cron]] == Configuring man:cron[8] One of the most useful utilities in FreeBSD is cron. This utility runs in the background and regularly checks [.filename]#/etc/crontab# for tasks to execute and searches [.filename]#/var/cron/tabs# for custom crontab files. These files are used to schedule tasks which cron runs at the specified times. Each entry in a crontab defines a task to run and is known as a _cron job_. Two different types of configuration files are used: the system crontab, which should not be modified, and user crontabs, which can be created and edited as needed. The format used by these files is documented in man:crontab[5]. The format of the system crontab, [.filename]#/etc/crontab# includes a `who` column which does not exist in user crontabs. In the system crontab, cron runs the command as the user specified in this column. In a user crontab, all commands run as the user who created the crontab. User crontabs allow individual users to schedule their own tasks. The `root` user can also have a user [.filename]#crontab# which can be used to schedule tasks that do not exist in the system [.filename]#crontab#. Here is a sample entry from the system crontab, [.filename]#/etc/crontab#: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD$ # <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> Lines that begin with the `#` character are comments. A comment can be placed in the file as a reminder of what and why a desired action is performed. Comments cannot be on the same line as a command or else they will be interpreted as part of the command; they must be on a new line. Blank lines are ignored. <.> The equals (`=`) character is used to define any environment settings. In this example, it is used to define the `SHELL` and `PATH`. If the `SHELL` is omitted, cron will use the default Bourne shell. If the `PATH` is omitted, the full path must be given to the command or script to run. <.> This line defines the seven fields used in a system crontab: `minute`, `hour`, `mday`, `month`, `wday`, `who`, and `command`. The `minute` field is the time in minutes when the specified command will be run, the `hour` is the hour when the specified command will be run, the `mday` is the day of the month, `month` is the month, and `wday` is the day of the week. These fields must be numeric values, representing the twenty-four hour clock, or a `*`, representing all values for that field. The `who` field only exists in the system crontab and specifies which user the command should be run as. The last field is the command to be executed. <.> This entry defines the values for this cron job. The `\*/5`, followed by several more `*` characters, specifies that `/usr/libexec/atrun` is invoked by `root` every five minutes of every hour, of every day and day of the week, of every month.Commands can include any number of switches. However, commands which extend to multiple lines need to be broken with the backslash "\" continuation character. [[configtuning-installcrontab]] === Creating a User Crontab To create a user crontab, invoke `crontab` in editor mode: [source,bash] .... % crontab -e .... This will open the user's crontab using the default text editor. The first time a user runs this command, it will open an empty file. Once a user creates a crontab, this command will open that file for editing. It is useful to add these lines to the top of the crontab file in order to set the environment variables and to remember the meanings of the fields in the crontab: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... Then add a line for each command or script to run, specifying the time to run the command. This example runs the specified custom Bourne shell script every day at two in the afternoon. Since the path to the script is not specified in `PATH`, the full path to the script is given: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== Before using a custom script, make sure it is executable and test it with the limited set of environment variables set by cron. To replicate the environment that would be used to run the above cron entry, use: [.programlisting] .... env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... The environment set by cron is discussed in man:crontab[5]. Checking that scripts operate correctly in a cron environment is especially important if they include any commands that delete files using wildcards. ==== When finished editing the crontab, save the file. It will automatically be installed and cron will read the crontab and run its cron jobs at their specified times. To list the cron jobs in a crontab, use this command: [source,bash] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... To remove all of the cron jobs in a user crontab: [source,bash] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == Managing Services in FreeBSD FreeBSD uses the man:rc[8] system of startup scripts during system initialization and for managing services. The scripts listed in [.filename]#/etc/rc.d# provide basic services which can be controlled with the `start`, `stop`, and `restart` options to man:service[8]. For instance, man:sshd[8] can be restarted with the following command: [source,bash] .... # service sshd restart .... This procedure can be used to start services on a running system. Services will be started automatically at boot time as specified in man:rc.conf[5]. For example, to enable man:natd[8] at system startup, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... If a `natd_enable="NO"` line is already present, change the `NO` to `YES`. The man:rc[8] scripts will automatically load any dependent services during the next boot, as described below. Since the man:rc[8] system is primarily intended to start and stop services at system startup and shutdown time, the `start`, `stop` and `restart` options will only perform their action if the appropriate [.filename]#/etc/rc.conf# variable is set. For instance, `sshd restart` will only work if `sshd_enable` is set to `YES` in [.filename]#/etc/rc.conf#. To `start`, `stop` or `restart` a service regardless of the settings in [.filename]#/etc/rc.conf#, these commands should be prefixed with "one". For instance, to restart man:sshd[8] regardless of the current [.filename]#/etc/rc.conf# setting, execute the following command: [source,bash] .... # service sshd onerestart .... To check if a service is enabled in [.filename]#/etc/rc.conf#, run the appropriate man:rc[8] script with `rcvar`. This example checks to see if man:sshd[8] is enabled in [.filename]#/etc/rc.conf#: [source,bash] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== The `# sshd` line is output from the above command, not a `root` console. ==== To determine whether or not a service is running, use `status`. For instance, to verify that man:sshd[8] is running: [source,bash] .... # service sshd status sshd is running as pid 433. .... In some cases, it is also possible to `reload` a service. This attempts to send a signal to an individual service, forcing the service to reload its configuration files. In most cases, this means sending the service a `SIGHUP` signal. Support for this feature is not included for every service. The man:rc[8] system is used for network services and it also contributes to most of the system initialization. For instance, when the [.filename]#/etc/rc.d/bgfsck# script is executed, it prints out the following message: [source,bash] .... Starting background file system checks in 60 seconds. .... This script is used for background file system checks, which occur only during system initialization. Many system services depend on other services to function properly. For example, man:yp[8] and other RPC-based services may fail to start until after the man:rpcbind[8] service has started. To resolve this issue, information about dependencies and other meta-data is included in the comments at the top of each startup script. The man:rcorder[8] program is used to parse these comments during system initialization to determine the order in which system services should be invoked to satisfy the dependencies. The following key word must be included in all startup scripts as it is required by man:rc.subr[8] to "enable" the startup script: * `PROVIDE`: Specifies the services this file provides. The following key words may be included at the top of each startup script. They are not strictly necessary, but are useful as hints to man:rcorder[8]: * `REQUIRE`: Lists services which are required for this service. The script containing this key word will run _after_ the specified services. * `BEFORE`: Lists services which depend on this service. The script containing this key word will run _before_ the specified services. By carefully setting these keywords for each startup script, an administrator has a fine-grained level of control of the startup order of the scripts, without the need for "runlevels" used by some UNIX(R) operating systems. Additional information can be found in man:rc[8] and man:rc.subr[8]. Refer to link:{rc-scripting}[this article] for instructions on how to create custom man:rc[8] scripts. [[configtuning-core-configuration]] === Managing System-Specific Configuration The principal location for system configuration information is [.filename]#/etc/rc.conf#. This file contains a wide range of configuration information and it is read at system startup to configure the system. It provides the configuration information for the [.filename]#rc*# files. The entries in [.filename]#/etc/rc.conf# override the default settings in [.filename]#/etc/defaults/rc.conf#. The file containing the default settings should not be edited. Instead, all system-specific changes should be made to [.filename]#/etc/rc.conf#. A number of strategies may be applied in clustered applications to separate site-wide configuration from system-specific configuration in order to reduce administration overhead. The recommended approach is to place system-specific configuration into [.filename]#/etc/rc.conf.local#. For example, these entries in [.filename]#/etc/rc.conf# apply to all systems: [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... Whereas these entries in [.filename]#/etc/rc.conf.local# apply to this system only: [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Distribute [.filename]#/etc/rc.conf# to every system using an application such as rsync or puppet, while [.filename]#/etc/rc.conf.local# remains unique. Upgrading the system will not overwrite [.filename]#/etc/rc.conf#, so system configuration information will not be lost. [TIP] ==== Both [.filename]#/etc/rc.conf# and [.filename]#/etc/rc.conf.local# are parsed by man:sh[1]. This allows system operators to create complex configuration scenarios. Refer to man:rc.conf[5] for further information on this topic. ==== [[config-network-setup]] == Setting Up Network Interface Cards Adding and configuring a network interface card (NIC) is a common task for any FreeBSD administrator. === Locating the Correct Driver First, determine the model of the NIC and the chip it uses. FreeBSD supports a wide variety of NICs. Check the Hardware Compatibility List for the FreeBSD release to see if the NIC is supported. If the NIC is supported, determine the name of the FreeBSD driver for the NIC. Refer to [.filename]#/usr/src/sys/conf/NOTES# and [.filename]#/usr/src/sys/arch/conf/NOTES# for the list of NIC drivers with some information about the supported chipsets. When in doubt, read the manual page of the driver as it will provide more information about the supported hardware and any known limitations of the driver. The drivers for common NICs are already present in the [.filename]#GENERIC# kernel, meaning the NIC should be probed during boot. The system's boot messages can be viewed by typing `more /var/run/dmesg.boot` and using the spacebar to scroll through the text. In this example, two Ethernet NICs using the man:dc[4] driver are present on the system: [source,bash] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... If the driver for the NIC is not present in [.filename]#GENERIC#, but a driver is available, the driver will need to be loaded before the NIC can be configured and used. This may be accomplished in one of two ways: * The easiest way is to load a kernel module for the NIC using man:kldload[8]. To also automatically load the driver at boot time, add the appropriate line to [.filename]#/boot/loader.conf#. Not all NIC drivers are available as modules. * Alternatively, statically compile support for the NIC into a custom kernel. Refer to [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# and the manual page of the driver to determine which line to add to the custom kernel configuration file. For more information about recompiling the kernel, refer to crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. If the NIC was detected at boot, the kernel does not need to be recompiled. [[config-network-ndis]] ==== Using Windows(R) NDIS Drivers Unfortunately, there are still many vendors that do not provide schematics for their drivers to the open source community because they regard such information as trade secrets. Consequently, the developers of FreeBSD and other operating systems are left with two choices: develop the drivers by a long and pain-staking process of reverse engineering or using the existing driver binaries available for Microsoft(R) Windows(R) platforms. FreeBSD provides "native" support for the Network Driver Interface Specification (NDIS). It includes man:ndisgen[8] which can be used to convert a Windows(R) XP driver into a format that can be used on FreeBSD. As the man:ndis[4] driver uses a Windows(R) XP binary, it only runs on i386(TM) and amd64 systems. PCI, CardBus, PCMCIA, and USB devices are supported. To use man:ndisgen[8], three things are needed: . FreeBSD kernel sources. . A Windows(R) XP driver binary with a [.filename]#.SYS# extension. . A Windows(R) XP driver configuration file with a [.filename]#.INF# extension. Download the [.filename]#.SYS# and [.filename]#.INF# files for the specific NIC. Generally, these can be found on the driver CD or at the vendor's website. The following examples use [.filename]#W32DRIVER.SYS# and [.filename]#W32DRIVER.INF#. The driver bit width must match the version of FreeBSD. For FreeBSD/i386, use a Windows(R) 32-bit driver. For FreeBSD/amd64, a Windows(R) 64-bit driver is needed. The next step is to compile the driver binary into a loadable kernel module. As `root`, use man:ndisgen[8]: [source,bash] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... This command is interactive and prompts for any extra information it requires. A new kernel module will be generated in the current directory. Use man:kldload[8] to load the new module: [source,bash] .... # kldload ./W32DRIVER_SYS.ko .... In addition to the generated kernel module, the [.filename]#ndis.ko# and [.filename]#if_ndis.ko# modules must be loaded. This should happen automatically when any module that depends on man:ndis[4] is loaded. If not, load them manually, using the following commands: [source,bash] .... # kldload ndis # kldload if_ndis .... The first command loads the man:ndis[4] miniport driver wrapper and the second loads the generated NIC driver. Check man:dmesg[8] to see if there were any load errors. If all went well, the output should be similar to the following: [source,bash] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... From here, [.filename]#ndis0# can be configured like any other NIC. To configure the system to load the man:ndis[4] modules at boot time, copy the generated module, [.filename]#W32DRIVER_SYS.ko#, to [.filename]#/boot/modules#. Then, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Configuring the Network Card Once the right driver is loaded for the NIC, the card needs to be configured. It may have been configured at installation time by man:bsdinstall[8]. To display the NIC configuration, enter the following command: [source,bash] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... In this example, the following devices were displayed: * [.filename]#dc0#: The first Ethernet interface. * [.filename]#dc1#: The second Ethernet interface. * [.filename]#lo0#: The loopback device. FreeBSD uses the driver name followed by the order in which the card is detected at boot to name the NIC. For example, [.filename]#sis2# is the third NIC on the system using the man:sis[4] driver. In this example, [.filename]#dc0# is up and running. The key indicators are: . `UP` means that the card is configured and ready. . The card has an Internet (`inet`) address, `192.168.1.3`. . It has a valid subnet mask (`netmask`), where `0xffffff00` is the same as `255.255.255.0`. . It has a valid broadcast address, `192.168.1.255`. . The MAC address of the card (`ether`) is `00:a0:cc:da:da:da`. . The physical media selection is on autoselection mode (`media: Ethernet autoselect (100baseTX )`). In this example, [.filename]#dc1# is configured to run with `10baseT/UTP` media. For more information on available media types for a driver, refer to its manual page. . The status of the link (`status`) is `active`, indicating that the carrier signal is detected. For [.filename]#dc1#, the `status: no carrier` status is normal when an Ethernet cable is not plugged into the card. If the man:ifconfig[8] output had shown something similar to: [source,bash] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... it would indicate the card has not been configured. The card must be configured as `root`. The NIC configuration can be performed from the command line with man:ifconfig[8] but will not persist after a reboot unless the configuration is also added to [.filename]#/etc/rc.conf#. If a DHCP server is present on the LAN, just add this line: [.programlisting] .... ifconfig_dc0="DHCP" .... Replace _dc0_ with the correct value for the system. The line added, then, follow the instructions given in <>. [NOTE] ==== If the network was configured during installation, some entries for the NIC(s) may be already present. Double check [.filename]#/etc/rc.conf# before adding any lines. ==== If there is no DHCP server, the NIC(s) must be configured manually. Add a line for each NIC present on the system, as seen in this example: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Replace [.filename]#dc0# and [.filename]#dc1# and the IP address information with the correct values for the system. Refer to the man page for the driver, man:ifconfig[8], and man:rc.conf[5] for more details about the allowed options and the syntax of [.filename]#/etc/rc.conf#. -If the network is not using DNS, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/shared/examples/etc/hosts#. +If the network is not using DNS, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/share/examples/etc/hosts#. [NOTE] ==== If there is no DHCP server and access to the Internet is needed, manually configure the default gateway and the nameserver: [source,bash] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === Testing and Troubleshooting Once the necessary changes to [.filename]#/etc/rc.conf# are saved, a reboot can be used to test the network configuration and to verify that the system restarts without any configuration errors. Alternatively, apply the settings to the networking system with this command: [source,bash] .... # service netif restart .... [NOTE] ==== If a default gateway has been set in [.filename]#/etc/rc.conf#, also issue this command: [source,bash] .... # service routing restart .... ==== Once the networking system has been relaunched, test the NICs. ==== Testing the Ethernet Card To verify that an Ethernet card is configured correctly, man:ping[8] the interface itself, and then man:ping[8] another machine on the LAN: [source,bash] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,bash] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... -To test network resolution, use the host name instead of the IP address. If there is no DNS server on the network, [.filename]#/etc/hosts# must first be configured. To this purpose, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/shared/examples/etc/hosts#. +To test network resolution, use the host name instead of the IP address. If there is no DNS server on the network, [.filename]#/etc/hosts# must first be configured. To this purpose, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/share/examples/etc/hosts#. ==== Troubleshooting When troubleshooting hardware and software configurations, check the simple things first. Is the network cable plugged in? Are the network services properly configured? Is the firewall configured correctly? Is the NIC supported by FreeBSD? Before sending a bug report, always check the Hardware Notes, update the version of FreeBSD to the latest STABLE version, check the mailing list archives, and search the Internet. If the card works, yet performance is poor, read through man:tuning[7]. Also, check the network configuration as incorrect network settings can cause slow connections. Some users experience one or two `device timeout` messages, which is normal for some cards. If they continue, or are bothersome, determine if the device is conflicting with another device. Double check the cable connections. Consider trying another card. To resolve `watchdog timeout` errors, first check the network cable. Many cards require a PCI slot which supports bus mastering. On some old motherboards, only one PCI slot allows it, usually slot 0. Check the NIC and the motherboard documentation to determine if that may be the problem. `No route to host` messages occur if the system is unable to route a packet to the destination host. This can happen if no default route is specified or if a cable is unplugged. Check the output of `netstat -rn` and make sure there is a valid route to the host. If there is not, read crossref:advanced-networking[network-routing,“Gateways and Routes”]. `ping: sendto: Permission denied` error messages are often caused by a misconfigured firewall. If a firewall is enabled on FreeBSD but no rules have been defined, the default policy is to deny all traffic, even man:ping[8]. Refer to crossref:firewalls[firewalls,Firewalls] for more information. Sometimes performance of the card is poor or below average. In these cases, try setting the media selection mode from `autoselect` to the correct media selection. While this works for most hardware, it may or may not resolve the issue. Again, check all the network settings, and refer to man:tuning[7]. [[configtuning-virtual-hosts]] == Virtual Hosts A common use of FreeBSD is virtual site hosting, where one server appears to the network as many servers. This is achieved by assigning multiple network addresses to a single interface. A given network interface has one "real" address, and may have any number of "alias" addresses. These aliases are normally added by placing alias entries in [.filename]#/etc/rc.conf#, as seen in this example: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Alias entries must start with `alias__0__` using a sequential number such as `alias0`, `alias1`, and so on. The configuration process will stop at the first missing number. The calculation of alias netmasks is important. For a given interface, there must be one address which correctly represents the network's netmask. Any other addresses which fall within this network must have a netmask of all ``1``s, expressed as either `255.255.255.255` or `0xffffffff`. For example, consider the case where the [.filename]#fxp0# interface is connected to two networks: `10.1.1.0` with a netmask of `255.255.255.0` and `202.0.75.16` with a netmask of `255.255.255.240`. The system is to be configured to appear in the ranges `10.1.1.1` through `10.1.1.5` and `202.0.75.17` through `202.0.75.20`. Only the first address in a given network range should have a real netmask. All the rest (`10.1.1.2` through `10.1.1.5` and `202.0.75.18` through `202.0.75.20`) must be configured with a netmask of `255.255.255.255`. The following [.filename]#/etc/rc.conf# entries configure the adapter correctly for this scenario: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... A simpler way to express this is with a space-separated list of IP address ranges. The first address will be given the indicated subnet mask and the additional addresses will have a subnet mask of `255.255.255.255`. [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == Configuring System Logging Generating and reading system logs is an important aspect of system administration. The information in system logs can be used to detect hardware and software issues as well as application and system configuration errors. This information also plays an important role in security auditing and incident response. Most system daemons and applications will generate log entries. FreeBSD provides a system logger, syslogd, to manage logging. By default, syslogd is started when the system boots. This is controlled by the variable `syslogd_enable` in [.filename]#/etc/rc.conf#. There are numerous application arguments that can be set using `syslogd_flags` in [.filename]#/etc/rc.conf#. Refer to man:syslogd[8] for more information on the available arguments. This section describes how to configure the FreeBSD system logger for both local and remote logging and how to perform log rotation and log management. === Configuring Local Logging The configuration file, [.filename]#/etc/syslog.conf#, controls what syslogd does with log entries as they are received. There are several parameters to control the handling of incoming events. The _facility_ describes which subsystem generated the message, such as the kernel or a daemon, and the _level_ describes the severity of the event that occurred. This makes it possible to configure if and where a log message is logged, depending on the facility and level. It is also possible to take action depending on the application that sent the message, and in the case of remote logging, the hostname of the machine generating the logging event. This configuration file contains one line per action, where the syntax for each line is a selector field followed by an action field. The syntax of the selector field is _facility.level_ which will match log messages from _facility_ at level _level_ or higher. It is also possible to add an optional comparison flag before the level to specify more precisely what is logged. Multiple selector fields can be used for the same action, and are separated with a semicolon (`;`). Using `*` will match everything. The action field denotes where to send the log message, such as to a file or remote log host. As an example, here is the default [.filename]#syslog.conf# from FreeBSD: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... In this example: * Line 8 matches all messages with a level of `err` or higher, as well as `kern.warning`, `auth.notice` and `mail.crit`, and sends these log messages to the console ([.filename]#/dev/console#). * Line 12 matches all messages from the `mail` facility at level `info` or above and logs the messages to [.filename]#/var/log/maillog#. * Line 17 uses a comparison flag (`=`) to only match messages at level `debug` and logs them to [.filename]#/var/log/debug.log#. * Line 33 is an example usage of a program specification. This makes the rules following it only valid for the specified program. In this case, only the messages generated by ppp are logged to [.filename]#/var/log/ppp.log#. The available levels, in order from most to least critical are `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`. The facilities, in no particular order, are `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp`, and `local0` through `local7`. Be aware that other operating systems might have different facilities. To log everything of level `notice` and higher to [.filename]#/var/log/daemon.log#, add the following entry: [.programlisting] .... daemon.notice /var/log/daemon.log .... For more information about the different levels and facilities, refer to man:syslog[3] and man:syslogd[8]. For more information about [.filename]#/etc/syslog.conf#, its syntax, and more advanced usage examples, see man:syslog.conf[5]. === Log Management and Rotation Log files can grow quickly, taking up disk space and making it more difficult to locate useful information. Log management attempts to mitigate this. In FreeBSD, newsyslog is used to manage log files. This built-in program periodically rotates and compresses log files, and optionally creates missing log files and signals programs when log files are moved. The log files may be generated by syslogd or by any other program which generates log files. While newsyslog is normally run from man:cron[8], it is not a system daemon. In the default configuration, it runs every hour. To know which actions to take, newsyslog reads its configuration file, [.filename]#/etc/newsyslog.conf#. This file contains one line for each log file that newsyslog manages. Each line states the file owner, permissions, when to rotate that file, optional flags that affect log rotation, such as compression, and programs to signal when the log is rotated. Here is the default configuration in FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Each line starts with the name of the log to be rotated, optionally followed by an owner and group for both rotated and newly created files. The `mode` field sets the permissions on the log file and `count` denotes how many rotated log files should be kept. The `size` and `when` fields tell newsyslog when to rotate the file. A log file is rotated when either its size is larger than the `size` field or when the time in the `when` field has passed. An asterisk (`*`) means that this field is ignored. The _flags_ field gives further instructions, such as how to compress the rotated file or to create the log file if it is missing. The last two fields are optional and specify the name of the Process ID (PID) file of a process and a signal number to send to that process when the file is rotated. For more information on all fields, valid flags, and how to specify the rotation time, refer to man:newsyslog.conf[5]. Since newsyslog is run from man:cron[8], it cannot rotate files more often than it is scheduled to run from man:cron[8]. [[network-syslogd]] === Configuring Remote Logging Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration. In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host `A`, named `logserv.example.com`, will collect logging information for the local network. Host `B`, named `logclient.example.com`, will be configured to pass logging information to the logging server. ==== Log Server Configuration A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following: * If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server. * The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system's [.filename]#/etc/hosts#. Proper name resolution is required so that log entries are not rejected by the logging server. On the log server, edit [.filename]#/etc/syslog.conf# to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host's log entries. This example adds the hostname of `B`, logs all facilities, and stores the log entries in [.filename]#/var/log/logclient.log#. .Sample Log Server Configuration [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in man:syslog.conf[5]. Next, configure [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The `-v -v` increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility. Multiple `-a` options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to man:syslogd[8] for a full list of possible options. Finally, create the log file: [source,bash] .... # touch /var/log/logclient.log .... At this point, syslogd should be restarted and verified: [source,bash] .... # service syslogd restart # pgrep syslog .... If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult [.filename]#/var/log/messages# for the error. ==== Log Client Configuration A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs. Once a logging server has been configured, edit [.filename]#/etc/rc.conf# on the logging client: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (`-s`) and increases the verbosity of logged messages. Next, define the logging server in the client's [.filename]#/etc/syslog.conf#. In this example, all logged facilities are sent to a remote system, denoted by the `@` symbol, with the specified hostname: [.programlisting] .... *.* @logserv.example.com .... After saving the edit, restart syslogd for the changes to take effect: [source,bash] .... # service syslogd restart .... To test that log messages are being sent across the network, use man:logger[1] on the client to send a message to syslogd: [source,bash] .... # logger "Test message from logclient" .... This message should now exist both in [.filename]#/var/log/messages# on the client and [.filename]#/var/log/logclient.log# on the log server. ==== Debugging Log Servers If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to `ping` each other using the hostname specified in their [.filename]#/etc/rc.conf#. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or [.filename]#/etc/hosts# on both the logging server and clients. Repeat until the `ping` is successful from both hosts. If the `ping` succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, [.filename]#/var/log/logclient.log# on the logging server is empty and [.filename]#/var/log/messages# on the logging client does not indicate a reason for the failure. To increase debugging output, edit the `syslogd_flags` entry on the logging server and issue a restart: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,bash] .... # service syslogd restart .... Debugging data similar to the following will flash on the console immediately after the restart: [source,bash] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client's hostname should be `logclient`, not `logclien`. Fix the typo, issue a restart, and verify the results: [source,bash] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... At this point, the messages are being properly received and placed in the correct file. ==== Security Considerations As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using package:security/stunnel[], which will transmit the logging data over an encrypted tunnel. Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode `600` should prevent unwanted access by local users. Refer to man:newsyslog.conf[5] for additional information. [[configtuning-configfiles]] == Configuration Files === [.filename]#/etc# Layout There are a number of directories in which configuration information is kept. These include: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Generic system-specific configuration information. |[.filename]#/etc/defaults# |Default versions of system configuration files. |[.filename]#/etc/mail# |Extra man:sendmail[8] configuration and other MTA configuration files. |[.filename]#/etc/ppp# |Configuration for both user- and kernel-ppp programs. |[.filename]#/usr/local/etc# |Configuration files for installed applications. May contain per-application subdirectories. |[.filename]#/usr/local/etc/rc.d# |man:rc[8] scripts for installed applications. |[.filename]#/var/db# |Automatically generated system-specific database files, such as the package database and the man:locate[1] database. |=== === Hostnames ==== [.filename]#/etc/resolv.conf# How a FreeBSD system accesses the Internet Domain Name System (DNS) is controlled by man:resolv.conf[5]. The most common entries to [.filename]#/etc/resolv.conf# are: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three. |`search` |Search list for hostname lookup. This is normally determined by the domain of the local hostname. |`domain` |The local domain name. |=== A typical [.filename]#/etc/resolv.conf# looks like this: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Only one of the `search` and `domain` options should be used. ==== When using DHCP, man:dhclient[8] usually rewrites [.filename]#/etc/resolv.conf# with information received from the DHCP server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# is a simple text database which works in conjunction with DNS and NIS to provide host name to IP address mappings. Entries for local computers connected via a LAN can be added to this file for simplistic naming purposes instead of setting up a man:named[8] server. Additionally, [.filename]#/etc/hosts# can be used to provide a local record of Internet names, reducing the need to query external DNS servers for commonly accessed names. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... The format of [.filename]#/etc/hosts# is as follows: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... For example: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consult man:hosts[5] for more information. [[configtuning-sysctl]] == Tuning with man:sysctl[8] man:sysctl[8] is used to make changes to a running FreeBSD system. This includes many advanced options of the TCP/IP stack and virtual memory system that can dramatically improve performance for an experienced system administrator. Over five hundred system variables can be read and set using man:sysctl[8]. At its core, man:sysctl[8] serves two functions: to read and to modify system settings. To view all readable variables: [source,bash] .... % sysctl -a .... To read a particular variable, specify its name: [source,bash] .... % sysctl kern.maxproc kern.maxproc: 1044 .... To set a particular variable, use the _variable_=_value_ syntax: [source,bash] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Settings of sysctl variables are usually either strings, numbers, or booleans, where a boolean is `1` for yes or `0` for no. To automatically set some variables each time the machine boots, add them to [.filename]#/etc/sysctl.conf#. For more information, refer to man:sysctl.conf[5] and <>. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# The configuration file for man:sysctl[8], [.filename]#/etc/sysctl.conf#, looks much like [.filename]#/etc/rc.conf#. Values are set in a `variable=value` form. The specified values are set after the system goes into multi-user mode. Not all variables are settable in this mode. For example, to turn off logging of fatal signal exits and prevent users from seeing processes started by other users, the following tunables can be set in [.filename]#/etc/sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === man:sysctl[8] Read-only In some cases it may be desirable to modify read-only man:sysctl[8] values, which will require a reboot of the system. For instance, on some laptop models the man:cardbus[4] device will not probe memory ranges and will fail with errors similar to: [source,bash] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... The fix requires the modification of a read-only man:sysctl[8] setting. Add `hw.pci.allow_unsupported_io_range=1` to [.filename]#/boot/loader.conf# and reboot. Now man:cardbus[4] should work properly. [[configtuning-disk]] == Tuning Disks The following section will discuss various tuning mechanisms and options which may be applied to disk devices. In many cases, disks with mechanical parts, such as SCSI drives, will be the bottleneck driving down the overall system performance. While a solution is to install a drive without mechanical parts, such as a solid state drive, mechanical drives are not going away anytime in the near future. When tuning disks, it is advisable to utilize the features of the man:iostat[8] command to test various changes to the system. This command will allow the user to obtain valuable information on system IO. === Sysctl Variables ==== `vfs.vmiodirenable` The `vfs.vmiodirenable` man:sysctl[8] variable may be set to either `0` (off) or `1` (on). It is set to `1` by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this man:sysctl[8] allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out. ==== `vfs.write_behind` The `vfs.write_behind` man:sysctl[8] variable defaults to `1` (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off. ==== `vfs.hirunningspace` The `vfs.hirunningspace` man:sysctl[8] variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five _megabytes_. Setting too high a value which exceeds the buffer cache's write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time. There are various other buffer cache and VM page cache related man:sysctl[8] values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself. ==== `vm.swap_idle_enabled` The `vm.swap_idle_enabled` man:sysctl[8] variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily. ==== `hw.ata.wc` Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the `hw.ata.wc` man:sysctl[8] variable. If IDE write caching is turned off, one can set this read-only variable to `1` in [.filename]#/boot/loader.conf# in order to enable it at boot time. For more information, refer to man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) The `SCSI_DELAY` kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for `15` seconds of delay in the boot process. Reducing it to `5` seconds usually works with modern drives. The `kern.cam.scsi_delay` boot time tunable should be used. The tunable and kernel configuration option accept values in terms of _milliseconds_ and _not seconds_. [[soft-updates]] === Soft Updates To fine-tune a file system, use man:tunefs[8]. This program has many different options. To toggle Soft Updates on and off, use: [source,bash] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... A file system cannot be modified with man:tunefs[8] while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode. Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as `make installworld`, can cause the file system to run out of space and the update to fail. ==== More Details About Soft Updates Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system's meta-data back to disk. Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, man:fsck[8] recognizes this and repairs the file system by setting the file length to `0`. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, `rm -r` touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using `tar -x`. The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with `mount -o async`. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system. If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a man:fsck[8] which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup. The usual solution for this problem is to implement _dirty region logging_, which is also referred to as _journaling_. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Since the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup. Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit "log rewind" causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". man:fsck[8] recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with `mount -f`. In order to free resources that may be unused, man:fsck[8] needs to be run at a later time. This is the idea behind the _background man:fsck[8]_: at system startup time, only a _snapshot_ of the file system is recorded and man:fsck[8] is run afterwards. All file systems can then be mounted "dirty", so the system startup proceeds in multi-user mode. Then, background man:fsck[8] is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground man:fsck[8]. The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than _logging_, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the man:fsck[8], these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running man:rm[1]. This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice. [[configtuning-kernel-limits]] == Tuning Kernel Limits [[file-process-limits]] === File/Process Limits [[kern-maxfiles]] ==== `kern.maxfiles` The `kern.maxfiles` man:sysctl[8] variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, `file: table is full` will show up repeatedly in the system message buffer, which can be viewed using man:dmesg[8]. Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently. In older FreeBSD releases, the default value of `kern.maxfiles` is derived from `maxusers` in the kernel configuration file. `kern.maxfiles` grows proportionally to the value of `maxusers`. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server. The read-only man:sysctl[8] variable `kern.maxusers` is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of `kern.maxusers`. Some systems require larger or smaller values of `kern.maxusers` and values of `64`, `128`, and `256` are not uncommon. Going above `256` is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by `kern.maxusers` may be individually overridden at boot-time or run-time in [.filename]#/boot/loader.conf#. Refer to man:loader.conf[5] and [.filename]#/boot/defaults/loader.conf# for more details and some hints. In older releases, the system will auto-tune `maxusers` if it is set to `0`. footnote:[The auto-tuning algorithm sets maxusers equal to the amount of memory in the system, with a minimum of 32, and a maximum of 384.]. When setting this option, set `maxusers` to at least `4`, especially if the system runs Xorg or is used to compile software. The most important table set by `maxusers` is the maximum number of processes, which is set to `20 + 16 * maxusers`. If `maxusers` is set to `1`, there can only be `36` simultaneous processes, including the `18` or so that the system starts up at boot time and the `15` or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting `maxusers` to `64` allows up to `1044` simultaneous processes, which should be enough for nearly all uses. If, however, the error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild. [NOTE] ==== `maxusers` does _not_ limit the number of users which can log into the machine. It instead sets various table sizes to reasonable values considering the maximum number of users on the system and how many processes each user will be running. ==== ==== `kern.ipc.soacceptqueue` The `kern.ipc.soacceptqueue` man:sysctl[8] variable limits the size of the listen queue for accepting new `TCP` connections. The default value of `128` is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to `1024` or higher. A service such as man:sendmail[8], or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks. [[nmbclusters]] === Network Limits The `NMBCLUSTERS` kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of `1024` represents `2` megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at `1000` simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by `2`, so 2x32 MB / 2 KB = 64 MB / 2 kB = `32768`. Values between `4096` and `32768` are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use `-m` with man:netstat[1]. The `kern.ipc.nmbclusters` loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the `NMBCLUSTERS` kernel man:config[8] option. For busy servers that make extensive use of the man:sendfile[2] system call, it may be necessary to increase the number of man:sendfile[2] buffers via the `NSFBUFS` kernel configuration option or by setting its value in [.filename]#/boot/loader.conf# (see man:loader[8] for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the `sfbufa` state. The man:sysctl[8] variable `kern.ipc.nsfbufs` is read-only. This parameter nominally scales with `kern.maxusers`, however it may be necessary to tune accordingly. [IMPORTANT] ==== Even though a socket has been marked as non-blocking, calling man:sendfile[2] on the non-blocking socket may result in the man:sendfile[2] call blocking until enough ``struct sf_buf``'s are made available. ==== ==== `net.inet.ip.portrange.*` The `net.inet.ip.portrange.*` man:sysctl[8] variables control the port number ranges automatically bound to `TCP` and `UDP` sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by `net.inet.ip.portrange.first` and `net.inet.ip.portrange.last`, which default to `1024` and `5000`, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase `net.inet.ip.portrange.last` modestly. A value of `10000`, `20000` or `30000` may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of `net.inet.ip.portrange.first` be lowered. ==== `TCP` Bandwidth Delay Product `TCP` bandwidth delay product limiting can be enabled by setting the `net.inet.tcp.inflight.enable` man:sysctl[8] variable to `1`. This instructs the system to attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput. This feature is useful when serving data over modems, Gigabit Ethernet, high speed `WAN` links, or any other link with a high bandwidth delay product, especially when also using window scaling or when a large send window has been configured. When enabling this option, also set `net.inet.tcp.inflight.debug` to `0` to disable debugging. For production use, setting `net.inet.tcp.inflight.min` to at least `6144` may be beneficial. Setting high minimums may effectively disable bandwidth limiting, depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues and reduces the amount of data built up in the local host's interface queue. With fewer queued packets, interactive connections, especially over slow modems, will operate with lower _Round Trip Times_. This feature only effects server side data transmission such as uploading. It has no effect on data reception or downloading. Adjusting `net.inet.tcp.inflight.stab` is _not_ recommended. This parameter defaults to `20`, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher man:ping[8] times over slow links, though still much lower than without the inflight algorithm. In such cases, try reducing this parameter to `15`, `10`, or `5` and reducing `net.inet.tcp.inflight.min` to a value such as `3500` to get the desired effect. Reducing these parameters should be done as a last resort only. === Virtual Memory ==== `kern.maxvnodes` A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account. To see the current number of vnodes in use: [source,bash] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... To see the maximum vnodes: [source,bash] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... If the current vnode usage is near the maximum, try increasing `kern.maxvnodes` by a value of `1000`. Keep an eye on the number of `vfs.numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will need to be increased further. Otherwise, a shift in memory usage as reported by man:top[1] should be visible and more memory should be active. [[adding-swap-space]] == Adding Swap Space Sometimes a system requires more swap space. This section describes two methods to increase swap space: adding swap to an existing partition or new hard drive, and creating a swap file on an existing partition. For information on how to encrypt swap space, which options exist, and why it should be done, refer to crossref:disks[swap-encrypting,“Encrypting Swap”]. [[new-drive-swap]] === Swap on a New Hard Drive or Existing Partition Adding a new hard drive for swap gives better performance than using a partition on an existing drive. Setting up partitions and hard drives is explained in crossref:disks[disks-adding,“Adding Disks”] while crossref:bsdinstall[configtuning-initial,“Designing the Partition Layout”] discusses partition layouts and swap partition size considerations. Use `swapon` to add a swap partition to the system. For example: [source,bash] .... # swapon /dev/ada1s1b .... [WARNING] ==== It is possible to use any partition not currently mounted, even if it already contains data. Using `swapon` on a partition that contains data will overwrite and destroy that data. Make sure that the partition to be added as swap is really the intended partition before running `swapon`. ==== To automatically add this swap partition on boot, add an entry to [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... See man:fstab[5] for an explanation of the entries in [.filename]#/etc/fstab#. More information about `swapon` can be found in man:swapon[8]. [[create-swapfile]] === Creating a Swap File These examples create a 512M swap file called [.filename]#/usr/swap0# instead of using a partition. Using swap files requires that the module needed by man:md[4] has either been built into the kernel or has been loaded before swap is enabled. See crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel] for information about building a custom kernel. [[swapfile-10-and-later]] .Creating a Swap File [example] ==== [.procedure] . Create the swap file: + [source,bash] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=512 .... . Set the proper permissions on the new file: + [source,bash] .... # chmod 0600 /usr/swap0 .... . Inform the system about the swap file by adding a line to [.filename]#/etc/fstab#: + [.programlisting] .... md99 none swap sw,file=/usr/swap0,late 0 0 .... + The man:md[4] device [.filename]#md99# is used, leaving lower device numbers available for interactive use. . Swap space will be added on system startup. To add swap space immediately, use man:swapon[8]: + [source,bash] .... # swapon -aL .... ==== [[acpi-overview]] == Power and Resource Management It is important to utilize hardware resources in an efficient manner. Power and resource management allows the operating system to monitor system limits and to possibly provide an alert if the system temperature increases unexpectedly. An early specification for providing power management was the Advanced Power Management (APM) facility. APM controls the power usage of a system based on its activity. However, it was difficult and inflexible for operating systems to manage the power usage and thermal properties of a system. The hardware was managed by the BIOS and the user had limited configurability and visibility into the power management settings. The APMBIOS is supplied by the vendor and is specific to the hardware platform. An APM driver in the operating system mediates access to the APM Software Interface, which allows management of power levels. There are four major problems in APM. First, power management is done by the vendor-specific BIOS, separate from the operating system. For example, the user can set idle-time values for a hard drive in the APMBIOS so that, when exceeded, the BIOS spins down the hard drive without the consent of the operating system. Second, the APM logic is embedded in the BIOS, and it operates outside the scope of the operating system. This means that users can only fix problems in the APMBIOS by flashing a new one into the ROM, which is a dangerous procedure with the potential to leave the system in an unrecoverable state if it fails. Third, APM is a vendor-specific technology, meaning that there is a lot of duplication of efforts and bugs found in one vendor's BIOS may not be solved in others. Lastly, the APMBIOS did not have enough room to implement a sophisticated power policy or one that can adapt well to the purpose of the machine. The Plug and Play BIOS (PNPBIOS) was unreliable in many situations. PNPBIOS is 16-bit technology, so the operating system has to use 16-bit emulation in order to interface with PNPBIOS methods. FreeBSD provides an APM driver as APM should still be used for systems manufactured at or before the year 2000. The driver is documented in man:apm[4]. The successor to APM is the Advanced Configuration and Power Interface (ACPI). ACPI is a standard written by an alliance of vendors to provide an interface for hardware resources and power management. It is a key element in _Operating System-directed configuration and Power Management_ as it provides more control and flexibility to the operating system. This chapter demonstrates how to configure ACPI on FreeBSD. It then offers some tips on how to debug ACPI and how to submit a problem report containing debugging information so that developers can diagnosis and fix ACPI issues. [[acpi-config]] === Configuring ACPI In FreeBSD the man:acpi[4] driver is loaded by default at system boot and should _not_ be compiled into the kernel. This driver cannot be unloaded after boot because the system bus uses it for various hardware interactions. However, if the system is experiencing problems, ACPI can be disabled altogether by rebooting after setting `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# or by setting this variable at the loader prompt, as described in crossref:boot[boot-loader,“Stage Three”]. [NOTE] ==== ACPI and APM cannot coexist and should be used separately. The last one to load will terminate if the driver notices the other is running. ==== ACPI can be used to put the system into a sleep mode with `acpiconf`, the `-s` flag, and a number from `1` to `5`. Most users only need `1` (quick suspend to RAM) or `3` (suspend to RAM). Option `5` performs a soft-off which is the same as running `halt -p`. Other options are available using `sysctl`. Refer to man:acpi[4] and man:acpiconf[8] for more information. [[ACPI-comprob]] === Common Problems ACPI is present in all modern computers that conform to the ia32 (x86) and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity. An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods. The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel(R) has provided an interpreter (ACPI-CA) that is shared with Linux(R) and NetBSD. The path to the ACPI-CA source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/Osd#. Finally, drivers that implement various ACPI devices are found in [.filename]#src/sys/dev/acpica#. For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to <> for instructions on how to submit a bug report. ==== Mouse Issues In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add `hint.psm.0.flags="0x3000"` to [.filename]#/boot/loader.conf#. ==== Suspend/Resume ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to disk state (STD), called `S4`. STD can be implemented in two separate ways. The ``S4``BIOS is a BIOS-assisted suspend to disk and ``S4``OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is "soft off" (`S5`). Use `sysctl hw.acpi` to check for the suspend-related items. These example results are from a Thinkpad: [source,bash] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Use `acpiconf -s` to test `S3`, `S4`, and `S5`. An `s4bios` of one (`1`) indicates ``S4``BIOS support instead of `S4` operating system support. When testing suspend/resume, start with `S1`, if supported. This state is most likely to work since it does not require much driver support. No one has implemented `S2`, which is similar to `S1`. Next, try `S3`. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware. A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try: [source,bash] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... This test emulates the suspend/resume cycle of all device drivers without actually going into `S3` state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter `S3` state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real `S3` state. Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using man:dcons[4], and kernel debugging skills. To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like [.filename]#nvidia.ko#, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and [.filename]#/etc/rc.resume#. Try setting `hw.acpi.reset_video` to `1` if the display is messed up after resume. Try setting longer or shorter values for `hw.acpi.sleep_delay` to see if that helps. Try loading a recent Linux(R) distribution to see if suspend/resume works on the same hardware. If it works on Linux(R), it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the {freebsd-current} and mailed to the driver maintainer. Advanced users can include debugging man:printf[3]s in a problematic driver to track down where in its resume function it hangs. Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI. ==== System Hangs Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI). Interrupt storms can be distinguished from lost interrupts by checking the output of `vmstat -i` and looking at the line that has `acpi0`. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (kbd:[CTRL+ALT+ESC] on console) and type `show interrupts`. When dealing with interrupt problems, try disabling APIC support with `hint.apic.0.disabled="1"` in [.filename]#/boot/loader.conf#. ==== Panics Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling `options DDB` and setting up a serial console in crossref:serialcomms[serialconsole-ddb,“Entering the DDB Debugger from the Serial Line”] or setting up a dump partition. To get a backtrace in DDB, use `tr`. When handwriting the backtrace, get at least the last five and the top five lines in the trace. Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of `debug.acpi.disable`. See man:acpi[4] for some examples. ==== System Powers Up After Suspend or Shutdown First, try setting `hw.acpi.disable_on_poweroff="0"` in [.filename]#/boot/loader.conf#. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to `1` (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff. [[ACPI-aslanddump]] ==== BIOS Contains Buggy Bytecode Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this: [source,bash] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems. === Overriding the Default AML The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT). The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft(R) interpreter ([.filename]#acpi.sys# and [.filename]#acpiec.sys#) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows(R) never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft(R)'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL. To help identify buggy behavior and possibly fix it manually, a copy can be made of the system's ASL. To copy the system's ASL to a specified file name, use `acpidump` with `-t`, to show the contents of the fixed tables, and `-d`, to disassemble the AML: [source,bash] .... # acpidump -td > my.asl .... Some AML versions assume the user is running Windows(R). To override this, set `hw.acpi.osname=_"Windows 2009"_` in [.filename]#/boot/loader.conf#, using the most recent Windows(R) version listed in the ASL. Other workarounds may require [.filename]#my.asl# to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly. [source,bash] .... # iasl -f my.asl .... Including `-f` forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter. The default output filename for `iasl` is [.filename]#DSDT.aml#. Load this file instead of the BIOS's buggy copy, which is still present in flash memory, by editing [.filename]#/boot/loader.conf# as follows: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Be sure to copy [.filename]#DSDT.aml# to [.filename]#/boot#, then reboot the system. If this fixes the problem, send a man:diff[1] of the old and new ASL to {freebsd-acpi} so that developers can work around the buggy behavior in [.filename]#acpica#. [[ACPI-submitdebug]] === Getting and Submitting Debugging Info The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (`ACPI_ALL_COMPONENTS`) and ACPI hardware support (`ACPI_ALL_DRIVERS`). The verbosity of debugging output is specified as the level and ranges from just report errors (`ACPI_LV_ERROR`) to everything (`ACPI_LV_VERBOSE`). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in man:acpi[4]. Debugging output is not enabled by default. To enable it, add `options ACPI_DEBUG` to the custom kernel configuration file if ACPI is compiled into the kernel. Add `ACPI_DEBUG=1` to [.filename]#/etc/make.conf# to enable it globally. If a module is used instead of a custom kernel, recompile just the [.filename]#acpi.ko# module as follows: [source,bash] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Copy the compiled [.filename]#acpi.ko# to [.filename]#/boot/kernel# and add the desired level and layer to [.filename]#/boot/loader.conf#. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... If the required information is triggered by a specific event, such as a suspend and then resume, do not modify [.filename]#/boot/loader.conf#. Instead, use `sysctl` to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using `sysctl` are named the same as the tunables in [.filename]#/boot/loader.conf#. Once the debugging information is gathered, it can be sent to {freebsd-acpi} so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution. [NOTE] ==== Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version. ==== When submitting a problem report, include the following information: * Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new. * The output of `dmesg` after running `boot -v`, including any error messages generated by the bug. * The `dmesg` output from `boot -v` with ACPI disabled, if disabling ACPI helps to fix the problem. * Output from `sysctl hw.acpi`. This lists which features the system offers. * The URL to a pasted version of the system's ASL. Do _not_ send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command: + [source,bash] .... # acpidump -dt > name-system.asl .... + Substitute the login name for _name_ and manufacturer/model for _system_. For example, use [.filename]#njl-FooCo6000.asl#. Most FreeBSD developers watch the {freebsd-current}, but one should submit problems to {freebsd-acpi} to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a bug report. When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing {freebsd-acpi} first as it is likely that the problem has been reported before. [[ACPI-References]] === References More information about ACPI may be found in the following locations: * The FreeBSD ACPI Mailing List Archives (https://lists.freebsd.org/pipermail/freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/]) * The ACPI 2.0 Specification (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], and man:acpidb[8] diff --git a/documentation/content/en/books/handbook/cutting-edge/_index.adoc b/documentation/content/en/books/handbook/cutting-edge/_index.adoc index 28fb60e7c1..6d6b74f3f5 100644 --- a/documentation/content/en/books/handbook/cutting-edge/_index.adoc +++ b/documentation/content/en/books/handbook/cutting-edge/_index.adoc @@ -1,918 +1,918 @@ --- title: Chapter 24. Updating and Upgrading FreeBSD part: Part III. System Administration prev: books/handbook/l10n next: books/handbook/dtrace --- [[updating-upgrading]] = Updating and Upgrading FreeBSD :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 24 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/cutting-edge/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/cutting-edge/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/cutting-edge/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[updating-upgrading-synopsis]] == Synopsis FreeBSD is under constant development between releases. Some people prefer to use the officially released versions, while others prefer to keep in sync with the latest developments. However, even official releases are often updated with security and other critical fixes. Regardless of the version used, FreeBSD provides all the necessary tools to keep the system updated, and allows for easy upgrades between versions. This chapter describes how to track the development system and the basic tools for keeping a FreeBSD system up-to-date. After reading this chapter, you will know: * How to keep a FreeBSD system up-to-date with freebsd-update or Subversion. * How to compare the state of an installed system against a known pristine copy. * How to keep the installed documentation up-to-date with Subversion or documentation ports. * The difference between the two development branches: FreeBSD-STABLE and FreeBSD-CURRENT. * How to rebuild and reinstall the entire base system. Before reading this chapter, you should: * Properly set up the network connection (crossref:advanced-networking[advanced-networking,Advanced Networking]). * Know how to install additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [NOTE] ==== Throughout this chapter, `svnlite` is used to obtain and update FreeBSD sources. Optionally, the package:devel/subversion[] port or package may be used. ==== [[updating-upgrading-freebsdupdate]] == FreeBSD Update Applying security patches in a timely manner and upgrading to a newer release of an operating system are important aspects of ongoing system administration. FreeBSD includes a utility called `freebsd-update` which can be used to perform both these tasks. This utility supports binary security and errata updates to FreeBSD, without the need to manually compile and install the patch or a new kernel. Binary updates are available for all architectures and releases currently supported by the security team. The list of supported releases and their estimated end-of-life dates are listed at https://www.FreeBSD.org/security/[https://www.FreeBSD.org/security/]. This utility also supports operating system upgrades to minor point releases as well as upgrades to another release branch. Before upgrading to a new release, review its release announcement as it contains important information pertinent to the release. Release announcements are available from https://www.FreeBSD.org/releases/[https://www.FreeBSD.org/releases/]. [NOTE] ==== If a `crontab` utilizing the features of man:freebsd-update[8] exists, it must be disabled before upgrading the operating system. ==== This section describes the configuration file used by `freebsd-update`, demonstrates how to apply a security patch and how to upgrade to a minor or major operating system release, and discusses some of the considerations when upgrading the operating system. [[freebsdupdate-config-file]] === The Configuration File The default configuration file for `freebsd-update` works as-is. Some users may wish to tweak the default configuration in [.filename]#/etc/freebsd-update.conf#, allowing better control of the process. The comments in this file explain the available options, but the following may require a bit more explanation: [.programlisting] .... # Components of the base system which should be kept updated. Components world kernel .... This parameter controls which parts of FreeBSD will be kept up-to-date. The default is to update the entire base system and the kernel. Individual components can instead be specified, such as `src/base` or `src/sys`. However, the best option is to leave this at the default as changing it to include specific items requires every needed item to be listed. Over time, this could have disastrous consequences as source code and binaries may become out of sync. [.programlisting] .... # Paths which start with anything matching an entry in an IgnorePaths # statement will be ignored. IgnorePaths /boot/kernel/linker.hints .... To leave specified directories, such as [.filename]#/bin# or [.filename]#/sbin#, untouched during the update process, add their paths to this statement. This option may be used to prevent `freebsd-update` from overwriting local modifications. [.programlisting] .... # Paths which start with anything matching an entry in an UpdateIfUnmodified # statement will only be updated if the contents of the file have not been # modified by the user (unless changes are merged; see below). UpdateIfUnmodified /etc/ /var/ /root/ /.cshrc /.profile .... This option will only update unmodified configuration files in the specified directories. Any changes made by the user will prevent the automatic updating of these files. There is another option, `KeepModifiedMetadata`, which will instruct `freebsd-update` to save the changes during the merge. [.programlisting] .... # When upgrading to a new FreeBSD release, files which match MergeChanges # will have any local changes merged into the version from the new release. MergeChanges /etc/ /var/named/etc/ /boot/device.hints .... List of directories with configuration files that `freebsd-update` should attempt to merge. The file merge process is a series of man:diff[1] patches similar to man:mergemaster[8], but with fewer options. Merges are either accepted, open an editor, or cause `freebsd-update` to abort. When in doubt, backup [.filename]#/etc# and just accept the merges. See man:mergemaster[8] for more information about `mergemaster`. [.programlisting] .... # Directory in which to store downloaded updates and temporary # files used by FreeBSD Update. # WorkDir /var/db/freebsd-update .... This directory is where all patches and temporary files are placed. In cases where the user is doing a version upgrade, this location should have at least a gigabyte of disk space available. [.programlisting] .... # When upgrading between releases, should the list of Components be # read strictly (StrictComponents yes) or merely as a list of components # which *might* be installed of which FreeBSD Update should figure out # which actually are installed and upgrade those (StrictComponents no)? # StrictComponents no .... When this option is set to `yes`, `freebsd-update` will assume that the `Components` list is complete and will not attempt to make changes outside of the list. Effectively, `freebsd-update` will attempt to update every file which belongs to the `Components` list. [[freebsdupdate-security-patches]] === Applying Security Patches The process of applying FreeBSD security patches has been simplified, allowing an administrator to keep a system fully patched using `freebsd-update`. More information about FreeBSD security advisories can be found in crossref:security[security-advisories,"FreeBSD Security Advisories"]. FreeBSD security patches may be downloaded and installed using the following commands. The first command will determine if any outstanding patches are available, and if so, will list the files that will be modifed if the patches are applied. The second command will apply the patches. [source,bash] .... # freebsd-update fetch # freebsd-update install .... If the update applies any kernel patches, the system will need a reboot in order to boot into the patched kernel. If the patch was applied to any running binaries, the affected applications should be restarted so that the patched version of the binary is used. [NOTE] ==== Usually, the user needs to be prepared to reboot the system. To know if a reboot is required by a kernel update, execute the commands `freebsd-version -k` and `uname -r` and if it differs a reboot is required. ==== The system can be configured to automatically check for updates once every day by adding this entry to [.filename]#/etc/crontab#: [.programlisting] .... @daily root freebsd-update cron .... If patches exist, they will automatically be downloaded but will not be applied. The `root` user will be sent an email so that the patches may be reviewed and manually installed with `freebsd-update install`. If anything goes wrong, `freebsd-update` has the ability to roll back the last set of changes with the following command: [source,bash] .... # freebsd-update rollback Uninstalling updates... done. .... Again, the system should be restarted if the kernel or any kernel modules were modified and any affected binaries should be restarted. Only the [.filename]#GENERIC# kernel can be automatically updated by `freebsd-update`. If a custom kernel is installed, it will have to be rebuilt and reinstalled after `freebsd-update` finishes installing the updates. The default kernel name is _GENERIC_. The man:uname[1] command may be used to verify its installation. [NOTE] ==== Always keep a copy of the [.filename]#GENERIC# kernel in [.filename]#/boot/GENERIC#. It will be helpful in diagnosing a variety of problems and in performing version upgrades. Refer to <> for instructions on how to get a copy of the [.filename]#GENERIC# kernel. ==== Unless the default configuration in [.filename]#/etc/freebsd-update.conf# has been changed, `freebsd-update` will install the updated kernel sources along with the rest of the updates. Rebuilding and reinstalling a new custom kernel can then be performed in the usual way. The updates distributed by `freebsd-update` do not always involve the kernel. It is not necessary to rebuild a custom kernel if the kernel sources have not been modified by `freebsd-update install`. However, `freebsd-update` will always update [.filename]#/usr/src/sys/conf/newvers.sh#. The current patch level, as indicated by the `-p` number reported by `uname -r`, is obtained from this file. Rebuilding a custom kernel, even if nothing else changed, allows `uname` to accurately report the current patch level of the system. This is particularly helpful when maintaining multiple systems, as it allows for a quick assessment of the updates installed in each one. [[freebsdupdate-upgrade]] === Performing Major and Minor Version Upgrades Upgrades from one minor version of FreeBSD to another, like from FreeBSD 9.0 to FreeBSD 9.1, are called _minor version_ upgrades. _Major version_ upgrades occur when FreeBSD is upgraded from one major version to another, like from FreeBSD 9.X to FreeBSD 10.X. Both types of upgrades can be performed by providing `freebsd-update` with a release version target. [NOTE] ==== If the system is running a custom kernel, make sure that a copy of the [.filename]#GENERIC# kernel exists in [.filename]#/boot/GENERIC# before starting the upgrade. Refer to <> for instructions on how to get a copy of the [.filename]#GENERIC# kernel. ==== The following command, when run on a FreeBSD 9.0 system, will upgrade it to FreeBSD 9.1: [source,bash] .... # freebsd-update -r 9.1-RELEASE upgrade .... After the command has been received, `freebsd-update` will evaluate the configuration file and current system in an attempt to gather the information necessary to perform the upgrade. A screen listing will display which components have and have not been detected. For example: [source,bash] .... Looking up update.FreeBSD.org mirrors... 1 mirrors found. Fetching metadata signature for 9.0-RELEASE from update1.FreeBSD.org... done. Fetching metadata index... done. Inspecting system... done. The following components of FreeBSD seem to be installed: kernel/smp src/base src/bin src/contrib src/crypto src/etc src/games src/gnu src/include src/krb5 src/lib src/libexec src/release src/rescue src/sbin src/secure src/share src/sys src/tools src/ubin src/usbin world/base world/info world/lib32 world/manpages The following components of FreeBSD do not seem to be installed: kernel/generic world/catpages world/dict world/doc world/games world/proflibs Does this look reasonable (y/n)? y .... At this point, `freebsd-update` will attempt to download all files required for the upgrade. In some cases, the user may be prompted with questions regarding what to install or how to proceed. When using a custom kernel, the above step will produce a warning similar to the following: [source,bash] .... WARNING: This system is running a "MYKERNEL" kernel, which is not a kernel configuration distributed as part of FreeBSD 9.0-RELEASE. This kernel will not be updated: you MUST update the kernel manually before running "/usr/sbin/freebsd-update install" .... This warning may be safely ignored at this point. The updated [.filename]#GENERIC# kernel will be used as an intermediate step in the upgrade process. Once all the patches have been downloaded to the local system, they will be applied. This process may take a while, depending on the speed and workload of the machine. Configuration files will then be merged. The merging process requires some user intervention as a file may be merged or an editor may appear on screen for a manual merge. The results of every successful merge will be shown to the user as the process continues. A failed or ignored merge will cause the process to abort. Users may wish to make a backup of [.filename]#/etc# and manually merge important files, such as [.filename]#master.passwd# or [.filename]#group# at a later time. [NOTE] ==== The system is not being altered yet as all patching and merging is happening in another directory. Once all patches have been applied successfully, all configuration files have been merged and it seems the process will go smoothly, the changes can be committed to disk by the user using the following command: [source,bash] .... # freebsd-update install .... ==== The kernel and kernel modules will be patched first. If the system is running with a custom kernel, use man:nextboot[8] to set the kernel for the next boot to the updated [.filename]#/boot/GENERIC#: [source,bash] .... # nextboot -k GENERIC .... [WARNING] ==== Before rebooting with the [.filename]#GENERIC# kernel, make sure it contains all the drivers required for the system to boot properly and connect to the network, if the machine being updated is accessed remotely. In particular, if the running custom kernel contains built-in functionality usually provided by kernel modules, make sure to temporarily load these modules into the [.filename]#GENERIC# kernel using the [.filename]#/boot/loader.conf# facility. It is recommended to disable non-essential services as well as any disk and network mounts until the upgrade process is complete. ==== The machine should now be restarted with the updated kernel: [source,bash] .... # shutdown -r now .... Once the system has come back online, restart `freebsd-update` using the following command. Since the state of the process has been saved, `freebsd-update` will not start from the beginning, but will instead move on to the next phase and remove all old shared libraries and object files. [source,bash] .... # freebsd-update install .... [NOTE] ==== Depending upon whether any library version numbers were bumped, there may only be two install phases instead of three. ==== The upgrade is now complete. If this was a major version upgrade, reinstall all ports and packages as described in <>. [[freebsd-update-custom-kernel-9x]] ==== Custom Kernels with FreeBSD 9.X and Later Before using `freebsd-update`, ensure that a copy of the [.filename]#GENERIC# kernel exists in [.filename]#/boot/GENERIC#. If a custom kernel has only been built once, the kernel in [.filename]#/boot/kernel.old# is the `GENERIC` kernel. Simply rename this directory to [.filename]#/boot/GENERIC#. If a custom kernel has been built more than once or if it is unknown how many times the custom kernel has been built, obtain a copy of the `GENERIC` kernel that matches the current version of the operating system. If physical access to the system is available, a copy of the `GENERIC` kernel can be installed from the installation media: [source,bash] .... # mount /cdrom # cd /cdrom/usr/freebsd-dist # tar -C/ -xvf kernel.txz boot/kernel/kernel .... Alternately, the `GENERIC` kernel may be rebuilt and installed from source: [source,bash] .... # cd /usr/src # make kernel __MAKE_CONF=/dev/null SRCCONF=/dev/null .... For this kernel to be identified as the `GENERIC` kernel by `freebsd-update`, the [.filename]#GENERIC# configuration file must not have been modified in any way. It is also suggested that the kernel is built without any other special options. Rebooting into the [.filename]#GENERIC# kernel is not required as `freebsd-update` only needs [.filename]#/boot/GENERIC# to exist. [[freebsdupdate-portsrebuild]] ==== Upgrading Packages After a Major Version Upgrade Generally, installed applications will continue to work without problems after minor version upgrades. Major versions use different Application Binary Interfaces (ABIs), which will break most third-party applications. After a major version upgrade, all installed packages and ports need to be upgraded. Packages can be upgraded using `pkg upgrade`. To upgrade installed ports, use a utility such as package:ports-mgmt/portmaster[]. A forced upgrade of all installed packages will replace the packages with fresh versions from the repository even if the version number has not increased. This is required because of the ABI version change when upgrading between major versions of FreeBSD. The forced upgrade can be accomplished by performing: [source,bash] .... # pkg-static upgrade -f .... A rebuild of all installed applications can be accomplished with this command: [source,bash] .... # portmaster -af .... This command will display the configuration screens for each application that has configurable options and wait for the user to interact with those screens. To prevent this behavior, and use only the default options, include `-G` in the above command. Once the software upgrades are complete, finish the upgrade process with a final call to `freebsd-update` in order to tie up all the loose ends in the upgrade process: [source,bash] .... # freebsd-update install .... If the [.filename]#GENERIC# kernel was temporarily used, this is the time to build and install a new custom kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. Reboot the machine into the new FreeBSD version. The upgrade process is now complete. [[freebsdupdate-system-comparison]] === System State Comparison The state of the installed FreeBSD version against a known good copy can be tested using `freebsd-update IDS`. This command evaluates the current version of system utilities, libraries, and configuration files and can be used as a built-in Intrusion Detection System (IDS). [WARNING] ==== This command is not a replacement for a real IDS such as package:security/snort[]. As `freebsd-update` stores data on disk, the possibility of tampering is evident. While this possibility may be reduced using `kern.securelevel` and by storing the `freebsd-update` data on a read-only file system when not in use, a better solution would be to compare the system against a secure disk, such as a DVD or securely stored external USB disk device. An alternative method for providing IDS functionality using a built-in utility is described in crossref:security[security-ids,"Binary Verification"] ==== To begin the comparison, specify the output file to save the results to: [source,bash] .... # freebsd-update IDS >> outfile.ids .... The system will now be inspected and a lengthy listing of files, along with the SHA256 hash values for both the known value in the release and the current installation, will be sent to the specified output file. The entries in the listing are extremely long, but the output format may be easily parsed. For instance, to obtain a list of all files which differ from those in the release, issue the following command: [source,bash] .... # cat outfile.ids | awk '{ print $1 }' | more /etc/master.passwd /etc/motd /etc/passwd /etc/pf.conf .... This sample output has been truncated as many more files exist. Some files have natural modifications. For example, [.filename]#/etc/passwd# will be modified if users have been added to the system. Kernel modules may differ as `freebsd-update` may have updated them. To exclude specific files or directories, add them to the `IDSIgnorePaths` option in [.filename]#/etc/freebsd-update.conf#. [[updating-upgrading-documentation]] == Updating the Documentation Set Documentation is an integral part of the FreeBSD operating system. While an up-to-date version of the FreeBSD documentation is always available on the FreeBSD web site (link:https://www.FreeBSD.org/doc/[https://www.freebsd.org/doc/]), it can be handy to have an up-to-date, local copy of the FreeBSD website, handbooks, FAQ, and articles. This section describes how to use either source or the FreeBSD Ports Collection to keep a local copy of the FreeBSD documentation up-to-date. For information on editing and submitting corrections to the documentation, refer to the FreeBSD Documentation Project Primer for New Contributors (link:{fdp-primer}[FreeBSD Documentation Project Primer for New Contributors]). [[updating-installed-documentation]] === Updating Documentation from Source Rebuilding the FreeBSD documentation from source requires a collection of tools which are not part of the FreeBSD base system. The required tools can be installed from the package:textproc/docproj[] package or port developed by the FreeBSD Documentation Project. Once installed, use svnlite to fetch a clean copy of the documentation source: [source,bash] .... # svnlite checkout https://svn.FreeBSD.org/doc/head /usr/doc .... The initial download of the documentation sources may take a while. Let it run until it completes. Future updates of the documentation sources may be fetched by running: [source,bash] .... # svnlite update /usr/doc .... Once an up-to-date snapshot of the documentation sources has been fetched to [.filename]#/usr/doc#, everything is ready for an update of the installed documentation. A full update of all available languages may be performed by typing: [source,bash] .... # cd /usr/doc # make install clean .... If an update of only a specific language is desired, `make` can be invoked in a language-specific subdirectory of [.filename]#/usr/doc#: [source,bash] .... # cd /usr/doc/en_US.ISO8859-1 # make install clean .... An alternative way of updating the documentation is to run this command from [.filename]#/usr/doc# or the desired language-specific subdirectory: [source,bash] .... # make update .... The output formats that will be installed may be specified by setting `FORMATS`: [source,bash] .... # cd /usr/doc # make FORMATS='html html-split' install clean .... Several options are available to ease the process of updating only parts of the documentation, or the build of specific translations. These options can be set either as system-wide options in [.filename]#/etc/make.conf#, or as command-line options passed to `make`. The options include: `DOC_LANG`:: The list of languages and encodings to build and install, such as `en_US.ISO8859-1` for English documentation. `FORMATS`:: A single format or a list of output formats to be built. Currently, `html`, `html-split`, `txt`, `ps`, and `pdf` are supported. `DOCDIR`:: -Where to install the documentation. It defaults to [.filename]#/usr/shared/doc#. +Where to install the documentation. It defaults to [.filename]#/usr/share/doc#. For more `make` variables supported as system-wide options in FreeBSD, refer to man:make.conf[5]. [[doc-ports-install-package]] === Updating Documentation from Ports The previous section presented a method for updating the FreeBSD documentation from sources. This section describes an alternative method which uses the Ports Collection and makes it possible to: * Install pre-built packages of the documentation, without having to locally build anything or install the documentation toolchain. * Build the documentation sources through the ports framework, making the checkout and build steps a bit easier. This method of updating the FreeBSD documentation is supported by a set of documentation ports and packages which are updated by the {doceng} on a monthly basis. These are listed in the FreeBSD Ports Collection, under the docs category (http://www.freshports.org/docs/[http://www.freshports.org/docs/]). Organization of the documentation ports is as follows: * The package:misc/freebsd-doc-en[] package or port installs all of the English documentation. * The package:misc/freebsd-doc-all[] meta-package or port installs all documentation in all available languages. * There is a package and port for each translation, such as package:misc/freebsd-doc-hu[] for the Hungarian documentation. When binary packages are used, the FreeBSD documentation will be installed in all available formats for the given language. For example, the following command will install the latest package of the Hungarian documentation: [source,bash] .... # pkg install hu-freebsd-doc .... [NOTE] ==== Packages use a format that differs from the corresponding port's name: `_lang_-freebsd-doc`, where _lang_ is the short format of the language code, such as `hu` for Hungarian, or `zh_cn` for Simplified Chinese. ==== To specify the format of the documentation, build the port instead of installing the package. For example, to build and install the English documentation: [source,bash] .... # cd /usr/ports/misc/freebsd-doc-en # make install clean .... The port provides a configuration menu where the format to build and install can be specified. By default, split HTML, similar to the format used on http://www.FreeBSD.org[http://www.FreeBSD.org], and PDF are selected. Alternately, several `make` options can be specified when building a documentation port, including: `WITH_HTML`:: Builds the HTML format with a single HTML file per document. The formatted documentation is saved to a file called [.filename]#article.html#, or [.filename]#book.html#. `WITH_PDF`:: The formatted documentation is saved to a file called [.filename]#article.pdf# or [.filename]#book.pdf#. `DOCBASE`:: Specifies where to install the documentation. It defaults to [.filename]#/usr/local/shared/doc/freebsd#. This example uses variables to install the Hungarian documentation as a PDF in the specified directory: [source,bash] .... # cd /usr/ports/misc/freebsd-doc-hu # make -DWITH_PDF DOCBASE=share/doc/freebsd/hu install clean .... Documentation packages or ports can be updated using the instructions in crossref:ports[ports,Installing Applications: Packages and Ports]. For example, the following command updates the installed Hungarian documentation using package:ports-mgmt/portmaster[] by using packages only: [source,bash] .... # portmaster -PP hu-freebsd-doc .... [[current-stable]] == Tracking a Development Branch FreeBSD has two development branches: FreeBSD-CURRENT and FreeBSD-STABLE. This section provides an explanation of each branch and its intended audience, as well as how to keep a system up-to-date with each respective branch. [[current]] === Using FreeBSD-CURRENT FreeBSD-CURRENT is the "bleeding edge" of FreeBSD development and FreeBSD-CURRENT users are expected to have a high degree of technical skill. Less technical users who wish to track a development branch should track FreeBSD-STABLE instead. FreeBSD-CURRENT is the very latest source code for FreeBSD and includes works in progress, experimental changes, and transitional mechanisms that might or might not be present in the next official release. While many FreeBSD developers compile the FreeBSD-CURRENT source code daily, there are short periods of time when the source may not be buildable. These problems are resolved as quickly as possible, but whether or not FreeBSD-CURRENT brings disaster or new functionality can be a matter of when the source code was synced. FreeBSD-CURRENT is made available for three primary interest groups: . Members of the FreeBSD community who are actively working on some part of the source tree. . Members of the FreeBSD community who are active testers. They are willing to spend time solving problems, making topical suggestions on changes and the general direction of FreeBSD, and submitting patches. . Users who wish to keep an eye on things, use the current source for reference purposes, or make the occasional comment or code contribution. FreeBSD-CURRENT should _not_ be considered a fast-track to getting new features before the next release as pre-release features are not yet fully tested and most likely contain bugs. It is not a quick way of getting bug fixes as any given commit is just as likely to introduce new bugs as to fix existing ones. FreeBSD-CURRENT is not in any way "officially supported". To track FreeBSD-CURRENT: . Join the {freebsd-current} and the {svn-src-head} lists. This is _essential_ in order to see the comments that people are making about the current state of the system and to receive important bulletins about the current state of FreeBSD-CURRENT. + The {svn-src-head} list records the commit log entry for each change as it is made, along with any pertinent information on possible side effects. + To join these lists, go to {mailman-lists}, click on the list to subscribe to, and follow the instructions. In order to track changes to the whole source tree, not just the changes to FreeBSD-CURRENT, subscribe to the {svn-src-all}. . Synchronize with the FreeBSD-CURRENT sources. Typically, <> is used to check out the -CURRENT code from the `head` branch of one of the Subversion mirror sites listed in crossref:mirrors[svn-mirrors,“Subversion Mirror Sites”]. . Due to the size of the repository, some users choose to only synchronize the sections of source that interest them or which they are contributing patches to. However, users that plan to compile the operating system from source must download _all_ of FreeBSD-CURRENT, not just selected portions. + Before compiling FreeBSD-CURRENT , read [.filename]#/usr/src/Makefile# very carefully and follow the instructions in <>. Read the {freebsd-current} and [.filename]#/usr/src/UPDATING# to stay up-to-date on other bootstrapping procedures that sometimes become necessary on the road to the next release. . Be active! FreeBSD-CURRENT users are encouraged to submit their suggestions for enhancements or bug fixes. Suggestions with accompanying code are always welcome. [[stable]] === Using FreeBSD-STABLE FreeBSD-STABLE is the development branch from which major releases are made. Changes go into this branch at a slower pace and with the general assumption that they have first been tested in FreeBSD-CURRENT. This is _still_ a development branch and, at any given time, the sources for FreeBSD-STABLE may or may not be suitable for general use. It is simply another engineering development track, not a resource for end-users. Users who do not have the resources to perform testing should instead run the most recent release of FreeBSD. Those interested in tracking or contributing to the FreeBSD development process, especially as it relates to the next release of FreeBSD, should consider following FreeBSD-STABLE. While the FreeBSD-STABLE branch should compile and run at all times, this cannot be guaranteed. Since more people run FreeBSD-STABLE than FreeBSD-CURRENT, it is inevitable that bugs and corner cases will sometimes be found in FreeBSD-STABLE that were not apparent in FreeBSD-CURRENT. For this reason, one should not blindly track FreeBSD-STABLE. It is particularly important _not_ to update any production servers to FreeBSD-STABLE without thoroughly testing the code in a development or testing environment. To track FreeBSD-STABLE: . Join the {freebsd-stable} in order to stay informed of build dependencies that may appear in FreeBSD-STABLE or any other issues requiring special attention. Developers will also make announcements in this mailing list when they are contemplating some controversial fix or update, giving the users a chance to respond if they have any issues to raise concerning the proposed change. + Join the relevant svn list for the branch being tracked. For example, users tracking the 9-STABLE branch should join the {svn-src-stable-9}. This list records the commit log entry for each change as it is made, along with any pertinent information on possible side effects. + To join these lists, go to {mailman-lists}, click on the list to subscribe to, and follow the instructions. In order to track changes for the whole source tree, subscribe to {svn-src-all}. . To install a new FreeBSD-STABLE system, install the most recent FreeBSD-STABLE release from the crossref:mirrors[mirrors,FreeBSD mirror sites] or use a monthly snapshot built from FreeBSD-STABLE. Refer to link:https://www.FreeBSD.org/snapshots/[www.freebsd.org/snapshots] for more information about snapshots. + To compile or upgrade to an existing FreeBSD system to FreeBSD-STABLE, use crossref:mirrors[svn,svn] to check out the source for the desired branch. Branch names, such as `stable/9`, are listed at link:https://www.FreeBSD.org/releng/[www.freebsd.org/releng]. . Before compiling or upgrading to FreeBSD-STABLE , read [.filename]#/usr/src/Makefile# carefully and follow the instructions in <>. Read the {freebsd-stable} and [.filename]#/usr/src/UPDATING# to keep up-to-date on other bootstrapping procedures that sometimes become necessary on the road to the next release. [[makeworld]] == Updating FreeBSD from Source Updating FreeBSD by compiling from source offers several advantages over binary updates. Code can be built with options to take advantage of specific hardware. Parts of the base system can be built with non-default settings, or left out entirely where they are not needed or desired. The build process takes longer to update a system than just installing binary updates, but allows complete customization to produce a tailored version of FreeBSD. [[updating-src-quick-start]] === Quick Start This is a quick reference for the typical steps used to update FreeBSD by building from source. Later sections describe the process in more detail. [.procedure] ==== * Update and Build + [source,bash] .... # svnlite update /usr/src <.> check /usr/src/UPDATING <.> # cd /usr/src <.> # make -j4 buildworld <.> # make -j4 kernel <.> # shutdown -r now <.> # cd /usr/src <.> # make installworld <.> # mergemaster -Ui <.> # shutdown -r now <.> .... <.> Get the latest version of the source. See <> for more information on obtaining and updating source. <.> Check [.filename]#/usr/src/UPDATING# for any manual steps required before or after building from source. <.> Go to the source directory. <.> Compile the world, everything except the kernel. <.> Compile and install the kernel. This is equivalent to `make buildkernel installkernel`. <.> Reboot the system to the new kernel. <.> Go to the source directory. <.> Install the world. <.> Update and merge configuration files in [.filename]#/etc/#. <.> Restart the system to use the newly-built world and kernel. ==== [[updating-src-preparing]] === Preparing for a Source Update Read [.filename]#/usr/src/UPDATING#. Any manual steps that must be performed before or after an update are described in this file. [[updating-src-obtaining-src]] === Updating the Source FreeBSD source code is located in [.filename]#/usr/src/#. The preferred method of updating this source is through the Subversion version control system. Verify that the source code is under version control: [source,bash] .... # svnlite info /usr/src Path: /usr/src Working Copy Root Path: /usr/src ... .... This indicates that [.filename]#/usr/src/# is under version control and can be updated with man:svnlite[1]: [[synching]] [source,bash] .... # svnlite update /usr/src .... The update process can take some time if the directory has not been updated recently. After it finishes, the source code is up to date and the build process described in the next section can begin. [NOTE] ==== *Obtaining the Source:* + If the output says `'/usr/src' is not a working copy`, the files there are missing or were installed with a different method. A new checkout of the source is required. [[updating-src-obtaining-src-repopath]] .FreeBSD Versions and Repository Paths [cols="10%,10%,80%", options="header"] |=== | uname -r Output | Repository Path | Description |`_X.Y_-RELEASE` |`base/releng/_X.Y_` |The Release version plus only critical security and bug fix patches. This branch is recommended for most users. |`_X.Y_-STABLE` |`base/stable/_X_` | The Release version plus all additional development on that branch. _STABLE_ refers to the Applications Binary Interface (ABI) not changing, so software compiled for earlier versions still runs. For example, software compiled to run on FreeBSD 10.1 will still run on FreeBSD 10-STABLE compiled later. STABLE branches occasionally have bugs or incompatibilities which might affect users, although these are typically fixed quickly. |`_X_-CURRENT` |`base/head/` |The latest unreleased development version of FreeBSD. The CURRENT branch can have major bugs or incompatibilities and is recommended only for advanced users. |=== Determine which version of FreeBSD is being used with man:uname[1]: [source,bash] .... # uname -r 10.3-RELEASE .... Based on <>, the source used to update `10.3-RELEASE` has a repository path of `base/releng/10.3`. That path is used when checking out the source: [source,bash] .... # mv /usr/src /usr/src.bak <.> # svnlite checkout https://svn.freebsd.org/base/releng/10.3 /usr/src <.> .... <.> Move the old directory out of the way. If there are no local modifications in this directory, it can be deleted. <.> The path from <> is added to the repository URL. The third parameter is the destination directory for the source code on the local system. ==== [[updating-src-building]] === Building from Source The _world_, or all of the operating system except the kernel, is compiled. This is done first to provide up-to-date tools to build the kernel. Then the kernel itself is built: [source,bash] .... # cd /usr/src # make buildworld # make buildkernel .... The compiled code is written to [.filename]#/usr/obj#. These are the basic steps. Additional options to control the build are described below. [[updating-src-building-clean-build]] ==== Performing a Clean Build Some versions of the FreeBSD build system leave previously-compiled code in the temporary object directory, [.filename]#/usr/obj#. This can speed up later builds by avoiding recompiling code that has not changed. To force a clean rebuild of everything, use `cleanworld` before starting a build: [source,bash] .... # make cleanworld .... [[updating-src-building-jobs]] ==== Setting the Number of Jobs Increasing the number of build jobs on multi-core processors can improve build speed. Determine the number of cores with `sysctl hw.ncpu`. Processors vary, as do the build systems used with different versions of FreeBSD, so testing is the only sure method to tell how a different number of jobs affects the build speed. For a starting point, consider values between half and double the number of cores. The number of jobs is specified with `-j`. [[updating-src-building-jobs-example]] .Increasing the Number of Build Jobs [example] ==== Building the world and kernel with four jobs: [source,bash] .... # make -j4 buildworld buildkernel .... ==== [[updating-src-building-only-kernel]] ==== Building Only the Kernel A `buildworld` must be completed if the source code has changed. After that, a `buildkernel` to build a kernel can be run at any time. To build just the kernel: [source,bash] .... # cd /usr/src # make buildkernel .... [[updating-src-building-custom-kernel]] ==== Building a Custom Kernel The standard FreeBSD kernel is based on a _kernel config file_ called [.filename]#GENERIC#. The [.filename]#GENERIC# kernel includes the most commonly-needed device drivers and options. Sometimes it is useful or necessary to build a custom kernel, adding or removing device drivers or options to fit a specific need. For example, someone developing a small embedded computer with severely limited RAM could remove unneeded device drivers or options to make the kernel slightly smaller. Kernel config files are located in [.filename]#/usr/src/sys/arch/conf/#, where _arch_ is the output from `uname -m`. On most computers, that is `amd64`, giving a config file directory of [.filename]#/usr/src/sys/amd64/conf/#. [TIP] ==== [.filename]#/usr/src# can be deleted or recreated, so it is preferable to keep custom kernel config files in a separate directory, like [.filename]#/root#. Link the kernel config file into the [.filename]#conf# directory. If that directory is deleted or overwritten, the kernel config can be re-linked into the new one. ==== A custom config file can be created by copying the [.filename]#GENERIC# config file. In this example, the new custom kernel is for a storage server, so is named [.filename]#STORAGESERVER#: [source,bash] .... # cp /usr/src/sys/amd64/conf/GENERIC /root/STORAGESERVER # cd /usr/src/sys/amd64/conf # ln -s /root/STORAGESERVER . .... [.filename]#/root/STORAGESERVER# is then edited, adding or removing devices or options as shown in man:config[5]. The custom kernel is built by setting `KERNCONF` to the kernel config file on the command line: [source,bash] .... # make buildkernel KERNCONF=STORAGESERVER .... [[updating-src-installing]] === Installing the Compiled Code After the `buildworld` and `buildkernel` steps have been completed, the new kernel and world are installed: [source,bash] .... # cd /usr/src # make installkernel # shutdown -r now # cd /usr/src # make installworld # shutdown -r now .... If a custom kernel was built, `KERNCONF` must also be set to use the new custom kernel: [source,bash] .... # cd /usr/src # make installkernel KERNCONF=STORAGESERVER # shutdown -r now # cd /usr/src # make installworld # shutdown -r now .... [[updating-src-completing]] === Completing the Update A few final tasks complete the update. Any modified configuration files are merged with the new versions, outdated libraries are located and removed, then the system is restarted. [[updating-src-completing-merge-mergemaster]] ==== Merging Configuration Files with man:mergemaster[8] man:mergemaster[8] provides an easy way to merge changes that have been made to system configuration files with new versions of those files. With `-Ui`, man:mergemaster[8] automatically updates files that have not been user-modified and installs new files that are not already present: [source,bash] .... # mergemaster -Ui .... If a file must be manually merged, an interactive display allows the user to choose which portions of the files are kept. See man:mergemaster[8] for more information. [[updating-src-completing-check-old]] ==== Checking for Outdated Files and Libraries Some obsolete files or directories can remain after an update. These files can be located: [source,bash] .... # make check-old .... and deleted: [source,bash] .... # make delete-old .... Some obsolete libraries can also remain. These can be detected with: [source,bash] .... # make check-old-libs .... and deleted with [source,bash] .... # make delete-old-libs .... Programs which were still using those old libraries will stop working when the library has been deleted. These programs must be rebuilt or replaced after deleting the old libraries. [TIP] ==== When all the old files or directories are known to be safe to delete, pressing kbd:[y] and kbd:[Enter] to delete each file can be avoided by setting `BATCH_DELETE_OLD_FILES` in the command. For example: [source,bash] .... # make BATCH_DELETE_OLD_FILES=yes delete-old-libs .... ==== [[updating-src-completing-restart]] ==== Restarting After the Update The last step after updating is to restart the computer so all the changes take effect: [source,bash] .... # shutdown -r now .... [[small-lan]] == Tracking for Multiple Machines When multiple machines need to track the same source tree, it is a waste of disk space, network bandwidth, and CPU cycles to have each system download the sources and rebuild everything. The solution is to have one machine do most of the work, while the rest of the machines mount that work via NFS. This section outlines a method of doing so. For more information about using NFS, refer to crossref:network-servers[network-nfs,"Network File System (NFS)"]. First, identify a set of machines which will run the same set of binaries, known as a _build set_. Each machine can have a custom kernel, but will run the same userland binaries. From that set, choose a machine to be the _build machine_ that the world and kernel are built on. Ideally, this is a fast machine that has sufficient spare CPU to run `make buildworld` and `make buildkernel`. Select a machine to be the _test machine_, which will test software updates before they are put into production. This _must_ be a machine that can afford to be down for an extended period of time. It can be the build machine, but need not be. All the machines in this build set need to mount [.filename]#/usr/obj# and [.filename]#/usr/src# from the build machine via NFS. For multiple build sets, [.filename]#/usr/src# should be on one build machine, and NFS mounted on the rest. Ensure that [.filename]#/etc/make.conf# and [.filename]#/etc/src.conf# on all the machines in the build set agree with the build machine. That means that the build machine must build all the parts of the base system that any machine in the build set is going to install. Also, each build machine should have its kernel name set with `KERNCONF` in [.filename]#/etc/make.conf#, and the build machine should list them all in its `KERNCONF`, listing its own kernel first. The build machine must have the kernel configuration files for each machine in its [.filename]#/usr/src/sys/arch/conf#. On the build machine, build the kernel and world as described in <>, but do not install anything on the build machine. Instead, install the built kernel on the test machine. On the test machine, mount [.filename]#/usr/src# and [.filename]#/usr/obj# via NFS. Then, run `shutdown now` to go to single-user mode in order to install the new kernel and world and run `mergemaster` as usual. When done, reboot to return to normal multi-user operations. After verifying that everything on the test machine is working properly, use the same procedure to install the new software on each of the other machines in the build set. The same methodology can be used for the ports tree. The first step is to share [.filename]#/usr/ports# via NFS to all the machines in the build set. To configure [.filename]#/etc/make.conf# to share distfiles, set `DISTDIR` to a common shared directory that is writable by whichever user `root` is mapped to by the NFS mount. Each machine should set `WRKDIRPREFIX` to a local build directory, if ports are to be built locally. Alternately, if the build system is to build and distribute packages to the machines in the build set, set `PACKAGES` on the build system to a directory similar to `DISTDIR`. diff --git a/documentation/content/en/books/handbook/dtrace/_index.adoc b/documentation/content/en/books/handbook/dtrace/_index.adoc index 3a3dd2d186..33adc59fef 100644 --- a/documentation/content/en/books/handbook/dtrace/_index.adoc +++ b/documentation/content/en/books/handbook/dtrace/_index.adoc @@ -1,229 +1,229 @@ --- title: Chapter 25. DTrace part: Part III. System Administration prev: books/handbook/cutting-edge next: books/handbook/usb-device-mode --- [[dtrace]] = DTrace :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 25 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/dtrace/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[dtrace-synopsis]] == Synopsis DTrace, also known as Dynamic Tracing, was developed by Sun(TM) as a tool for locating performance bottlenecks in production and pre-production systems. In addition to diagnosing performance problems, DTrace can be used to help investigate and debug unexpected behavior in both the FreeBSD kernel and in userland programs. DTrace is a remarkable profiling tool, with an impressive array of features for diagnosing system issues. It may also be used to run pre-written scripts to take advantage of its capabilities. Users can author their own utilities using the DTrace D Language, allowing them to customize their profiling based on specific needs. The FreeBSD implementation provides full support for kernel DTrace and experimental support for userland DTrace. Userland DTrace allows users to perform function boundary tracing for userland programs using the `pid` provider, and to insert static probes into userland programs for later tracing. Some ports, such as package:databases/postgresql12-server[] and package:lang/php74[] have a DTrace option to enable static probes. The official guide to DTrace is maintained by the Illumos project at http://dtrace.org/guide[DTrace Guide]. After reading this chapter, you will know: * What DTrace is and what features it provides. * Differences between the Solaris(TM) DTrace implementation and the one provided by FreeBSD. * How to enable and use DTrace on FreeBSD. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Have some familiarity with security and how it pertains to FreeBSD (crossref:security[security,Security]). [[dtrace-implementation]] == Implementation Differences While the DTrace in FreeBSD is similar to that found in Solaris(TM), differences do exist. The primary difference is that in FreeBSD, DTrace is implemented as a set of kernel modules and DTrace can not be used until the modules are loaded. To load all of the necessary modules: [source,bash] .... # kldload dtraceall .... Beginning with FreeBSD 10.0-RELEASE, the modules are automatically loaded when `dtrace` is run. FreeBSD uses the `DDB_CTF` kernel option to enable support for loading `CTF` data from kernel modules and the kernel itself. `CTF` is the Solaris(TM) Compact C Type Format which encapsulates a reduced form of debugging information similar to `DWARF` and the venerable stabs. `CTF` data is added to binaries by the `ctfconvert` and `ctfmerge` build tools. The `ctfconvert` utility parses `DWARF``ELF` debug sections created by the compiler and `ctfmerge` merges `CTF``ELF` sections from objects into either executables or shared libraries. Some different providers exist for FreeBSD than for Solaris(TM). Most notable is the `dtmalloc` provider, which allows tracing `malloc()` by type in the FreeBSD kernel. Some of the providers found in Solaris(TM), such as `cpc` and `mib`, are not present in FreeBSD. These may appear in future versions of FreeBSD. Moreover, some of the providers available in both operating systems are not compatible, in the sense that their probes have different argument types. Thus, `D` scripts written on Solaris(TM) may or may not work unmodified on FreeBSD, and vice versa. Due to security differences, only `root` may use DTrace on FreeBSD. Solaris(TM) has a few low level security checks which do not yet exist in FreeBSD. As such, the [.filename]#/dev/dtrace/dtrace# is strictly limited to `root`. DTrace falls under the Common Development and Distribution License (`CDDL`) license. To view this license on FreeBSD, see [.filename]#/usr/src/cddl/contrib/opensolaris/OPENSOLARIS.LICENSE# or view it online at http://opensource.org/licenses/CDDL-1.0[http://opensource.org/licenses/CDDL-1.0]. While a FreeBSD kernel with DTrace support is `BSD` licensed, the `CDDL` is used when the modules are distributed in binary form or the binaries are loaded. [[dtrace-enable]] == Enabling DTrace Support In FreeBSD 9.2 and 10.0, DTrace support is built into the [.filename]#GENERIC# kernel. Users of earlier versions of FreeBSD or who prefer to statically compile in DTrace support should add the following lines to a custom kernel configuration file and recompile the kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [.programlisting] .... options KDTRACE_HOOKS options DDB_CTF makeoptions DEBUG=-g makeoptions WITH_CTF=1 .... Users of the AMD64 architecture should also add this line: [.programlisting] .... options KDTRACE_FRAME .... This option provides support for `FBT`. While DTrace will work without this option, there will be limited support for function boundary tracing. Once the FreeBSD system has rebooted into the new kernel, or the DTrace kernel modules have been loaded using `kldload dtraceall`, the system will need support for the Korn shell as the DTrace Toolkit has several utilities written in `ksh`. Make sure that the package:shells/ksh93[] package or port is installed. It is also possible to run these tools under package:shells/pdksh[] or package:shells/mksh[]. -Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/shared/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/DTraceToolkit[] package or port. +Finally, install the current DTrace Toolkit, a collection of ready-made scripts for collecting system information. There are scripts to check open files, memory, `CPU` usage, and a lot more. FreeBSD 10 installs a few of these scripts into [.filename]#/usr/share/dtrace#. On other FreeBSD versions, or to install the full DTrace Toolkit, use the package:sysutils/DTraceToolkit[] package or port. [NOTE] ==== -The scripts found in [.filename]#/usr/shared/dtrace# have been specifically ported to FreeBSD. Not all of the scripts found in the DTrace Toolkit will work as-is on FreeBSD and some scripts may require some effort in order for them to work on FreeBSD. +The scripts found in [.filename]#/usr/share/dtrace# have been specifically ported to FreeBSD. Not all of the scripts found in the DTrace Toolkit will work as-is on FreeBSD and some scripts may require some effort in order for them to work on FreeBSD. ==== The DTrace Toolkit includes many scripts in the special language of DTrace. This language is called the D language and it is very similar to C++. An in depth discussion of the language is beyond the scope of this document. It is covered extensively in the http://www.dtrace.org/guide[Illumos Dynamic Tracing Guide]. [[dtrace-using]] == Using DTrace DTrace scripts consist of a list of one or more _probes_, or instrumentation points, where each probe is associated with an action. Whenever the condition for a probe is met, the associated action is executed. For example, an action may occur when a file is opened, a process is started, or a line of code is executed. The action might be to log some information or to modify context variables. The reading and writing of context variables allows probes to share information and to cooperatively analyze the correlation of different events. To view all probes, the administrator can execute the following command: [source,bash] .... # dtrace -l | more .... Each probe has an `ID`, a `PROVIDER` (dtrace or fbt), a `MODULE`, and a `FUNCTION NAME`. Refer to man:dtrace[1] for more information about this command. The examples in this section provide an overview of how to use two of the fully supported scripts from the DTrace Toolkit: the [.filename]#hotkernel# and [.filename]#procsystime# scripts. The [.filename]#hotkernel# script is designed to identify which function is using the most kernel time. It will produce output similar to the following: [source,bash] .... # cd /usr/local/shared/dtrace-toolkit # ./hotkernel Sampling... Hit Ctrl-C to end. .... As instructed, use the kbd:[Ctrl+C] key combination to stop the process. Upon termination, the script will display a list of kernel functions and timing information, sorting the output in increasing order of time: [source,bash] .... kernel`_thread_lock_flags 2 0.0% 0xc1097063 2 0.0% kernel`sched_userret 2 0.0% kernel`kern_select 2 0.0% kernel`generic_copyin 3 0.0% kernel`_mtx_assert 3 0.0% kernel`vm_fault 3 0.0% kernel`sopoll_generic 3 0.0% kernel`fixup_filename 4 0.0% kernel`_isitmyx 4 0.0% kernel`find_instance 4 0.0% kernel`_mtx_unlock_flags 5 0.0% kernel`syscall 5 0.0% kernel`DELAY 5 0.0% 0xc108a253 6 0.0% kernel`witness_lock 7 0.0% kernel`read_aux_data_no_wait 7 0.0% kernel`Xint0x80_syscall 7 0.0% kernel`witness_checkorder 7 0.0% kernel`sse2_pagezero 8 0.0% kernel`strncmp 9 0.0% kernel`spinlock_exit 10 0.0% kernel`_mtx_lock_flags 11 0.0% kernel`witness_unlock 15 0.0% kernel`sched_idletd 137 0.3% 0xc10981a5 42139 99.3% .... This script will also work with kernel modules. To use this feature, run the script with `-m`: [source,bash] .... # ./hotkernel -m Sampling... Hit Ctrl-C to end. ^C MODULE COUNT PCNT 0xc107882e 1 0.0% 0xc10e6aa4 1 0.0% 0xc1076983 1 0.0% 0xc109708a 1 0.0% 0xc1075a5d 1 0.0% 0xc1077325 1 0.0% 0xc108a245 1 0.0% 0xc107730d 1 0.0% 0xc1097063 2 0.0% 0xc108a253 73 0.0% kernel 874 0.4% 0xc10981a5 213781 99.6% .... The [.filename]#procsystime# script captures and prints the system call time usage for a given process `ID` (`PID`) or process name. In the following example, a new instance of [.filename]#/bin/csh# was spawned. Then, [.filename]#procsystime# was executed and remained waiting while a few commands were typed on the other incarnation of `csh`. These are the results of this test: [source,bash] .... # ./procsystime -n csh Tracing... Hit Ctrl-C to end... ^C Elapsed Times for processes csh, SYSCALL TIME (ns) getpid 6131 sigreturn 8121 close 19127 fcntl 19959 dup 26955 setpgid 28070 stat 31899 setitimer 40938 wait4 62717 sigaction 67372 sigprocmask 119091 gettimeofday 183710 write 263242 execve 492547 ioctl 770073 vfork 3258923 sigsuspend 6985124 read 3988049784 .... As shown, the `read()` system call used the most time in nanoseconds while the `getpid()` system call used the least amount of time. diff --git a/documentation/content/en/books/handbook/firewalls/_index.adoc b/documentation/content/en/books/handbook/firewalls/_index.adoc index 65fb2fed25..9307e1a0d1 100644 --- a/documentation/content/en/books/handbook/firewalls/_index.adoc +++ b/documentation/content/en/books/handbook/firewalls/_index.adoc @@ -1,2225 +1,2225 @@ --- title: Chapter 31. Firewalls part: IV. Network Communication prev: books/handbook/network-servers next: books/handbook/advanced-networking --- [[firewalls]] = Firewalls :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 31 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/firewalls/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/firewalls/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/firewalls/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[firewalls-intro]] == Synopsis Firewalls make it possible to filter the incoming and outgoing traffic that flows through a system. A firewall can use one or more sets of "rules" to inspect network packets as they come in or go out of network connections and either allows the traffic through or blocks it. The rules of a firewall can inspect one or more characteristics of the packets such as the protocol type, source or destination host address, and source or destination port. Firewalls can enhance the security of a host or a network. They can be used to do one or more of the following: * Protect and insulate the applications, services, and machines of an internal network from unwanted traffic from the public Internet. * Limit or disable access from hosts of the internal network to services of the public Internet. * Support network address translation (NAT), which allows an internal network to use private IP addresses and share a single connection to the public Internet using either a single IP address or a shared pool of automatically assigned public addresses. FreeBSD has three firewalls built into the base system: PF, IPFW, and IPFILTER, also known as IPF. FreeBSD also provides two traffic shapers for controlling bandwidth usage: man:altq[4] and man:dummynet[4]. ALTQ has traditionally been closely tied with PF and dummynet with IPFW. Each firewall uses rules to control the access of packets to and from a FreeBSD system, although they go about it in different ways and each has a different rule syntax. FreeBSD provides multiple firewalls in order to meet the different requirements and preferences for a wide variety of users. Each user should evaluate which firewall best meets their needs. After reading this chapter, you will know: * How to define packet filtering rules. * The differences between the firewalls built into FreeBSD. * How to use and configure the PF firewall. * How to use and configure the IPFW firewall. * How to use and configure the IPFILTER firewall. Before reading this chapter, you should: * Understand basic FreeBSD and Internet concepts. [NOTE] ==== Since all firewalls are based on inspecting the values of selected packet control fields, the creator of the firewall ruleset must have an understanding of how TCP/IP works, what the different values in the packet control fields are, and how these values are used in a normal session conversation. For a good introduction, refer to http://www.ipprimer.com[Daryl's TCP/IP Primer]. ==== [[firewalls-concepts]] == Firewall Concepts A ruleset contains a group of rules which pass or block packets based on the values contained in the packet. The bi-directional exchange of packets between hosts comprises a session conversation. The firewall ruleset processes both the packets arriving from the public Internet, as well as the packets produced by the system as a response to them. Each TCP/IP service is predefined by its protocol and listening port. Packets destined for a specific service originate from the source address using an unprivileged port and target the specific service port on the destination address. All the above parameters can be used as selection criteria to create rules which will pass or block services. To lookup unknown port numbers, refer to [.filename]#/etc/services#. Alternatively, visit http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers[http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers] and do a port number lookup to find the purpose of a particular port number. Check out this link for http://web.archive.org/web/20150803024617/http://www.sans.org/security-resources/idfaq/oddports.php[port numbers used by Trojans]. FTP has two modes: active mode and passive mode. The difference is in how the data channel is acquired. Passive mode is more secure as the data channel is acquired by the ordinal ftp session requester. For a good explanation of FTP and the different modes, see http://www.slacksite.com/other/ftp.html[http://www.slacksite.com/other/ftp.html]. A firewall ruleset can be either "exclusive" or "inclusive". An exclusive firewall allows all traffic through except for the traffic matching the ruleset. An inclusive firewall does the reverse as it only allows traffic matching the rules through and blocks everything else. An inclusive firewall offers better control of the outgoing traffic, making it a better choice for systems that offer services to the public Internet. It also controls the type of traffic originating from the public Internet that can gain access to a private network. All traffic that does not match the rules is blocked and logged. Inclusive firewalls are generally safer than exclusive firewalls because they significantly reduce the risk of allowing unwanted traffic. [NOTE] ==== Unless noted otherwise, all configuration and example rulesets in this chapter create inclusive firewall rulesets. ==== Security can be tightened further using a "stateful firewall". This type of firewall keeps track of open connections and only allows traffic which either matches an existing connection or opens a new, allowed connection. Stateful filtering treats traffic as a bi-directional exchange of packets comprising a session. When state is specified on a matching rule the firewall dynamically generates internal rules for each anticipated packet being exchanged during the session. It has sufficient matching capabilities to determine if a packet is valid for a session. Any packets that do not properly fit the session template are automatically rejected. When the session completes, it is removed from the dynamic state table. Stateful filtering allows one to focus on blocking/passing new sessions. If the new session is passed, all its subsequent packets are allowed automatically and any impostor packets are automatically rejected. If a new session is blocked, none of its subsequent packets are allowed. Stateful filtering provides advanced matching abilities capable of defending against the flood of different attack methods employed by attackers. NAT stands for _Network Address Translation_. NAT function enables the private LAN behind the firewall to share a single ISP-assigned IP address, even if that address is dynamically assigned. NAT allows each computer in the LAN to have Internet access, without having to pay the ISP for multiple Internet accounts or IP addresses. NAT will automatically translate the private LAN IP address for each system on the LAN to the single public IP address as packets exit the firewall bound for the public Internet. It also performs the reverse translation for returning packets. According to RFC 1918, the following IP address ranges are reserved for private networks which will never be routed directly to the public Internet, and therefore are available for use with NAT: * `10.0.0.0/8`. * `172.16.0.0/12`. * `192.168.0.0/16`. [WARNING] ==== When working with the firewall rules, be _very careful_. Some configurations _can lock the administrator out_ of the server. To be on the safe side, consider performing the initial firewall configuration from the local console rather than doing it remotely over ssh. ==== [[firewalls-pf]] == PF Since FreeBSD 5.3, a ported version of OpenBSD's PF firewall has been included as an integrated part of the base system. PF is a complete, full-featured firewall that has optional support for ALTQ (Alternate Queuing), which provides Quality of Service (QoS). The OpenBSD Project maintains the definitive reference for PF in the http://www.openbsd.org/faq/pf/[PF FAQ]. Peter Hansteen maintains a thorough PF tutorial at http://home.nuug.no/\~peter/pf/[http://home.nuug.no/~peter/pf/]. [WARNING] ==== When reading the http://www.openbsd.org/faq/pf/[PF FAQ], keep in mind that FreeBSD's version of PF has diverged substantially from the upstream OpenBSD version over the years. Not all features work the same way on FreeBSD as they do in OpenBSD and vice versa. ==== The {freebsd-pf} is a good place to ask questions about configuring and running the PF firewall. Check the mailing list archives before asking a question as it may have already been answered. This section of the Handbook focuses on PF as it pertains to FreeBSD. It demonstrates how to enable PF and ALTQ. It also provides several examples for creating rulesets on a FreeBSD system. === Enabling PF To use PF, its kernel module must be first loaded. This section describes the entries that can be added to [.filename]#/etc/rc.conf# to enable PF. Start by adding `pf_enable=yes` to [.filename]#/etc/rc.conf#: [source,bash] .... # sysrc pf_enable=yes .... Additional options, described in man:pfctl[8], can be passed to PF when it is started. Add or change this entry in [.filename]#/etc/rc.conf# and specify any required flags between the two quotes (`""`): [.programlisting] .... pf_flags="" # additional flags for pfctl startup .... -PF will not start if it cannot find its ruleset configuration file. By default, FreeBSD does not ship with a ruleset and there is no [.filename]#/etc/pf.conf#. Example rulesets can be found in [.filename]#/usr/shared/examples/pf/#. If a custom ruleset has been saved somewhere else, add a line to [.filename]#/etc/rc.conf# which specifies the full path to the file: +PF will not start if it cannot find its ruleset configuration file. By default, FreeBSD does not ship with a ruleset and there is no [.filename]#/etc/pf.conf#. Example rulesets can be found in [.filename]#/usr/share/examples/pf/#. If a custom ruleset has been saved somewhere else, add a line to [.filename]#/etc/rc.conf# which specifies the full path to the file: [.programlisting] .... pf_rules="/path/to/pf.conf" .... Logging support for PF is provided by man:pflog[4]. To enable logging support, add `pflog_enable=yes` to [.filename]#/etc/rc.conf#: [source,bash] .... # sysrc pflog_enable=yes .... The following lines can also be added to change the default location of the log file or to specify any additional flags to pass to man:pflog[4] when it is started: [.programlisting] .... pflog_logfile="/var/log/pflog" # where pflogd should store the logfile pflog_flags="" # additional flags for pflogd startup .... Finally, if there is a LAN behind the firewall and packets need to be forwarded for the computers on the LAN, or NAT is required, enable the following option: [.programlisting] .... gateway_enable="YES" # Enable as LAN gateway .... After saving the needed edits, PF can be started with logging support by typing: [source,bash] .... # service pf start # service pflog start .... -By default, PF reads its configuration rules from [.filename]#/etc/pf.conf# and modifies, drops, or passes packets according to the rules or definitions specified in this file. The FreeBSD installation includes several sample files located in [.filename]#/usr/shared/examples/pf/#. Refer to the http://www.openbsd.org/faq/pf/[PF FAQ] for complete coverage of PF rulesets. +By default, PF reads its configuration rules from [.filename]#/etc/pf.conf# and modifies, drops, or passes packets according to the rules or definitions specified in this file. The FreeBSD installation includes several sample files located in [.filename]#/usr/share/examples/pf/#. Refer to the http://www.openbsd.org/faq/pf/[PF FAQ] for complete coverage of PF rulesets. To control PF, use `pfctl`. <> summarizes some useful options to this command. Refer to man:pfctl[8] for a description of all available options: [[pfctl]] .Useful `pfctl` Options [cols="1,1", frame="none", options="header"] |=== | Command | Purpose |`pfctl -e` |Enable PF. |`pfctl -d` |Disable PF. |`pfctl -F all -f /etc/pf.conf` |Flush all NAT, filter, state, and table rules and reload [.filename]#/etc/pf.conf#. |`pfctl -s [ rules \| nat \| states ]` |Report on the filter rules, NAT rules, or state table. |`pfctl -vnf /etc/pf.conf` |Check [.filename]#/etc/pf.conf# for errors, but do not load ruleset. |=== [TIP] ==== package:security/sudo[] is useful for running commands like `pfctl` that require elevated privileges. It can be installed from the Ports Collection. ==== To keep an eye on the traffic that passes through the PF firewall, consider installing the package:sysutils/pftop[] package or port. Once installed, pftop can be run to view a running snapshot of traffic in a format which is similar to man:top[1]. [[pf-tutorial]] === PF Rulesets This section demonstrates how to create a customized ruleset. It starts with the simplest of rulesets and builds upon its concepts using several examples to demonstrate real-world usage of PF's many features. The simplest possible ruleset is for a single machine that does not run any services and which needs access to one network, which may be the Internet. To create this minimal ruleset, edit [.filename]#/etc/pf.conf# so it looks like this: [.programlisting] .... block in all pass out all keep state .... The first rule denies all incoming traffic by default. The second rule allows connections created by this system to pass out, while retaining state information on those connections. This state information allows return traffic for those connections to pass back and should only be used on machines that can be trusted. The ruleset can be loaded with: [source,bash] .... # pfctl -e ; pfctl -f /etc/pf.conf .... In addition to keeping state, PF provides _lists_ and _macros_ which can be defined for use when creating rules. Macros can include lists and need to be defined before use. As an example, insert these lines at the very top of the ruleset: [.programlisting] .... tcp_services = "{ ssh, smtp, domain, www, pop3, auth, pop3s }" udp_services = "{ domain }" .... PF understands port names as well as port numbers, as long as the names are listed in [.filename]#/etc/services#. This example creates two macros. The first is a list of seven TCP port names and the second is one UDP port name. Once defined, macros can be used in rules. In this example, all traffic is blocked except for the connections initiated by this system for the seven specified TCP services and the one specified UDP service: [.programlisting] .... tcp_services = "{ ssh, smtp, domain, www, pop3, auth, pop3s }" udp_services = "{ domain }" block all pass out proto tcp to any port $tcp_services keep state pass proto udp to any port $udp_services keep state .... Even though UDP is considered to be a stateless protocol, PF is able to track some state information. For example, when a UDP request is passed which asks a name server about a domain name, PF will watch for the response to pass it back. Whenever an edit is made to a ruleset, the new rules must be loaded so they can be used: [source,bash] .... # pfctl -f /etc/pf.conf .... If there are no syntax errors, `pfctl` will not output any messages during the rule load. Rules can also be tested before attempting to load them: [source,bash] .... # pfctl -nf /etc/pf.conf .... Including `-n` causes the rules to be interpreted only, but not loaded. This provides an opportunity to correct any errors. At all times, the last valid ruleset loaded will be enforced until either PF is disabled or a new ruleset is loaded. [TIP] ==== Adding `-v` to a `pfctl` ruleset verify or load will display the fully parsed rules exactly the way they will be loaded. This is extremely useful when debugging rules. ==== [[pftut-gateway]] ==== A Simple Gateway with NAT This section demonstrates how to configure a FreeBSD system running PF to act as a gateway for at least one other machine. The gateway needs at least two network interfaces, each connected to a separate network. In this example, [.filename]#xl0# is connected to the Internet and [.filename]#xl1# is connected to the internal network. First, enable the gateway to let the machine forward the network traffic it receives on one interface to another interface. This sysctl setting will forward IPv4 packets: [source,bash] .... # sysctl net.inet.ip.forwarding=1 .... To forward IPv6 traffic, use: [source,bash] .... # sysctl net.inet6.ip6.forwarding=1 .... To enable these settings at system boot, use man:sysrc[8] to add them to [.filename]#/etc/rc.conf#: [source,bash] .... # sysrc gateway_enable=yes # sysrc ipv6_gateway_enable=yes .... Verify with `ifconfig` that both of the interfaces are up and running. Next, create the PF rules to allow the gateway to pass traffic. While the following rule allows stateful traffic from hosts of the internal network to pass to the gateway, the `to` keyword does not guarantee passage all the way from source to destination: [.programlisting] .... pass in on xl1 from xl1:network to xl0:network port $ports keep state .... That rule only lets the traffic pass in to the gateway on the internal interface. To let the packets go further, a matching rule is needed: [.programlisting] .... pass out on xl0 from xl1:network to xl0:network port $ports keep state .... While these two rules will work, rules this specific are rarely needed. For a busy network admin, a readable ruleset is a safer ruleset. The remainder of this section demonstrates how to keep the rules as simple as possible for readability. For example, those two rules could be replaced with one rule: [.programlisting] .... pass from xl1:network to any port $ports keep state .... The `interface:network` notation can be replaced with a macro to make the ruleset even more readable. For example, a `$localnet` macro could be defined as the network directly attached to the internal interface (`$xl1:network`). Alternatively, the definition of `$localnet` could be changed to an _IP address/netmask_ notation to denote a network, such as `192.168.100.1/24` for a subnet of private addresses. If required, `$localnet` could even be defined as a list of networks. Whatever the specific needs, a sensible `$localnet` definition could be used in a typical pass rule as follows: [.programlisting] .... pass from $localnet to any port $ports keep state .... The following sample ruleset allows all traffic initiated by machines on the internal network. It first defines two macros to represent the external and internal 3COM interfaces of the gateway. [NOTE] ==== For dialup users, the external interface will use [.filename]#tun0#. For an ADSL connection, specifically those using PPP over Ethernet (PPPoE), the correct external interface is [.filename]#tun0#, not the physical Ethernet interface. ==== [.programlisting] .... ext_if = "xl0" # macro for external interface - use tun0 for PPPoE int_if = "xl1" # macro for internal interface localnet = $int_if:network # ext_if IP address could be dynamic, hence ($ext_if) nat on $ext_if from $localnet to any -> ($ext_if) block all pass from { lo0, $localnet } to any keep state .... This ruleset introduces the `nat` rule which is used to handle the network address translation from the non-routable addresses inside the internal network to the IP address assigned to the external interface. The parentheses surrounding the last part of the nat rule `($ext_if)` is included when the IP address of the external interface is dynamically assigned. It ensures that network traffic runs without serious interruptions even if the external IP address changes. Note that this ruleset probably allows more traffic to pass out of the network than is needed. One reasonable setup could create this macro: [.programlisting] .... client_out = "{ ftp-data, ftp, ssh, domain, pop3, auth, nntp, http, \ https, cvspserver, 2628, 5999, 8000, 8080 }" .... to use in the main pass rule: [.programlisting] .... pass inet proto tcp from $localnet to any port $client_out \ flags S/SA keep state .... A few other pass rules may be needed. This one enables SSH on the external interface: [.programlisting] .... pass in inet proto tcp to $ext_if port ssh .... This macro definition and rule allows DNS and NTP for internal clients: [.programlisting] .... udp_services = "{ domain, ntp }" pass quick inet proto { tcp, udp } to any port $udp_services keep state .... Note the `quick` keyword in this rule. Since the ruleset consists of several rules, it is important to understand the relationships between the rules in a ruleset. Rules are evaluated from top to bottom, in the sequence they are written. For each packet or connection evaluated by PF, _the last matching rule_ in the ruleset is the one which is applied. However, when a packet matches a rule which contains the `quick` keyword, the rule processing stops and the packet is treated according to that rule. This is very useful when an exception to the general rules is needed. [[pftut-ftp]] ==== Creating an FTP Proxy Configuring working FTP rules can be problematic due to the nature of the FTP protocol. FTP pre-dates firewalls by several decades and is insecure in its design. The most common points against using FTP include: * Passwords are transferred in the clear. * The protocol demands the use of at least two TCP connections (control and data) on separate ports. * When a session is established, data is communicated using randomly selected ports. All of these points present security challenges, even before considering any potential security weaknesses in client or server software. More secure alternatives for file transfer exist, such as man:sftp[1] or man:scp[1], which both feature authentication and data transfer over encrypted connections.. For those situations when FTP is required, PF provides redirection of FTP traffic to a small proxy program called man:ftp-proxy[8], which is included in the base system of FreeBSD. The role of the proxy is to dynamically insert and delete rules in the ruleset, using a set of anchors, to correctly handle FTP traffic. To enable the FTP proxy, add this line to [.filename]#/etc/rc.conf#: [.programlisting] .... ftpproxy_enable="YES" .... Then start the proxy by running `service ftp-proxy start`. For a basic configuration, three elements need to be added to [.filename]#/etc/pf.conf#. First, the anchors which the proxy will use to insert the rules it generates for the FTP sessions: [.programlisting] .... nat-anchor "ftp-proxy/*" rdr-anchor "ftp-proxy/*" .... Second, a pass rule is needed to allow FTP traffic in to the proxy. Third, redirection and NAT rules need to be defined before the filtering rules. Insert this `rdr` rule immediately after the `nat` rule: [.programlisting] .... rdr pass on $int_if proto tcp from any to any port ftp -> 127.0.0.1 port 8021 .... Finally, allow the redirected traffic to pass: [.programlisting] .... pass out proto tcp from $proxy to any port ftp .... where `$proxy` expands to the address the proxy daemon is bound to. Save [.filename]#/etc/pf.conf#, load the new rules, and verify from a client that FTP connections are working: [source,bash] .... # pfctl -f /etc/pf.conf .... This example covers a basic setup where the clients in the local network need to contact FTP servers elsewhere. This basic configuration should work well with most combinations of FTP clients and servers. As shown in man:ftp-proxy[8], the proxy's behavior can be changed in various ways by adding options to the `ftpproxy_flags=` line. Some clients or servers may have specific quirks that must be compensated for in the configuration, or there may be a need to integrate the proxy in specific ways such as assigning FTP traffic to a specific queue. For ways to run an FTP server protected by PF and man:ftp-proxy[8], configure a separate `ftp-proxy` in reverse mode, using `-R`, on a separate port with its own redirecting pass rule. [[pftut-icmp]] ==== Managing ICMP Many of the tools used for debugging or troubleshooting a TCP/IP network rely on the Internet Control Message Protocol (ICMP), which was designed specifically with debugging in mind. The ICMP protocol sends and receives _control messages_ between hosts and gateways, mainly to provide feedback to a sender about any unusual or difficult conditions enroute to the target host. Routers use ICMP to negotiate packet sizes and other transmission parameters in a process often referred to as _path MTU discovery_. From a firewall perspective, some ICMP control messages are vulnerable to known attack vectors. Also, letting all diagnostic traffic pass unconditionally makes debugging easier, but it also makes it easier for others to extract information about the network. For these reasons, the following rule may not be optimal: [.programlisting] .... pass inet proto icmp from any to any .... One solution is to let all ICMP traffic from the local network through while stopping all probes from outside the network: [.programlisting] .... pass inet proto icmp from $localnet to any keep state pass inet proto icmp from any to $ext_if keep state .... Additional options are available which demonstrate some of PF's flexibility. For example, rather than allowing all ICMP messages, one can specify the messages used by man:ping[8] and man:traceroute[8]. Start by defining a macro for that type of message: [.programlisting] .... icmp_types = "echoreq" .... and a rule which uses the macro: [.programlisting] .... pass inet proto icmp all icmp-type $icmp_types keep state .... If other types of ICMP packets are needed, expand `icmp_types` to a list of those packet types. Type `more /usr/src/sbin/pfctl/pfctl_parser.c` to see the list of ICMP message types supported by PF. Refer to http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml[http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml] for an explanation of each message type. Since Unix `traceroute` uses UDP by default, another rule is needed to allow Unix `traceroute`: [.programlisting] .... # allow out the default range for traceroute(8): pass out on $ext_if inet proto udp from any to any port 33433 >< 33626 keep state .... Since `TRACERT.EXE` on Microsoft Windows systems uses ICMP echo request messages, only the first rule is needed to allow network traces from those systems. Unix `traceroute` can be instructed to use other protocols as well, and will use ICMP echo request messages if `-I` is used. Check the man:traceroute[8] man page for details. [[pftut-pathmtudisc]] ===== Path MTU Discovery Internet protocols are designed to be device independent, and one consequence of device independence is that the optimal packet size for a given connection cannot always be predicted reliably. The main constraint on packet size is the _Maximum Transmission Unit_ (MTU) which sets the upper limit on the packet size for an interface. Type `ifconfig` to view the MTUs for a system's network interfaces. TCP/IP uses a process known as path MTU discovery to determine the right packet size for a connection. This process sends packets of varying sizes with the "Do not fragment" flag set, expecting an ICMP return packet of "type 3, code 4" when the upper limit has been reached. Type 3 means "destination unreachable", and code 4 is short for "fragmentation needed, but the do-not-fragment flag is set". To allow path MTU discovery in order to support connections to other MTUs, add the `destination unreachable` type to the `icmp_types` macro: [.programlisting] .... icmp_types = "{ echoreq, unreach }" .... Since the pass rule already uses that macro, it does not need to be modified to support the new ICMP type: [.programlisting] .... pass inet proto icmp all icmp-type $icmp_types keep state .... PF allows filtering on all variations of ICMP types and codes. The list of possible types and codes are documented in man:icmp[4] and man:icmp6[4]. [[pftut-tables]] ==== Using Tables Some types of data are relevant to filtering and redirection at a given time, but their definition is too long to be included in the ruleset file. PF supports the use of tables, which are defined lists that can be manipulated without needing to reload the entire ruleset, and which can provide fast lookups. Table names are always enclosed within `< >`, like this: [.programlisting] .... table { 192.168.2.0/24, !192.168.2.5 } .... In this example, the `192.168.2.0/24` network is part of the table, except for the address `192.168.2.5`, which is excluded using the `!` operator. It is also possible to load tables from files where each item is on a separate line, as seen in this example [.filename]#/etc/clients#: [.programlisting] .... 192.168.2.0/24 !192.168.2.5 .... To refer to the file, define the table like this: [.programlisting] .... table persist file "/etc/clients" .... Once the table is defined, it can be referenced by a rule: [.programlisting] .... pass inet proto tcp from to any port $client_out flags S/SA keep state .... A table's contents can be manipulated live, using `pfctl`. This example adds another network to the table: [source,bash] .... # pfctl -t clients -T add 192.168.1.0/16 .... Note that any changes made this way will take affect now, making them ideal for testing, but will not survive a power failure or reboot. To make the changes permanent, modify the definition of the table in the ruleset or edit the file that the table refers to. One can maintain the on-disk copy of the table using a man:cron[8] job which dumps the table's contents to disk at regular intervals, using a command such as `pfctl -t clients -T show >/etc/clients`. Alternatively, [.filename]#/etc/clients# can be updated with the in-memory table contents: [source,bash] .... # pfctl -t clients -T replace -f /etc/clients .... [[pftut-overload]] ==== Using Overload Tables to Protect SSH Those who run SSH on an external interface have probably seen something like this in the authentication logs: [.programlisting] .... Sep 26 03:12:34 skapet sshd[25771]: Failed password for root from 200.72.41.31 port 40992 ssh2 Sep 26 03:12:34 skapet sshd[5279]: Failed password for root from 200.72.41.31 port 40992 ssh2 Sep 26 03:12:35 skapet sshd[5279]: Received disconnect from 200.72.41.31: 11: Bye Bye Sep 26 03:12:44 skapet sshd[29635]: Invalid user admin from 200.72.41.31 Sep 26 03:12:44 skapet sshd[24703]: input_userauth_request: invalid user admin Sep 26 03:12:44 skapet sshd[24703]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2 .... This is indicative of a brute force attack where somebody or some program is trying to discover the user name and password which will let them into the system. If external SSH access is needed for legitimate users, changing the default port used by SSH can offer some protection. However, PF provides a more elegant solution. Pass rules can contain limits on what connecting hosts can do and violators can be banished to a table of addresses which are denied some or all access. It is even possible to drop all existing connections from machines which overreach the limits. To configure this, create this table in the tables section of the ruleset: [.programlisting] .... table persist .... Then, somewhere early in the ruleset, add rules to block brute access while allowing legitimate access: [.programlisting] .... block quick from pass inet proto tcp from any to $localnet port $tcp_services \ flags S/SA keep state \ (max-src-conn 100, max-src-conn-rate 15/5, \ overload flush global) .... The part in parentheses defines the limits and the numbers should be changed to meet local requirements. It can be read as follows: `max-src-conn` is the number of simultaneous connections allowed from one host. `max-src-conn-rate` is the rate of new connections allowed from any single host (_15_) per number of seconds (_5_). `overload ` means that any host which exceeds these limits gets its address added to the `bruteforce` table. The ruleset blocks all traffic from addresses in the `bruteforce` table. Finally, `flush global` says that when a host reaches the limit, that all (`global`) of that host's connections will be terminated (`flush`). [NOTE] ==== These rules will _not_ block slow bruteforcers, as described in http://home.nuug.no/\~peter/hailmary2013/[http://home.nuug.no/~peter/hailmary2013/]. ==== This example ruleset is intended mainly as an illustration. For example, if a generous number of connections in general are wanted, but the desire is to be more restrictive when it comes to ssh, supplement the rule above with something like the one below, early on in the rule set: [.programlisting] .... pass quick proto { tcp, udp } from any to any port ssh \ flags S/SA keep state \ (max-src-conn 15, max-src-conn-rate 5/3, \ overload flush global) .... [NOTE] ==== *It May Not be Necessary to Block All Overloaders:* + It is worth noting that the overload mechanism is a general technique which does not apply exclusively to SSH, and it is not always optimal to entirely block all traffic from offenders. For example, an overload rule could be used to protect a mail service or a web service, and the overload table could be used in a rule to assign offenders to a queue with a minimal bandwidth allocation or to redirect to a specific web page. ==== Over time, tables will be filled by overload rules and their size will grow incrementally, taking up more memory. Sometimes an IP address that is blocked is a dynamically assigned one, which has since been assigned to a host who has a legitimate reason to communicate with hosts in the local network. For situations like these, pfctl provides the ability to expire table entries. For example, this command will remove `` table entries which have not been referenced for `86400` seconds: [source,bash] .... # pfctl -t bruteforce -T expire 86400 .... Similar functionality is provided by package:security/expiretable[], which removes table entries which have not been accessed for a specified period of time. Once installed, expiretable can be run to remove `` table entries older than a specified age. This example removes all entries older than 24 hours: [.programlisting] .... /usr/local/sbin/expiretable -v -d -t 24h bruteforce .... [[pftut-spamd]] ==== Protecting Against SPAM Not to be confused with the spamd daemon which comes bundled with spamassassin, package:mail/spamd[] can be configured with PF to provide an outer defense against SPAM. This spamd hooks into the PF configuration using a set of redirections. Spammers tend to send a large number of messages, and SPAM is mainly sent from a few spammer friendly networks and a large number of hijacked machines, both of which are reported to _blacklists_ fairly quickly. When an SMTP connection from an address in a blacklist is received, spamd presents its banner and immediately switches to a mode where it answers SMTP traffic one byte at a time. This technique, which is intended to waste as much time as possible on the spammer's end, is called _tarpitting_. The specific implementation which uses one byte SMTP replies is often referred to as _stuttering_. This example demonstrates the basic procedure for setting up spamd with automatically updated blacklists. Refer to the man pages which are installed with package:mail/spamd[] for more information. [.procedure] **** .Procedure: Configuring spamd . Install the package:mail/spamd[] package or port. To use spamd's greylisting features, man:fdescfs[5] must be mounted at [.filename]#/dev/fd#. Add the following line to [.filename]#/etc/fstab#: + [.programlisting] .... fdescfs /dev/fd fdescfs rw 0 0 .... + Then, mount the filesystem: + [.programlisting] .... # mount fdescfs .... . Next, edit the PF ruleset to include: + [.programlisting] .... table persist table persist rdr pass on $ext_if inet proto tcp from to \ { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025 rdr pass on $ext_if inet proto tcp from ! to \ { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025 .... + The two tables `` and `` are essential. SMTP traffic from an address listed in `` but not in `` is redirected to the spamd daemon listening at port 8025. . The next step is to configure spamd in [.filename]#/usr/local/etc/spamd.conf# and to add some [.filename]#rc.conf# parameters. + The installation of package:mail/spamd[] includes a sample configuration file ([.filename]#/usr/local/etc/spamd.conf.sample#) and a man page for [.filename]#spamd.conf#. Refer to these for additional configuration options beyond those shown in this example. + One of the first lines in the configuration file that does not begin with a `#` comment sign contains the block which defines the `all` list, which specifies the lists to use: + [.programlisting] .... all:\ :traplist:whitelist: .... + This entry adds the desired blacklists, separated by colons (`:`). To use a whitelist to subtract addresses from a blacklist, add the name of the whitelist _immediately_ after the name of that blacklist. For example: `:blacklist:whitelist:`. + This is followed by the specified blacklist's definition: + [.programlisting] .... traplist:\ :black:\ :msg="SPAM. Your address %A has sent spam within the last 24 hours":\ :method=http:\ :file=www.openbsd.org/spamd/traplist.gz .... + where the first line is the name of the blacklist and the second line specifies the list type. The `msg` field contains the message to display to blacklisted senders during the SMTP dialogue. The `method` field specifies how spamd-setup fetches the list data; supported methods are `http`, `ftp`, from a `file` in a mounted file system, and via `exec` of an external program. Finally, the `file` field specifies the name of the file spamd expects to receive. + The definition of the specified whitelist is similar, but omits the `msg` field since a message is not needed: + [.programlisting] .... whitelist:\ :white:\ :method=file:\ :file=/var/mail/whitelist.txt .... + [TIP] ==== *Choose Data Sources with Care:* + Using all the blacklists in the sample [.filename]#spamd.conf# will blacklist large blocks of the Internet. Administrators need to edit the file to create an optimal configuration which uses applicable data sources and, when necessary, uses custom lists. ==== + Next, add this entry to [.filename]#/etc/rc.conf#. Additional flags are described in the man page specified by the comment: + [.programlisting] .... spamd_flags="-v" # use "" and see spamd-setup(8) for flags .... + When finished, reload the ruleset, start spamd by typing `service obspamd start`, and complete the configuration using `spamd-setup`. Finally, create a man:cron[8] job which calls `spamd-setup` to update the tables at reasonable intervals. **** On a typical gateway in front of a mail server, hosts will soon start getting trapped within a few seconds to several minutes. PF also supports _greylisting_, which temporarily rejects messages from unknown hosts with _45n_ codes. Messages from greylisted hosts which try again within a reasonable time are let through. Traffic from senders which are set up to behave within the limits set by RFC 1123 and RFC 2821 are immediately let through. More information about greylisting as a technique can be found at the http://www.greylisting.org/[greylisting.org] web site. The most amazing thing about greylisting, apart from its simplicity, is that it still works. Spammers and malware writers have been very slow to adapt to bypass this technique. The basic procedure for configuring greylisting is as follows: [.procedure] .Procedure: Configuring Greylisting . Make sure that man:fdescfs[5] is mounted as described in Step 1 of the previous Procedure. . To run spamd in greylisting mode, add this line to [.filename]#/etc/rc.conf#: + [.programlisting] .... spamd_grey="YES" # use spamd greylisting if YES .... + Refer to the spamd man page for descriptions of additional related parameters. . To complete the greylisting setup: + [.programlisting] .... # service obspamd restart # service obspamlogd start .... Behind the scenes, the spamdb database tool and the spamlogd whitelist updater perform essential functions for the greylisting feature. spamdb is the administrator's main interface to managing the black, grey, and white lists via the contents of the [.filename]#/var/db/spamdb# database. [[pftut-hygiene]] ==== Network Hygiene This section describes how `block-policy`, `scrub`, and `antispoof` can be used to make the ruleset behave sanely. The `block-policy` is an option which can be set in the `options` part of the ruleset, which precedes the redirection and filtering rules. This option determines which feedback, if any, PF sends to hosts that are blocked by a rule. The option has two possible values: `drop` drops blocked packets with no feedback, and `return` returns a status code such as `Connection refused`. If not set, the default policy is `drop`. To change the `block-policy`, specify the desired value: [.programlisting] .... set block-policy return .... In PF, `scrub` is a keyword which enables network packet normalization. This process reassembles fragmented packets and drops TCP packets that have invalid flag combinations. Enabling `scrub` provides a measure of protection against certain kinds of attacks based on incorrect handling of packet fragments. A number of options are available, but the simplest form is suitable for most configurations: [.programlisting] .... scrub in all .... Some services, such as NFS, require specific fragment handling options. Refer to https://home.nuug.no/\~peter/pf/en/scrub.html[https://home.nuug.no/~peter/pf/en/scrub.html] for more information. This example reassembles fragments, clears the "do not fragment" bit, and sets the maximum segment size to 1440 bytes: [.programlisting] .... scrub in all fragment reassemble no-df max-mss 1440 .... The `antispoof` mechanism protects against activity from spoofed or forged IP addresses, mainly by blocking packets appearing on interfaces and in directions which are logically not possible. These rules weed out spoofed traffic coming in from the rest of the world as well as any spoofed packets which originate in the local network: [.programlisting] .... antispoof for $ext_if antispoof for $int_if .... [[pftut-unrouteables]] ==== Handling Non-Routable Addresses Even with a properly configured gateway to handle network address translation, one may have to compensate for other people's misconfigurations. A common misconfiguration is to let traffic with non-routable addresses out to the Internet. Since traffic from non-routeable addresses can play a part in several DoS attack techniques, consider explicitly blocking traffic from non-routeable addresses from entering the network through the external interface. In this example, a macro containing non-routable addresses is defined, then used in blocking rules. Traffic to and from these addresses is quietly dropped on the gateway's external interface. [.programlisting] .... martians = "{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \ 10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \ 0.0.0.0/8, 240.0.0.0/4 }" block drop in quick on $ext_if from $martians to any block drop out quick on $ext_if from any to $martians .... === Enabling ALTQ On FreeBSD, ALTQ can be used with PF to provide Quality of Service (QOS). Once ALTQ is enabled, queues can be defined in the ruleset which determine the processing priority of outbound packets. Before enabling ALTQ, refer to man:altq[4] to determine if the drivers for the network cards installed on the system support it. ALTQ is not available as a loadable kernel module. If the system's interfaces support ALTQ, create a custom kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. The following kernel options are available. The first is needed to enable ALTQ. At least one of the other options is necessary to specify the queueing scheduler algorithm: [.programlisting] .... options ALTQ options ALTQ_CBQ # Class Based Queuing (CBQ) options ALTQ_RED # Random Early Detection (RED) options ALTQ_RIO # RED In/Out options ALTQ_HFSC # Hierarchical Packet Scheduler (HFSC) options ALTQ_PRIQ # Priority Queuing (PRIQ) .... The following scheduler algorithms are available: CBQ:: Class Based Queuing (CBQ) is used to divide a connection's bandwidth into different classes or queues to prioritize traffic based on filter rules. RED:: Random Early Detection (RED) is used to avoid network congestion by measuring the length of the queue and comparing it to the minimum and maximum thresholds for the queue. When the queue is over the maximum, all new packets are randomly dropped. RIO:: In Random Early Detection In and Out (RIO) mode, RED maintains multiple average queue lengths and multiple threshold values, one for each QOS level. HFSC:: Hierarchical Fair Service Curve Packet Scheduler (HFSC) is described in http://www-2.cs.cmu.edu/\~hzhang/HFSC/main.html[http://www-2.cs.cmu.edu/~hzhang/HFSC/main.html]. PRIQ:: Priority Queuing (PRIQ) always passes traffic that is in a higher queue first. More information about the scheduling algorithms and example rulesets are available at the https://web.archive.org/web/20151109213426/http://www.openbsd.org/faq/pf/queueing.html[OpenBSD's web archive]. [[firewalls-ipfw]] == IPFW IPFW is a stateful firewall written for FreeBSD which supports both IPv4 and IPv6. It is comprised of several components: the kernel firewall filter rule processor and its integrated packet accounting facility, the logging facility, NAT, the man:dummynet[4] traffic shaper, a forward facility, a bridge facility, and an ipstealth facility. FreeBSD provides a sample ruleset in [.filename]#/etc/rc.firewall# which defines several firewall types for common scenarios to assist novice users in generating an appropriate ruleset. IPFW provides a powerful syntax which advanced users can use to craft customized rulesets that meet the security requirements of a given environment. This section describes how to enable IPFW, provides an overview of its rule syntax, and demonstrates several rulesets for common configuration scenarios. [[firewalls-ipfw-enable]] === Enabling IPFW IPFW is included in the basic FreeBSD install as a kernel loadable module, meaning that a custom kernel is not needed in order to enable IPFW. For those users who wish to statically compile IPFW support into a custom kernel, see <>. To configure the system to enable IPFW at boot time, add `firewall_enable="YES"` to [.filename]#/etc/rc.conf#: [source,bash] .... # sysrc firewall_enable="YES" .... To use one of the default firewall types provided by FreeBSD, add another line which specifies the type: [source,bash] .... # sysrc firewall_type="open" .... The available types are: * `open`: passes all traffic. * `client`: protects only this machine. * `simple`: protects the whole network. * `closed`: entirely disables IP traffic except for the loopback interface. * `workstation`: protects only this machine using stateful rules. * `UNKNOWN`: disables the loading of firewall rules. * [.filename]#filename#: full path of the file containing the firewall ruleset. If `firewall_type` is set to either `client` or `simple`, modify the default rules found in [.filename]#/etc/rc.firewall# to fit the configuration of the system. Note that the `filename` type is used to load a custom ruleset. An alternate way to load a custom ruleset is to set the `firewall_script` variable to the absolute path of an _executable script_ that includes IPFW commands. The examples used in this section assume that the `firewall_script` is set to [.filename]#/etc/ipfw.rules#: [source,bash] .... # sysrc firewall_script="/etc/ipfw.rules" .... To enable logging through man:syslogd[8], include this line: [source,bash] .... # sysrc firewall_logging="YES" .... [WARNING] ==== Only firewall rules with the `log` option will be logged. The default rules do not include this option and it must be manually added. Therefore it is advisable that the default ruleset is edited for logging. In addition, log rotation may be desired if the logs are stored in a separate file. ==== There is no [.filename]#/etc/rc.conf# variable to set logging limits. To limit the number of times a rule is logged per connection attempt, specify the number using this line in [.filename]#/etc/sysctl.conf#: [source,bash] .... # echo "net.inet.ip.fw.verbose_limit=5" >> /etc/sysctl.conf .... To enable logging through a dedicated interface named `ipfw0`, add this line to [.filename]#/etc/rc.conf# instead: [source,bash] .... # sysrc firewall_logif="YES" .... Then use tcpdump to see what is being logged: [source,bash] .... # tcpdump -t -n -i ipfw0 .... [TIP] ==== There is no overhead due to logging unless tcpdump is attached. ==== After saving the needed edits, start the firewall. To enable logging limits now, also set the `sysctl` value specified above: [source,bash] .... # service ipfw start # sysctl net.inet.ip.fw.verbose_limit=5 .... [[firewalls-ipfw-rules]] === IPFW Rule Syntax When a packet enters the IPFW firewall, it is compared against the first rule in the ruleset and progresses one rule at a time, moving from top to bottom in sequence. When the packet matches the selection parameters of a rule, the rule's action is executed and the search of the ruleset terminates for that packet. This is referred to as "first match wins". If the packet does not match any of the rules, it gets caught by the mandatory IPFW default rule number 65535, which denies all packets and silently discards them. However, if the packet matches a rule that contains the `count`, `skipto`, or `tee` keywords, the search continues. Refer to man:ipfw[8] for details on how these keywords affect rule processing. When creating an IPFW rule, keywords must be written in the following order. Some keywords are mandatory while other keywords are optional. The words shown in uppercase represent a variable and the words shown in lowercase must precede the variable that follows it. The `#` symbol is used to mark the start of a comment and may appear at the end of a rule or on its own line. Blank lines are ignored. `_CMD RULE_NUMBER set SET_NUMBER ACTION log LOG_AMOUNT PROTO from SRC SRC_PORT to DST DST_PORT OPTIONS_` This section provides an overview of these keywords and their options. It is not an exhaustive list of every possible option. Refer to man:ipfw[8] for a complete description of the rule syntax that can be used when creating IPFW rules. CMD:: Every rule must start with `ipfw add`. RULE_NUMBER:: Each rule is associated with a number from `1` to `65534`. The number is used to indicate the order of rule processing. Multiple rules can have the same number, in which case they are applied according to the order in which they have been added. SET_NUMBER:: Each rule is associated with a set number from `0` to `31`. Sets can be individually disabled or enabled, making it possible to quickly add or delete a set of rules. If a SET_NUMBER is not specified, the rule will be added to set `0`. ACTION:: A rule can be associated with one of the following actions. The specified action will be executed when the packet matches the selection criterion of the rule. + `allow | accept | pass | permit`: these keywords are equivalent and allow packets that match the rule. + `check-state`: checks the packet against the dynamic state table. If a match is found, execute the action associated with the rule which generated this dynamic rule, otherwise move to the next rule. A `check-state` rule does not have selection criterion. If no `check-state` rule is present in the ruleset, the dynamic rules table is checked at the first `keep-state` or `limit` rule. + `count`: updates counters for all packets that match the rule. The search continues with the next rule. + `deny | drop`: either word silently discards packets that match this rule. + Additional actions are available. Refer to man:ipfw[8] for details. LOG_AMOUNT:: When a packet matches a rule with the `log` keyword, a message will be logged to man:syslogd[8] with a facility name of `SECURITY`. Logging only occurs if the number of packets logged for that particular rule does not exceed a specified LOG_AMOUNT. If no LOG_AMOUNT is specified, the limit is taken from the value of `net.inet.ip.fw.verbose_limit`. A value of zero removes the logging limit. Once the limit is reached, logging can be re-enabled by clearing the logging counter or the packet counter for that rule, using `ipfw resetlog`. + [NOTE] ==== Logging is done after all other packet matching conditions have been met, and before performing the final action on the packet. The administrator decides which rules to enable logging on. ==== PROTO:: This optional value can be used to specify any protocol name or number found in [.filename]#/etc/protocols#. SRC:: The `from` keyword must be followed by the source address or a keyword that represents the source address. An address can be represented by `any`, `me` (any address configured on an interface on this system), `me6`, (any IPv6 address configured on an interface on this system), or `table` followed by the number of a lookup table which contains a list of addresses. When specifying an IP address, it can be optionally followed by its CIDR mask or subnet mask. For example, `1.2.3.4/25` or `1.2.3.4:255.255.255.128`. SRC_PORT:: An optional source port can be specified using the port number or name from [.filename]#/etc/services#. DST:: The `to` keyword must be followed by the destination address or a keyword that represents the destination address. The same keywords and addresses described in the SRC section can be used to describe the destination. DST_PORT:: An optional destination port can be specified using the port number or name from [.filename]#/etc/services#. OPTIONS:: Several keywords can follow the source and destination. As the name suggests, OPTIONS are optional. Commonly used options include `in` or `out`, which specify the direction of packet flow, `icmptypes` followed by the type of ICMP message, and `keep-state`. + When a `keep-state` rule is matched, the firewall will create a dynamic rule which matches bidirectional traffic between the source and destination addresses and ports using the same protocol. + The dynamic rules facility is vulnerable to resource depletion from a SYN-flood attack which would open a huge number of dynamic rules. To counter this type of attack with IPFW, use `limit`. This option limits the number of simultaneous sessions by checking the open dynamic rules, counting the number of times this rule and IP address combination occurred. If this count is greater than the value specified by `limit`, the packet is discarded. + Dozens of OPTIONS are available. Refer to man:ipfw[8] for a description of each available option. === Example Ruleset This section demonstrates how to create an example stateful firewall ruleset script named [.filename]#/etc/ipfw.rules#. In this example, all connection rules use `in` or `out` to clarify the direction. They also use `via` _interface-name_ to specify the interface the packet is traveling over. [NOTE] ==== When first creating or testing a firewall ruleset, consider temporarily setting this tunable: [.programlisting] .... net.inet.ip.fw.default_to_accept="1" .... This sets the default policy of man:ipfw[8] to be more permissive than the default `deny ip from any to any`, making it slightly more difficult to get locked out of the system right after a reboot. ==== The firewall script begins by indicating that it is a Bourne shell script and flushes any existing rules. It then creates the `cmd` variable so that `ipfw add` does not have to be typed at the beginning of every rule. It also defines the `pif` variable which represents the name of the interface that is attached to the Internet. [.programlisting] .... #!/bin/sh # Flush out the list before we begin. ipfw -q -f flush # Set rules command prefix cmd="ipfw -q add" pif="dc0" # interface name of NIC attached to Internet .... The first two rules allow all traffic on the trusted internal interface and on the loopback interface: [.programlisting] .... # Change xl0 to LAN NIC interface name $cmd 00005 allow all from any to any via xl0 # No restrictions on Loopback Interface $cmd 00010 allow all from any to any via lo0 .... The next rule allows the packet through if it matches an existing entry in the dynamic rules table: [.programlisting] .... $cmd 00101 check-state .... The next set of rules defines which stateful connections internal systems can create to hosts on the Internet: [.programlisting] .... # Allow access to public DNS # Replace x.x.x.x with the IP address of a public DNS server # and repeat for each DNS server in /etc/resolv.conf $cmd 00110 allow tcp from any to x.x.x.x 53 out via $pif setup keep-state $cmd 00111 allow udp from any to x.x.x.x 53 out via $pif keep-state # Allow access to ISP's DHCP server for cable/DSL configurations. # Use the first rule and check log for IP address. # Then, uncomment the second rule, input the IP address, and delete the first rule $cmd 00120 allow log udp from any to any 67 out via $pif keep-state #$cmd 00120 allow udp from any to x.x.x.x 67 out via $pif keep-state # Allow outbound HTTP and HTTPS connections $cmd 00200 allow tcp from any to any 80 out via $pif setup keep-state $cmd 00220 allow tcp from any to any 443 out via $pif setup keep-state # Allow outbound email connections $cmd 00230 allow tcp from any to any 25 out via $pif setup keep-state $cmd 00231 allow tcp from any to any 110 out via $pif setup keep-state # Allow outbound ping $cmd 00250 allow icmp from any to any out via $pif keep-state # Allow outbound NTP $cmd 00260 allow udp from any to any 123 out via $pif keep-state # Allow outbound SSH $cmd 00280 allow tcp from any to any 22 out via $pif setup keep-state # deny and log all other outbound connections $cmd 00299 deny log all from any to any out via $pif .... The next set of rules controls connections from Internet hosts to the internal network. It starts by denying packets typically associated with attacks and then explicitly allows specific types of connections. All the authorized services that originate from the Internet use `limit` to prevent flooding. [.programlisting] .... # Deny all inbound traffic from non-routable reserved address spaces $cmd 00300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 00301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 00302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 00303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 00304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 00305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 00306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 00307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster interconnect $cmd 00308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Deny public pings $cmd 00310 deny icmp from any to any in via $pif # Deny ident $cmd 00315 deny tcp from any to any 113 in via $pif # Deny all Netbios services. $cmd 00320 deny tcp from any to any 137 in via $pif $cmd 00321 deny tcp from any to any 138 in via $pif $cmd 00322 deny tcp from any to any 139 in via $pif $cmd 00323 deny tcp from any to any 81 in via $pif # Deny fragments $cmd 00330 deny all from any to any frag in via $pif # Deny ACK packets that did not match the dynamic rule table $cmd 00332 deny tcp from any to any established in via $pif # Allow traffic from ISP's DHCP server. # Replace x.x.x.x with the same IP address used in rule 00120. #$cmd 00360 allow udp from any to x.x.x.x 67 in via $pif keep-state # Allow HTTP connections to internal web server $cmd 00400 allow tcp from any to me 80 in via $pif setup limit src-addr 2 # Allow inbound SSH connections $cmd 00410 allow tcp from any to me 22 in via $pif setup limit src-addr 2 # Reject and log all other incoming connections $cmd 00499 deny log all from any to any in via $pif .... The last rule logs all packets that do not match any of the rules in the ruleset: [.programlisting] .... # Everything else is denied and logged $cmd 00999 deny log all from any to any .... [[in-kernel-nat]] === In-kernel NAT FreeBSD's IPFW firewall has two implementations of NAT: the userland implementation man:natd[8], and the more recent in-kernel NAT implementation. Both work in conjunction with IPFW to provide network address translation. This can be used to provide an Internet Connection Sharing solution so that several internal computers can connect to the Internet using a single public IP address. To do this, the FreeBSD machine connected to the Internet must act as a gateway. This system must have two NICs, where one is connected to the Internet and the other is connected to the internal LAN. Each machine connected to the LAN should be assigned an IP address in the private network space, as defined by https://www.ietf.org/rfc/rfc1918.txt[RFC 1918]. Some additional configuration is needed in order to enable the in-kernel NAT facility of IPFW. To enable in-kernel NAT support at boot time, the following must be set in [.filename]#/etc/rc.conf#: [.programlisting] .... gateway_enable="YES" firewall_enable="YES" firewall_nat_enable="YES" .... [NOTE] ==== When `firewall_nat_enable` is set but `firewall_enable` is not, it will have no effect and do nothing. This is because the in-kernel NAT implementation is only compatible with IPFW. ==== When the ruleset contains stateful rules, the positioning of the NAT rule is critical and the `skipto` action is used. The `skipto` action requires a rule number so that it knows which rule to jump to. The example below builds upon the firewall ruleset shown in the previous section. It adds some additional entries and modifies some existing rules in order to configure the firewall for in-kernel NAT. It starts by adding some additional variables which represent the rule number to skip to, the `keep-state` option, and a list of TCP ports which will be used to reduce the number of rules. [.programlisting] .... #!/bin/sh ipfw -q -f flush cmd="ipfw -q add" skip="skipto 1000" pif=dc0 ks="keep-state" good_tcpo="22,25,37,53,80,443,110" .... With in-kernel NAT it is necessary to disable TCP segmentation offloading (TSO) due to the architecture of man:libalias[3], a library implemented as a kernel module to provide the in-kernel NAT facility of IPFW. TSO can be disabled on a per network interface basis using man:ifconfig[8] or on a system wide basis using man:sysctl[8]. To disable TSO system wide, the following must be set it [.filename]#/etc/sysctl.conf#: [.programlisting] .... net.inet.tcp.tso="0" .... A NAT instance will also be configured. It is possible to have multiple NAT instances each with their own configuration. For this example only one NAT instance is needed, NAT instance number 1. The configuration can take a few options such as: `if` which indicates the public interface, `same_ports` which takes care that alliased ports and local port numbers are mapped the same, `unreg_only` will result in only unregistered (private) address spaces to be processed by the NAT instance, and `reset` which will help to keep a functioning NAT instance even when the public IP address of the IPFW machine changes. For all possible options that can be passed to a single NAT instance configuration consult man:ipfw[8]. When configuring a stateful NATing firewall, it is necessary to allow translated packets to be reinjected in the firewall for further processing. This can be achieved by disabling `one_pass` behavior at the start of the firewall script. [.programlisting] .... ipfw disable one_pass ipfw -q nat 1 config if $pif same_ports unreg_only reset .... The inbound NAT rule is inserted _after_ the two rules which allow all traffic on the trusted and loopback interfaces and after the reassemble rule but _before_ the `check-state` rule. It is important that the rule number selected for this NAT rule, in this example `100`, is higher than the first three rules and lower than the `check-state` rule. Furthermore, because of the behavior of in-kernel NAT it is advised to place a reassemble rule just before the first NAT rule and after the rules that allow traffic on trusted interface. Normally, IP fragmentation should not happen, but when dealing with IPSEC/ESP/GRE tunneling traffic it might and the reassembling of fragments is necessary before handing the complete packet over to the in-kernel NAT facility. [NOTE] ==== The reassemble rule was not needed with userland man:natd[8] because the internal workings of the IPFW `divert` action already takes care of reassembling packets before delivery to the socket as also stated in man:ipfw[8]. The NAT instance and rule number used in this example does not match with the default NAT instance and rule number created by [.filename]#rc.firewall#. [.filename]#rc.firewall# is a script that sets up the default firewall rules present in FreeBSD. ==== [.programlisting] .... $cmd 005 allow all from any to any via xl0 # exclude LAN traffic $cmd 010 allow all from any to any via lo0 # exclude loopback traffic $cmd 099 reass all from any to any in # reassemble inbound packets $cmd 100 nat 1 ip from any to any in via $pif # NAT any inbound packets # Allow the packet through if it has an existing entry in the dynamic rules table $cmd 101 check-state .... The outbound rules are modified to replace the `allow` action with the `$skip` variable, indicating that rule processing will continue at rule `1000`. The seven `tcp` rules have been replaced by rule `125` as the `$good_tcpo` variable contains the seven allowed outbound ports. [NOTE] ==== Remember that IPFW's performance is largely determined by the number of rules present in the ruleset. ==== [.programlisting] .... # Authorized outbound packets $cmd 120 $skip udp from any to x.x.x.x 53 out via $pif $ks $cmd 121 $skip udp from any to x.x.x.x 67 out via $pif $ks $cmd 125 $skip tcp from any to any $good_tcpo out via $pif setup $ks $cmd 130 $skip icmp from any to any out via $pif $ks .... The inbound rules remain the same, except for the very last rule which removes the `via $pif` in order to catch both inbound and outbound rules. The NAT rule must follow this last outbound rule, must have a higher number than that last rule, and the rule number must be referenced by the `skipto` action. In this ruleset, rule number `1000` handles passing all packets to our configured instance for NAT processing. The next rule allows any packet which has undergone NAT processing to pass. [.programlisting] .... $cmd 999 deny log all from any to any $cmd 1000 nat 1 ip from any to any out via $pif # skipto location for outbound stateful rules $cmd 1001 allow ip from any to any .... In this example, rules `100`, `101`, `125`, `1000`, and `1001` control the address translation of the outbound and inbound packets so that the entries in the dynamic state table always register the private LANIP address. Consider an internal web browser which initializes a new outbound HTTP session over port 80. When the first outbound packet enters the firewall, it does not match rule `100` because it is headed out rather than in. It passes rule `101` because this is the first packet and it has not been posted to the dynamic state table yet. The packet finally matches rule `125` as it is outbound on an allowed port and has a source IP address from the internal LAN. On matching this rule, two actions take place. First, the `keep-state` action adds an entry to the dynamic state table and the specified action, `skipto rule 1000`, is executed. Next, the packet undergoes NAT and is sent out to the Internet. This packet makes its way to the destination web server, where a response packet is generated and sent back. This new packet enters the top of the ruleset. It matches rule `100` and has its destination IP address mapped back to the original internal address. It then is processed by the `check-state` rule, is found in the table as an existing session, and is released to the LAN. On the inbound side, the ruleset has to deny bad packets and allow only authorized services. A packet which matches an inbound rule is posted to the dynamic state table and the packet is released to the LAN. The packet generated as a response is recognized by the `check-state` rule as belonging to an existing session. It is then sent to rule `1000` to undergo NAT before being released to the outbound interface. [NOTE] ==== Transitioning from userland man:natd[8] to in-kernel NAT might seem seamless at first but there is small catch. When using the GENERIC kernel, IPFW will load the [.filename]#libalias.ko# kernel module, when `firewall_nat_enable` is enabled in [.filename]#rc.conf#. The [.filename]#libalias.ko# kernel module only provides basic NAT functionality, whereas the userland implementation man:natd[8] has all NAT functionality available in its userland library without any extra configuration. All functionality refers to the following kernel modules that can additionally be loaded when needed besides the standard [.filename]#libalias.ko# kernel module: [.filename]#alias_cuseeme.ko#, [.filename]#alias_ftp.ko#, [.filename]#alias_bbt.ko#, [.filename]#skinny.ko#, [.filename]#irc.ko#, [.filename]#alias_pptp.ko# and [.filename]#alias_smedia.ko# using the `kld_list` directive in [.filename]#rc.conf#. If a custom kernel is used, the full functionality of the userland library can be compiled in, in the kernel, using the `options LIBALIAS`. ==== ==== Port Redirection The drawback with NAT in general is that the LAN clients are not accessible from the Internet. Clients on the LAN can make outgoing connections to the world but cannot receive incoming ones. This presents a problem if trying to run Internet services on one of the LAN client machines. A simple way around this is to redirect selected Internet ports on the NAT providing machine to a LAN client. For example, an IRC server runs on client `A` and a web server runs on client `B`. For this to work properly, connections received on ports 6667 (IRC) and 80 (HTTP) must be redirected to the respective machines. With in-kernel NAT all configuration is done in the NAT instance configuration. For a full list of options that an in-kernel NAT instance can use, consult man:ipfw[8]. The IPFW syntax follows the syntax of natd. The syntax for `redirect_port` is as follows: [.programlisting] .... redirect_port proto targetIP:targetPORT[-targetPORT] [aliasIP:]aliasPORT[-aliasPORT] [remoteIP[:remotePORT[-remotePORT]]] .... To configure the above example setup, the arguments should be: [.programlisting] .... redirect_port tcp 192.168.0.2:6667 6667 redirect_port tcp 192.168.0.3:80 80 .... After adding these arguments to the configuration of NAT instance 1 in the above ruleset, the TCP ports will be port forwarded to the LAN client machines running the IRC and HTTP services. [.programlisting] .... ipfw -q nat 1 config if $pif same_ports unreg_only reset \ redirect_port tcp 192.168.0.2:6667 6667 \ redirect_port tcp 192.168.0.3:80 80 .... Port ranges over individual ports can be indicated with `redirect_port`. For example, _tcp 192.168.0.2:2000-3000 2000-3000_ would redirect all connections received on ports 2000 to 3000 to ports 2000 to 3000 on client `A`. ==== Address Redirection Address redirection is useful if more than one IP address is available. Each LAN client can be assigned its own external IP address by man:ipfw[8], which will then rewrite outgoing packets from the LAN clients with the proper external IP address and redirects all traffic incoming on that particular IP address back to the specific LAN client. This is also known as static NAT. For example, if IP addresses `128.1.1.1`, `128.1.1.2`, and `128.1.1.3` are available, `128.1.1.1` can be used as the man:ipfw[8] machine's external IP address, while `128.1.1.2` and `128.1.1.3` are forwarded back to LAN clients `A` and `B`. The `redirect_address` syntax is as below, where `localIP` is the internal IP address of the LAN client, and `publicIP` the external IP address corresponding to the LAN client. [.programlisting] .... redirect_address localIP publicIP .... In the example, the arguments would read: [.programlisting] .... redirect_address 192.168.0.2 128.1.1.2 redirect_address 192.168.0.3 128.1.1.3 .... Like `redirect_port`, these arguments are placed in a NAT instance configuration. With address redirection, there is no need for port redirection, as all data received on a particular IP address is redirected. The external IP addresses on the man:ipfw[8] machine must be active and aliased to the external interface. Refer to man:rc.conf[5] for details. ==== Userspace NAT Let us start with a statement: the userspace NAT implementation: man:natd[8], has more overhead than in-kernel NAT. For man:natd[8] to translate packets, the packets have to be copied from the kernel to userspace and back which brings in extra overhead that is not present with in-kernel NAT. To enable the userpace NAT daemon man:natd[8] at boot time, the following is a minimum configuration in [.filename]#/etc/rc.conf#. Where `natd_interface` is set to the name of the NIC attached to the Internet. The man:rc[8] script of man:natd[8] will automatically check if a dynamic IP address is used and configure itself to handle that. [.programlisting] .... gateway_enable="YES" natd_enable="YES" natd_interface="rl0" .... In general, the above ruleset as explained for in-kernel NAT can also be used together with man:natd[8]. The exceptions are the configuration of the in-kernel NAT instance `(ipfw -q nat 1 config ...)` which is not needed together with reassemble rule 99 because its functionality is included in the `divert` action. Rule number 100 and 1000 will have to change sligthly as shown below. [.programlisting] .... $cmd 100 divert natd ip from any to any in via $pif $cmd 1000 divert natd ip from any to any out via $pif .... To configure port or address redirection, a similar syntax as with in-kernel NAT is used. Although, now, instead of specifying the configuration in our ruleset script like with in-kernel NAT, configuration of man:natd[8] is best done in a configuration file. To do this, an extra flag must be passed via [.filename]#/etc/rc.conf# which specifies the path of the configuration file. [.programlisting] .... natd_flags="-f /etc/natd.conf" .... [NOTE] ==== The specified file must contain a list of configuration options, one per line. For more information about the configuration file and possible variables, consult man:natd[8]. Below are two example entries, one per line: [.programlisting] .... redirect_port tcp 192.168.0.2:6667 6667 redirect_address 192.168.0.3 128.1.1.3 .... ==== [[firewalls-ipfw-cmd]] === The IPFW Command `ipfw` can be used to make manual, single rule additions or deletions to the active firewall while it is running. The problem with using this method is that all the changes are lost when the system reboots. It is recommended to instead write all the rules in a file and to use that file to load the rules at boot time and to replace the currently running firewall rules whenever that file changes. `ipfw` is a useful way to display the running firewall rules to the console screen. The IPFW accounting facility dynamically creates a counter for each rule that counts each packet that matches the rule. During the process of testing a rule, listing the rule with its counter is one way to determine if the rule is functioning as expected. To list all the running rules in sequence: [source,bash] .... # ipfw list .... To list all the running rules with a time stamp of when the last time the rule was matched: [source,bash] .... # ipfw -t list .... The next example lists accounting information and the packet count for matched rules along with the rules themselves. The first column is the rule number, followed by the number of matched packets and bytes, followed by the rule itself. [source,bash] .... # ipfw -a list .... To list dynamic rules in addition to static rules: [source,bash] .... # ipfw -d list .... To also show the expired dynamic rules: [source,bash] .... # ipfw -d -e list .... To zero the counters: [source,bash] .... # ipfw zero .... To zero the counters for just the rule with number _NUM_: [source,bash] .... # ipfw zero NUM .... ==== Logging Firewall Messages Even with the logging facility enabled, IPFW will not generate any rule logging on its own. The firewall administrator decides which rules in the ruleset will be logged, and adds the `log` keyword to those rules. Normally only deny rules are logged. It is customary to duplicate the "ipfw default deny everything" rule with the `log` keyword included as the last rule in the ruleset. This way, it is possible to see all the packets that did not match any of the rules in the ruleset. Logging is a two edged sword. If one is not careful, an over abundance of log data or a DoS attack can fill the disk with log files. Log messages are not only written to syslogd, but also are displayed on the root console screen and soon become annoying. The `IPFIREWALL_VERBOSE_LIMIT=5` kernel option limits the number of consecutive messages sent to man:syslogd[8], concerning the packet matching of a given rule. When this option is enabled in the kernel, the number of consecutive messages concerning a particular rule is capped at the number specified. There is nothing to be gained from 200 identical log messages. With this option set to five, five consecutive messages concerning a particular rule would be logged to syslogd and the remainder identical consecutive messages would be counted and posted to syslogd with a phrase like the following: [.programlisting] .... last message repeated 45 times .... All logged packets messages are written by default to [.filename]#/var/log/security#, which is defined in [.filename]#/etc/syslog.conf#. [[firewalls-ipfw-rules-script]] ==== Building a Rule Script Most experienced IPFW users create a file containing the rules and code them in a manner compatible with running them as a script. The major benefit of doing this is the firewall rules can be refreshed in mass without the need of rebooting the system to activate them. This method is convenient in testing new rules as the procedure can be executed as many times as needed. Being a script, symbolic substitution can be used for frequently used values to be substituted into multiple rules. This example script is compatible with the syntax used by the man:sh[1], man:csh[1], and man:tcsh[1] shells. Symbolic substitution fields are prefixed with a dollar sign ($). Symbolic fields do not have the $ prefix. The value to populate the symbolic field must be enclosed in double quotes (""). Start the rules file like this: [.programlisting] .... ############### start of example ipfw rules script ############# # ipfw -q -f flush # Delete all rules # Set defaults oif="tun0" # out interface odns="192.0.2.11" # ISP's DNS server IP address cmd="ipfw -q add " # build rule prefix ks="keep-state" # just too lazy to key this each time $cmd 00500 check-state $cmd 00502 deny all from any to any frag $cmd 00501 deny tcp from any to any established $cmd 00600 allow tcp from any to any 80 out via $oif setup $ks $cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks $cmd 00611 allow udp from any to $odns 53 out via $oif $ks ################### End of example ipfw rules script ############ .... The rules are not important as the focus of this example is how the symbolic substitution fields are populated. If the above example was in [.filename]#/etc/ipfw.rules#, the rules could be reloaded by the following command: [source,bash] .... # sh /etc/ipfw.rules .... [.filename]#/etc/ipfw.rules# can be located anywhere and the file can have any name. The same thing could be accomplished by running these commands by hand: [source,bash] .... # ipfw -q -f flush # ipfw -q add check-state # ipfw -q add deny all from any to any frag # ipfw -q add deny tcp from any to any established # ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state # ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state # ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state .... [[firewalls-ipfw-kernelconfig]] === IPFW Kernel Options In order to statically compile IPFW support into a custom kernel, refer to the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. The following options are available for the custom kernel configuration file: [.programlisting] .... options IPFIREWALL # enables IPFW options IPFIREWALL_VERBOSE # enables logging for rules with log keyword to syslogd(8) options IPFIREWALL_VERBOSE_LIMIT=5 # limits number of logged packets per-entry options IPFIREWALL_DEFAULT_TO_ACCEPT # sets default policy to pass what is not explicitly denied options IPFIREWALL_NAT # enables basic in-kernel NAT support options LIBALIAS # enables full in-kernel NAT support options IPFIREWALL_NAT64 # enables in-kernel NAT64 support options IPFIREWALL_NPTV6 # enables in-kernel IPv6 NPT support options IPFIREWALL_PMOD # enables protocols modification module support options IPDIVERT # enables NAT through natd(8) .... [NOTE] ==== IPFW can be loaded as a kernel module: options above are built by default as modules or can be set at runtime using tunables. ==== [[firewalls-ipf]] == IPFILTER (IPF) IPFILTER, also known as IPF, is a cross-platform, open source firewall which has been ported to several operating systems, including FreeBSD, NetBSD, OpenBSD, and Solaris(TM). IPFILTER is a kernel-side firewall and NAT mechanism that can be controlled and monitored by userland programs. Firewall rules can be set or deleted using ipf, NAT rules can be set or deleted using ipnat, run-time statistics for the kernel parts of IPFILTER can be printed using ipfstat, and ipmon can be used to log IPFILTER actions to the system log files. IPF was originally written using a rule processing logic of "the last matching rule wins" and only used stateless rules. Since then, IPF has been enhanced to include the `quick` and `keep state` options. The IPF FAQ is at http://www.phildev.net/ipf/index.html[http://www.phildev.net/ipf/index.html]. A searchable archive of the IPFilter mailing list is available at http://marc.info/?l=ipfilter[http://marc.info/?l=ipfilter]. This section of the Handbook focuses on IPF as it pertains to FreeBSD. It provides examples of rules that contain the `quick` and `keep state` options. === Enabling IPF IPF is included in the basic FreeBSD install as a kernel loadable module, meaning that a custom kernel is not needed in order to enable IPF. For users who prefer to statically compile IPF support into a custom kernel, refer to the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. The following kernel options are available: [.programlisting] .... options IPFILTER options IPFILTER_LOG options IPFILTER_LOOKUP options IPFILTER_DEFAULT_BLOCK .... where `options IPFILTER` enables support for IPFILTER, `options IPFILTER_LOG` enables IPF logging using the [.filename]#ipl# packet logging pseudo-device for every rule that has the `log` keyword, `IPFILTER_LOOKUP` enables IP pools in order to speed up IP lookups, and `options IPFILTER_DEFAULT_BLOCK` changes the default behavior so that any packet not matching a firewall `pass` rule gets blocked. To configure the system to enable IPF at boot time, add the following entries to [.filename]#/etc/rc.conf#. These entries will also enable logging and `default pass all`. To change the default policy to `block all` without compiling a custom kernel, remember to add a `block all` rule at the end of the ruleset. [.programlisting] .... ipfilter_enable="YES" # Start ipf firewall ipfilter_rules="/etc/ipf.rules" # loads rules definition text file ipv6_ipfilter_rules="/etc/ipf6.rules" # loads rules definition text file for IPv6 ipmon_enable="YES" # Start IP monitor log ipmon_flags="-Ds" # D = start as daemon # s = log to syslog # v = log tcp window, ack, seq # n = map IP & port to names .... If NAT functionality is needed, also add these lines: [.programlisting] .... gateway_enable="YES" # Enable as LAN gateway ipnat_enable="YES" # Start ipnat function ipnat_rules="/etc/ipnat.rules" # rules definition file for ipnat .... Then, to start IPF now: [.programlisting] .... # service ipfilter start .... To load the firewall rules, specify the name of the ruleset file using `ipf`. The following command can be used to replace the currently running firewall rules: [source,bash] .... # ipf -Fa -f /etc/ipf.rules .... where `-Fa` flushes all the internal rules tables and `-f` specifies the file containing the rules to load. This provides the ability to make changes to a custom ruleset and update the running firewall with a fresh copy of the rules without having to reboot the system. This method is convenient for testing new rules as the procedure can be executed as many times as needed. Refer to man:ipf[8] for details on the other flags available with this command. === IPF Rule Syntax -This section describes the IPF rule syntax used to create stateful rules. When creating rules, keep in mind that unless the `quick` keyword appears in a rule, every rule is read in order, with the _last matching rule_ being the one that is applied. This means that even if the first rule to match a packet is a `pass`, if there is a later matching rule that is a `block`, the packet will be dropped. Sample rulesets can be found in [.filename]#/usr/shared/examples/ipfilter#. +This section describes the IPF rule syntax used to create stateful rules. When creating rules, keep in mind that unless the `quick` keyword appears in a rule, every rule is read in order, with the _last matching rule_ being the one that is applied. This means that even if the first rule to match a packet is a `pass`, if there is a later matching rule that is a `block`, the packet will be dropped. Sample rulesets can be found in [.filename]#/usr/share/examples/ipfilter#. When creating rules, a `#` character is used to mark the start of a comment and may appear at the end of a rule, to explain that rule's function, or on its own line. Any blank lines are ignored. The keywords which are used in rules must be written in a specific order, from left to right. Some keywords are mandatory while others are optional. Some keywords have sub-options which may be keywords themselves and also include more sub-options. The keyword order is as follows, where the words shown in uppercase represent a variable and the words shown in lowercase must precede the variable that follows it: `_ACTION DIRECTION OPTIONS proto PROTO_TYPE from SRC_ADDR SRC_PORT to DST_ADDR DST_PORT TCP_FLAG|ICMP_TYPE keep state STATE_` This section describes each of these keywords and their options. It is not an exhaustive list of every possible option. Refer to man:ipf[5] for a complete description of the rule syntax that can be used when creating IPF rules and examples for using each keyword. ACTION:: The action keyword indicates what to do with the packet if it matches that rule. Every rule _must_ have an action. The following actions are recognized: + `block`: drops the packet. + `pass`: allows the packet. + `log`: generates a log record. + `count`: counts the number of packets and bytes which can provide an indication of how often a rule is used. + `auth`: queues the packet for further processing by another program. + `call`: provides access to functions built into IPF that allow more complex actions. + `decapsulate`: removes any headers in order to process the contents of the packet. DIRECTION:: Next, each rule must explicitly state the direction of traffic using one of these keywords: + `in`: the rule is applied against an inbound packet. + `out`: the rule is applied against an outbound packet. + `all`: the rule applies to either direction. + If the system has multiple interfaces, the interface can be specified along with the direction. An example would be `in on fxp0`. OPTIONS:: Options are optional. However, if multiple options are specified, they must be used in the order shown here. + `log`: when performing the specified ACTION, the contents of the packet's headers will be written to the man:ipl[4] packet log pseudo-device. + `quick`: if a packet matches this rule, the ACTION specified by the rule occurs and no further processing of any following rules will occur for this packet. + `on`: must be followed by the interface name as displayed by man:ifconfig[8]. The rule will only match if the packet is going through the specified interface in the specified direction. + When using the `log` keyword, the following qualifiers may be used in this order: + `body`: indicates that the first 128 bytes of the packet contents will be logged after the headers. + `first`: if the `log` keyword is being used in conjunction with a `keep state` option, this option is recommended so that only the triggering packet is logged and not every packet which matches the stateful connection. + Additional options are available to specify error return messages. Refer to man:ipf[5] for more details. PROTO_TYPE:: The protocol type is optional. However, it is mandatory if the rule needs to specify a SRC_PORT or a DST_PORT as it defines the type of protocol. When specifying the type of protocol, use the `proto` keyword followed by either a protocol number or name from [.filename]#/etc/protocols#. Example protocol names include `tcp`, `udp`, or `icmp`. If PROTO_TYPE is specified but no SRC_PORT or DST_PORT is specified, all port numbers for that protocol will match that rule. SRC_ADDR:: The `from` keyword is mandatory and is followed by a keyword which represents the source of the packet. The source can be a hostname, an IP address followed by the CIDR mask, an address pool, or the keyword `all`. Refer to man:ipf[5] for examples. + There is no way to match ranges of IP addresses which do not express themselves easily using the dotted numeric form / mask-length notation. The package:net-mgmt/ipcalc[] package or port may be used to ease the calculation of the CIDR mask. Additional information is available at the utility's web page: http://jodies.de/ipcalc[http://jodies.de/ipcalc]. SRC_PORT:: The port number of the source is optional. However, if it is used, it requires PROTO_TYPE to be first defined in the rule. The port number must also be preceded by the `proto` keyword. + A number of different comparison operators are supported: `=` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than or equal to), and `>=` (greater than or equal to). + To specify port ranges, place the two port numbers between `<>` (less than and greater than ), `><` (greater than and less than ), or `:` (greater than or equal to and less than or equal to). DST_ADDR:: The `to` keyword is mandatory and is followed by a keyword which represents the destination of the packet. Similar to SRC_ADDR, it can be a hostname, an IP address followed by the CIDR mask, an address pool, or the keyword `all`. DST_PORT:: Similar to SRC_PORT, the port number of the destination is optional. However, if it is used, it requires PROTO_TYPE to be first defined in the rule. The port number must also be preceded by the `proto` keyword. TCP_FLAG|ICMP_TYPE:: If `tcp` is specified as the PROTO_TYPE, flags can be specified as letters, where each letter represents one of the possible TCP flags used to determine the state of a connection. Possible values are: `S` (SYN), `A` (ACK), `P` (PSH), `F` (FIN), `U` (URG), `R` (RST), `C` (CWN), and `E` (ECN). + If `icmp` is specified as the PROTO_TYPE, the ICMP type to match can be specified. Refer to man:ipf[5] for the allowable types. STATE:: If a `pass` rule contains `keep state`, IPF will add an entry to its dynamic state table and allow subsequent packets that match the connection. IPF can track state for TCP, UDP, and ICMP sessions. Any packet that IPF can be certain is part of an active session, even if it is a different protocol, will be allowed. + In IPF, packets destined to go out through the interface connected to the public Internet are first checked against the dynamic state table. If the packet matches the next expected packet comprising an active session conversation, it exits the firewall and the state of the session conversation flow is updated in the dynamic state table. Packets that do not belong to an already active session are checked against the outbound ruleset. Packets coming in from the interface connected to the public Internet are first checked against the dynamic state table. If the packet matches the next expected packet comprising an active session, it exits the firewall and the state of the session conversation flow is updated in the dynamic state table. Packets that do not belong to an already active session are checked against the inbound ruleset. + Several keywords can be added after `keep state`. If used, these keywords set various options that control stateful filtering, such as setting connection limits or connection age. Refer to man:ipf[5] for the list of available options and their descriptions. === Example Ruleset This section demonstrates how to create an example ruleset which only allows services matching `pass` rules and blocks all others. FreeBSD uses the loopback interface ([.filename]#lo0#) and the IP address `127.0.0.1` for internal communication. The firewall ruleset must contain rules to allow free movement of these internally used packets: [.programlisting] .... # no restrictions on loopback interface pass in quick on lo0 all pass out quick on lo0 all .... The public interface connected to the Internet is used to authorize and control access of all outbound and inbound connections. If one or more interfaces are cabled to private networks, those internal interfaces may require rules to allow packets originating from the LAN to flow between the internal networks or to the interface attached to the Internet. The ruleset should be organized into three major sections: any trusted internal interfaces, outbound connections through the public interface, and inbound connections through the public interface. These two rules allow all traffic to pass through a trusted LAN interface named [.filename]#xl0#: [.programlisting] .... # no restrictions on inside LAN interface for private network pass out quick on xl0 all pass in quick on xl0 all .... The rules for the public interface's outbound and inbound sections should have the most frequently matched rules placed before less commonly matched rules, with the last rule in the section blocking and logging all packets for that interface and direction. This set of rules defines the outbound section of the public interface named [.filename]#dc0#. These rules keep state and identify the specific services that internal systems are authorized for public Internet access. All the rules use `quick` and specify the appropriate port numbers and, where applicable, destination addresses. [.programlisting] .... # interface facing Internet (outbound) # Matches session start requests originating from or behind the # firewall, destined for the Internet. # Allow outbound access to public DNS servers. # Replace x.x.x. with address listed in /etc/resolv.conf. # Repeat for each DNS server. pass out quick on dc0 proto tcp from any to x.x.x. port = 53 flags S keep state pass out quick on dc0 proto udp from any to xxx port = 53 keep state # Allow access to ISP's specified DHCP server for cable or DSL networks. # Use the first rule, then check log for the IP address of DHCP server. # Then, uncomment the second rule, replace z.z.z.z with the IP address, # and comment out the first rule pass out log quick on dc0 proto udp from any to any port = 67 keep state #pass out quick on dc0 proto udp from any to z.z.z.z port = 67 keep state # Allow HTTP and HTTPS pass out quick on dc0 proto tcp from any to any port = 80 flags S keep state pass out quick on dc0 proto tcp from any to any port = 443 flags S keep state # Allow email pass out quick on dc0 proto tcp from any to any port = 110 flags S keep state pass out quick on dc0 proto tcp from any to any port = 25 flags S keep state # Allow NTP pass out quick on dc0 proto tcp from any to any port = 37 flags S keep state # Allow FTP pass out quick on dc0 proto tcp from any to any port = 21 flags S keep state # Allow SSH pass out quick on dc0 proto tcp from any to any port = 22 flags S keep state # Allow ping pass out quick on dc0 proto icmp from any to any icmp-type 8 keep state # Block and log everything else block out log first quick on dc0 all .... This example of the rules in the inbound section of the public interface blocks all undesirable packets first. This reduces the number of packets that are logged by the last rule. [.programlisting] .... # interface facing Internet (inbound) # Block all inbound traffic from non-routable or reserved address spaces block in quick on dc0 from 192.168.0.0/16 to any #RFC 1918 private IP block in quick on dc0 from 172.16.0.0/12 to any #RFC 1918 private IP block in quick on dc0 from 10.0.0.0/8 to any #RFC 1918 private IP block in quick on dc0 from 127.0.0.0/8 to any #loopback block in quick on dc0 from 0.0.0.0/8 to any #loopback block in quick on dc0 from 169.254.0.0/16 to any #DHCP auto-config block in quick on dc0 from 192.0.2.0/24 to any #reserved for docs block in quick on dc0 from 204.152.64.0/23 to any #Sun cluster interconnect block in quick on dc0 from 224.0.0.0/3 to any #Class D & E multicast # Block fragments and too short tcp packets block in quick on dc0 all with frags block in quick on dc0 proto tcp all with short # block source routed packets block in quick on dc0 all with opt lsrr block in quick on dc0 all with opt ssrr # Block OS fingerprint attempts and log first occurrence block in log first quick on dc0 proto tcp from any to any flags FUP # Block anything with special options block in quick on dc0 all with ipopts # Block public pings and ident block in quick on dc0 proto icmp all icmp-type 8 block in quick on dc0 proto tcp from any to any port = 113 # Block incoming Netbios services block in log first quick on dc0 proto tcp/udp from any to any port = 137 block in log first quick on dc0 proto tcp/udp from any to any port = 138 block in log first quick on dc0 proto tcp/udp from any to any port = 139 block in log first quick on dc0 proto tcp/udp from any to any port = 81 .... Any time there are logged messages on a rule with the `log first` option, run `ipfstat -hio` to evaluate how many times the rule has been matched. A large number of matches may indicate that the system is under attack. The rest of the rules in the inbound section define which connections are allowed to be initiated from the Internet. The last rule denies all connections which were not explicitly allowed by previous rules in this section. [.programlisting] .... # Allow traffic in from ISP's DHCP server. Replace z.z.z.z with # the same IP address used in the outbound section. pass in quick on dc0 proto udp from z.z.z.z to any port = 68 keep state # Allow public connections to specified internal web server pass in quick on dc0 proto tcp from any to x.x.x.x port = 80 flags S keep state # Block and log only first occurrence of all remaining traffic. block in log first quick on dc0 all .... === Configuring NAT To enable NAT, add these statements to [.filename]#/etc/rc.conf# and specify the name of the file containing the NAT rules: [.programlisting] .... gateway_enable="YES" ipnat_enable="YES" ipnat_rules="/etc/ipnat.rules" .... NAT rules are flexible and can accomplish many different things to fit the needs of both commercial and home users. The rule syntax presented here has been simplified to demonstrate common usage. For a complete rule syntax description, refer to man:ipnat[5]. The basic syntax for a NAT rule is as follows, where `map` starts the rule and _IF_ should be replaced with the name of the external interface: [.programlisting] .... map IF LAN_IP_RANGE -> PUBLIC_ADDRESS .... The _LAN_IP_RANGE_ is the range of IP addresses used by internal clients. Usually, it is a private address range such as `192.168.1.0/24`. The _PUBLIC_ADDRESS_ can either be the static external IP address or the keyword `0/32` which represents the IP address assigned to _IF_. In IPF, when a packet arrives at the firewall from the LAN with a public destination, it first passes through the outbound rules of the firewall ruleset. Then, the packet is passed to the NAT ruleset which is read from the top down, where the first matching rule wins. IPF tests each NAT rule against the packet's interface name and source IP address. When a packet's interface name matches a NAT rule, the packet's source IP address in the private LAN is checked to see if it falls within the IP address range specified in _LAN_IP_RANGE_. On a match, the packet has its source IP address rewritten with the public IP address specified by _PUBLIC_ADDRESS_. IPF posts an entry in its internal NAT table so that when the packet returns from the Internet, it can be mapped back to its original private IP address before being passed to the firewall rules for further processing. For networks that have large numbers of internal systems or multiple subnets, the process of funneling every private IP address into a single public IP address becomes a resource problem. Two methods are available to relieve this issue. The first method is to assign a range of ports to use as source ports. By adding the `portmap` keyword, NAT can be directed to only use source ports in the specified range: [.programlisting] .... map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp 20000:60000 .... Alternately, use the `auto` keyword which tells NAT to determine the ports that are available for use: [.programlisting] .... map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp auto .... The second method is to use a pool of public addresses. This is useful when there are too many LAN addresses to fit into a single public address and a block of public IP addresses is available. These public addresses can be used as a pool from which NAT selects an IP address as a packet's address is mapped on its way out. The range of public IP addresses can be specified using a netmask or CIDR notation. These two rules are equivalent: [.programlisting] .... map dc0 192.168.1.0/24 -> 204.134.75.0/255.255.255.0 map dc0 192.168.1.0/24 -> 204.134.75.0/24 .... A common practice is to have a publically accessible web server or mail server segregated to an internal network segment. The traffic from these servers still has to undergo NAT, but port redirection is needed to direct inbound traffic to the correct server. For example, to map a web server using the internal address `10.0.10.25` to its public IP address of `20.20.20.5`, use this rule: [.programlisting] .... rdr dc0 20.20.20.5/32 port 80 -> 10.0.10.25 port 80 .... If it is the only web server, this rule would also work as it redirects all external HTTP requests to `10.0.10.25`: [.programlisting] .... rdr dc0 0.0.0.0/0 port 80 -> 10.0.10.25 port 80 .... IPF has a built in FTP proxy which can be used with NAT. It monitors all outbound traffic for active or passive FTP connection requests and dynamically creates temporary filter rules containing the port number used by the FTP data channel. This eliminates the need to open large ranges of high order ports for FTP connections. In this example, the first rule calls the proxy for outbound FTP traffic from the internal LAN. The second rule passes the FTP traffic from the firewall to the Internet, and the third rule handles all non-FTP traffic from the internal LAN: [.programlisting] .... map dc0 10.0.10.0/29 -> 0/32 proxy port 21 ftp/tcp map dc0 0.0.0.0/0 -> 0/32 proxy port 21 ftp/tcp map dc0 10.0.10.0/29 -> 0/32 .... The FTP `map` rules go before the NAT rule so that when a packet matches an FTP rule, the FTP proxy creates temporary filter rules to let the FTP session packets pass and undergo NAT. All LAN packets that are not FTP will not match the FTP rules but will undergo NAT if they match the third rule. Without the FTP proxy, the following firewall rules would instead be needed. Note that without the proxy, all ports above `1024` need to be allowed: [.programlisting] .... # Allow out LAN PC client FTP to public Internet # Active and passive modes pass out quick on rl0 proto tcp from any to any port = 21 flags S keep state # Allow out passive mode data channel high order port numbers pass out quick on rl0 proto tcp from any to any port > 1024 flags S keep state # Active mode let data channel in from FTP server pass in quick on rl0 proto tcp from any to any port = 20 flags S keep state .... Whenever the file containing the NAT rules is edited, run `ipnat` with `-CF` to delete the current NAT rules and flush the contents of the dynamic translation table. Include `-f` and specify the name of the NAT ruleset to load: [source,bash] .... # ipnat -CF -f /etc/ipnat.rules .... To display the NAT statistics: [source,bash] .... # ipnat -s .... To list the NAT table's current mappings: [source,bash] .... # ipnat -l .... To turn verbose mode on and display information relating to rule processing and active rules and table entries: [source,bash] .... # ipnat -v .... === Viewing IPF Statistics IPF includes man:ipfstat[8] which can be used to retrieve and display statistics which are gathered as packets match rules as they go through the firewall. Statistics are accumulated since the firewall was last started or since the last time they were reset to zero using `ipf -Z`. The default `ipfstat` output looks like this: [source,bash] .... input packets: blocked 99286 passed 1255609 nomatch 14686 counted 0 output packets: blocked 4200 passed 1284345 nomatch 14687 counted 0 input packets logged: blocked 99286 passed 0 output packets logged: blocked 0 passed 0 packets logged: input 0 output 0 log failures: input 3898 output 0 fragment state(in): kept 0 lost 0 fragment state(out): kept 0 lost 0 packet state(in): kept 169364 lost 0 packet state(out): kept 431395 lost 0 ICMP replies: 0 TCP RSTs sent: 0 Result cache hits(in): 1215208 (out): 1098963 IN Pullups succeeded: 2 failed: 0 OUT Pullups succeeded: 0 failed: 0 Fastroute successes: 0 failures: 0 TCP cksum fails(in): 0 (out): 0 Packet log flags set: (0) .... Several options are available. When supplied with either `-i` for inbound or `-o` for outbound, the command will retrieve and display the appropriate list of filter rules currently installed and in use by the kernel. To also see the rule numbers, include `-n`. For example, `ipfstat -on` displays the outbound rules table with rule numbers: [source,bash] .... @1 pass out on xl0 from any to any @2 block out on dc0 from any to any @3 pass out quick on dc0 proto tcp/udp from any to any keep state .... Include `-h` to prefix each rule with a count of how many times the rule was matched. For example, `ipfstat -oh` displays the outbound internal rules table, prefixing each rule with its usage count: [source,bash] .... 2451423 pass out on xl0 from any to any 354727 block out on dc0 from any to any 430918 pass out quick on dc0 proto tcp/udp from any to any keep state .... To display the state table in a format similar to man:top[1], use `ipfstat -t`. When the firewall is under attack, this option provides the ability to identify and see the attacking packets. The optional sub-flags give the ability to select the destination or source IP, port, or protocol to be monitored in real time. Refer to man:ipfstat[8] for details. === IPF Logging IPF provides `ipmon`, which can be used to write the firewall's logging information in a human readable format. It requires that `options IPFILTER_LOG` be first added to a custom kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. This command is typically run in daemon mode in order to provide a continuous system log file so that logging of past events may be reviewed. Since FreeBSD has a built in man:syslogd[8] facility to automatically rotate system logs, the default [.filename]#rc.conf#`ipmon_flags` statement uses `-Ds`: [.programlisting] .... ipmon_flags="-Ds" # D = start as daemon # s = log to syslog # v = log tcp window, ack, seq # n = map IP & port to names .... Logging provides the ability to review, after the fact, information such as which packets were dropped, what addresses they came from, and where they were going. This information is useful in tracking down attackers. Once the logging facility is enabled in [.filename]#rc.conf# and started with `service ipmon start`, IPF will only log the rules which contain the `log` keyword. The firewall administrator decides which rules in the ruleset should be logged and normally only deny rules are logged. It is customary to include the `log` keyword in the last rule in the ruleset. This makes it possible to see all the packets that did not match any of the rules in the ruleset. By default, `ipmon -Ds` mode uses `local0` as the logging facility. The following logging levels can be used to further segregate the logged data: [source,bash] .... LOG_INFO - packets logged using the "log" keyword as the action rather than pass or block. LOG_NOTICE - packets logged which are also passed LOG_WARNING - packets logged which are also blocked LOG_ERR - packets which have been logged and which can be considered short due to an incomplete header .... In order to setup IPF to log all data to [.filename]#/var/log/ipfilter.log#, first create the empty file: [source,bash] .... # touch /var/log/ipfilter.log .... Then, to write all logged messages to the specified file, add the following statement to [.filename]#/etc/syslog.conf#: [.programlisting] .... local0.* /var/log/ipfilter.log .... To activate the changes and instruct man:syslogd[8] to read the modified [.filename]#/etc/syslog.conf#, run `service syslogd reload`. Do not forget to edit [.filename]#/etc/newsyslog.conf# to rotate the new log file. Messages generated by `ipmon` consist of data fields separated by white space. Fields common to all messages are: . The date of packet receipt. . The time of packet receipt. This is in the form HH:MM:SS.F, for hours, minutes, seconds, and fractions of a second. . The name of the interface that processed the packet. . The group and rule number of the rule in the format `@0:17`. . The action: `p` for passed, `b` for blocked, `S` for a short packet, `n` did not match any rules, and `L` for a log rule. . The addresses written as three fields: the source address and port separated by a comma, the -> symbol, and the destination address and port. For example: `209.53.17.22,80 -> 198.73.220.17,1722`. . `PR` followed by the protocol name or number: for example, `PR tcp`. . `len` followed by the header length and total length of the packet: for example, `len 20 40`. If the packet is a TCP packet, there will be an additional field starting with a hyphen followed by letters corresponding to any flags that were set. Refer to man:ipf[5] for a list of letters and their flags. If the packet is an ICMP packet, there will be two fields at the end: the first always being "icmp" and the next being the ICMP message and sub-message type, separated by a slash. For example: `icmp 3/3` for a port unreachable message. [[firewalls-blacklistd]] == Blacklistd Blacklistd is a daemon listening to sockets to receive notifications from other daemons about connection attempts that failed or were successful. It is most widely used in blocking too many connection attempts on open ports. A prime example is SSH running on the internet getting a lot of requests from bots or scripts trying to guess passwords and gain access. Using blacklistd, the daemon can notify the firewall to create a filter rule to block excessive connection attempts from a single source after a number of tries. Blacklistd was first developed on NetBSD and appeared there in version 7. FreeBSD 11 imported blacklistd from NetBSD. This chapter describes how to set up blacklistd, configure it, and provides examples on how to use it. Readers should be familiar with basic firewall concepts like rules. For details, refer to the firewall chapter. PF is used in the examples, but other firewalls available on FreeBSD should be able to work with blacklistd, too. === Enabling Blacklistd The main configuration for blacklistd is stored in man:blacklistd.conf[5]. Various command line options are also available to change blacklistd's run-time behavior. Persistent configuration across reboots should be stored in [.filename]#/etc/blacklistd.conf#. To enable the daemon during system boot, add a `blacklistd_enable` line to [.filename]#/etc/rc.conf# like this: [source,bash] .... # sysrc blacklistd_enable=yes .... To start the service manually, run this command: [source,bash] .... # service blacklistd start .... === Creating a Blacklistd Ruleset Rules for blacklistd are configured in man:blacklistd.conf[5] with one entry per line. Each rule contains a tuple separated by spaces or tabs. Rules either belong to a `local` or a `remote`, which applies to the machine where blacklistd is running or an outside source, respectively. ==== Local Rules An example blacklistd.conf entry for a local rule looks like this: [.programlisting] .... [local] ssh stream * * * 3 24h .... All rules that follow the `[local]` section are treated as local rules (which is the default), applying to the local machine. When a `[remote]` section is encountered, all rules that follow it are handled as remote machine rules. Seven fields define a rule separated by either tabs or spaces. The first four fields identify the traffic that should be blacklisted. The three fields that follow define backlistd's behavior. Wildcards are denoted as asterisks (`*`), matching anything in this field. The first field defines the location. In local rules, these are the network ports. The syntax for the location field is as follows: [.programlisting] .... [address|interface][/mask][:port] .... Adressses can be specified as IPv4 in numeric format or IPv6 in square brackets. An interface name like `_em0_` can also be used. The socket type is defined by the second field. TCP sockets are of type `stream`, whereas UDP is denoted as `dgram`. The example above uses TCP, since SSH is using that protocol. A protocol can be used in the third field of a blacklistd rule. The following protocols can be used: `tcp`, `udp`, `tcp6`, `udp6`, or numeric. A wildcard, like in the example, is typically used to match all protocols unless there is a reason to distinguish traffic by a certain protocol. In the fourth field, the effective user or owner of the daemon process that is reporting the event is defined. The username or UID can be used here, as well as a wildcard (see example rule above). The packet filter rule name is declared by the fifth field, which starts the behavior part of the rule. By default, blacklistd puts all blocks under a pf anchor called `blacklistd` in [.filename]#pf.conf# like this: [.programlisting] .... anchor "blacklistd/*" in on $ext_if block in pass out .... For separate blacklists, an anchor name can be used in this field. In other cases, the wildcard will suffice. When a name starts with a hyphen (`-`) it means that an anchor with the default rule name prepended should be used. A modified example from the above using the hyphen would look like this: [.programlisting] .... ssh stream * * -ssh 3 24h .... With such a rule, any new blacklist rules are added to an anchor called `blacklistd-ssh`. To block whole subnets for a single rule violation, a `/` in the rule name can be used. This causes the remaining portion of the name to be interpreted as the mask to be applied to the address specified in the rule. For example, this rule would block every address adjoining `/24`. [.programlisting] .... 22 stream tcp * */24 3 24h .... [NOTE] ==== It is important to specify the proper protocol here. IPv4 and IPv6 treat /24 differently, that is the reason why `*` cannot be used in the third field for this rule. ==== This rule defines that if any one host in that network is misbehaving, everything else on that network will be blocked, too. The sixth field, called `nfail`, sets the number of login failures required to blacklist the remote IP in question. When a wildcard is used at this position, it means that blocks will never happen. In the example rule above, a limit of three is defined meaning that after three attempts to log into SSH on one connection, the IP is blocked. The last field in a blacklistd rule definition specifies how long a host is blacklisted. The default unit is seconds, but suffixes like `m`, `h`, and `d` can also be specified for minutes, hours, and days, respectively. The example rule in its entirety means that after three times authenticating to SSH will result in a new PF block rule for that host. Rule matches are performed by first checking local rules one after another, from most specific to least specific. When a match occurs, the `remote` rules are applied and the name, `nfail`, and disable fields are changed by the `remote` rule that matched. ==== Remote Rules Remote rules are used to specify how blacklistd changes its behavior depending on the remote host currently being evaluated. Each field in a remote rule is the same as in a local rule. The only difference is in the way blacklistd is using them. To explain it, this example rule is used: [.programlisting] .... [remote] 203.0.113.128/25 * * * =/25 = 48h .... The address field can be an IP address (either v4 or v6), a port or both. This allows setting special rules for a specific remote address range like in this example. The fields for type, protocol and owner are identically interpreted as in the local rule. The name fields is different though: the equal sign (`=`) in a remote rule tells blacklistd to use the value from the matching local rule. It means that the firewall rule entry is taken and the `/25` prefix (a netmask of `255.255.255.128`) is added. When a connection from that address range is blacklisted, the entire subnet is affected. A PF anchor name can also be used here, in which case blacklistd will add rules for this address block to the anchor of that name. The default table is used when a wildcard is specified. A custom number of failures in the `nfail` column can be defined for an address. This is useful for exceptions to a specific rule, to maybe allow someone a less strict application of rules or a bit more leniency in login tries. Blocking is disabled when an asterisk is used in this sixth field. Remote rules allow a stricter enforcement of limits on attempts to log in compared to attempts coming from a local network like an office. === Blacklistd Client Configuration There are a few software packages in FreeBSD that can utilize blacklistd's functionality. The two most prominent ones are man:ftpd[8] and man:sshd[8] to block excessive connection attempts. To activate blacklistd in the SSH daemon, add the following line to [.filename]#/etc/ssh/sshd_config#: [.programlisting] .... UseBlacklist yes .... Restart sshd afterwards to make these changes take effect. Blacklisting for man:ftpd[8] is enabled using `-B`, either in [.filename]#/etc/inetd.conf# or as a flag in [.filename]#/etc/rc.conf# like this: [.programlisting] .... ftpd_flags="-B" .... That is all that is needed to make these programs talk to blacklistd. === Blacklistd Management Blacklistd provides the user with a management utility called man:blacklistctl[8]. It displays blocked addresses and networks that are blacklisted by the rules defined in man:blacklistd.conf[5]. To see the list of currently blocked hosts, use `dump` combined with `-b` like this. [source,bash] .... # blacklistctl dump -b address/ma:port id nfail last access 213.0.123.128/25:22 OK 6/3 2019/06/08 14:30:19 .... This example shows that there were 6 out of three permitted attempts on port 22 coming from the address range `213.0.123.128/25`. There are more attempts listed than are allowed because SSH allows a client to try multiple logins on a single TCP connection. A connection that is currently going on is not stopped by blacklistd. The last connection attempt is listed in the `last access` column of the output. To see the remaining time that this host will be on the blacklist, add `-r` to the previous command. [source,bash] .... # blacklistctl dump -br address/ma:port id nfail remaining time 213.0.123.128/25:22 OK 6/3 36s .... In this example, there are 36s seconds left until this host will not be blocked any more. === Removing Hosts from the Block List Sometimes it is necessary to remove a host from the block list before the remaining time expires. Unfortunately, there is no functionality in blacklistd to do that. However, it is possible to remove the address from the PF table using pfctl. For each blocked port, there is a child anchor inside the blacklistd anchor defined in [.filename]#/etc/pf.conf#. For example, if there is a child anchor for blocking port 22 it is called `blacklistd/22`. There is a table inside that child anchor that contains the blocked addresses. This table is called port followed by the port number. In this example, it would be called `port22`. With that information at hand, it is now possible to use man:pfctl[8] to display all addresses listed like this: [source,bash] .... # pfctl -a blacklistd/22 -t port22 -T show ... 213.0.123.128/25 ... .... After identifying the address to be unblocked from the list, the following command removes it from the list: [source,bash] .... # pfctl -a blacklistd/22 -t port22 -T delete 213.0.123.128/25 .... The address is now removed from PF, but will still show up in the blacklistctl list, since it does not know about any changes made in PF. The entry in blacklistd's database will eventually expire and be removed from its output eventually. The entry will be added again if the host is matching one of the block rules in blacklistd again. diff --git a/documentation/content/en/books/handbook/mac/_index.adoc b/documentation/content/en/books/handbook/mac/_index.adoc index e38a745f61..60c1d46c07 100644 --- a/documentation/content/en/books/handbook/mac/_index.adoc +++ b/documentation/content/en/books/handbook/mac/_index.adoc @@ -1,804 +1,804 @@ --- title: Chapter 16. Mandatory Access Control part: Part III. System Administration prev: books/handbook/jails next: books/handbook/audit --- [[mac]] = Mandatory Access Control :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 16 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/mac/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/mac/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/mac/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[mac-synopsis]] == Synopsis FreeBSD supports security extensions based on the POSIX(R).1e draft. These security mechanisms include file system Access Control Lists (crossref:security[fs-acl,“Access Control Lists”]) and Mandatory Access Control (MAC). MAC allows access control modules to be loaded in order to implement security policies. Some modules provide protections for a narrow subset of the system, hardening a particular service. Others provide comprehensive labeled security across all subjects and objects. The mandatory part of the definition indicates that enforcement of controls is performed by administrators and the operating system. This is in contrast to the default security mechanism of Discretionary Access Control (DAC) where enforcement is left to the discretion of users. This chapter focuses on the MAC framework and the set of pluggable security policy modules FreeBSD provides for enabling various security mechanisms. After reading this chapter, you will know: * The terminology associated with the MAC framework. * The capabilities of MAC security policy modules as well as the difference between a labeled and non-labeled policy. * The considerations to take into account before configuring a system to use the MAC framework. * Which MAC security policy modules are included in FreeBSD and how to configure them. * How to implement a more secure environment using the MAC framework. * How to test the MAC configuration to ensure the framework has been properly implemented. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Have some familiarity with security and how it pertains to FreeBSD (crossref:security[security,Security]). [WARNING] ==== Improper MAC configuration may cause loss of system access, aggravation of users, or inability to access the features provided by Xorg. More importantly, MAC should not be relied upon to completely secure a system. The MAC framework only augments an existing security policy. Without sound security practices and regular security checks, the system will never be completely secure. The examples contained within this chapter are for demonstration purposes and the example settings should _not_ be implemented on a production system. Implementing any security policy takes a good deal of understanding, proper design, and thorough testing. ==== While this chapter covers a broad range of security issues relating to the MAC framework, the development of new MAC security policy modules will not be covered. A number of security policy modules included with the MAC framework have specific characteristics which are provided for both testing and new module development. Refer to man:mac_test[4], man:mac_stub[4] and man:mac_none[4] for more information on these security policy modules and the various mechanisms they provide. [[mac-inline-glossary]] == Key Terms The following key terms are used when referring to the MAC framework: * _compartment_: a set of programs and data to be partitioned or separated, where users are given explicit access to specific component of a system. A compartment represents a grouping, such as a work group, department, project, or topic. Compartments make it possible to implement a need-to-know-basis security policy. * _integrity_: the level of trust which can be placed on data. As the integrity of the data is elevated, so does the ability to trust that data. * _level_: the increased or decreased setting of a security attribute. As the level increases, its security is considered to elevate as well. * _label_: a security attribute which can be applied to files, directories, or other items in the system. It could be considered a confidentiality stamp. When a label is placed on a file, it describes the security properties of that file and will only permit access by files, users, and resources with a similar security setting. The meaning and interpretation of label values depends on the policy configuration. Some policies treat a label as representing the integrity or secrecy of an object while other policies might use labels to hold rules for access. * _multilabel_: this property is a file system option which can be set in single-user mode using man:tunefs[8], during boot using man:fstab[5], or during the creation of a new file system. This option permits an administrator to apply different MAC labels on different objects. This option only applies to security policy modules which support labeling. * _single label_: a policy where the entire file system uses one label to enforce access control over the flow of data. Whenever `multilabel` is not set, all files will conform to the same label setting. * _object_: an entity through which information flows under the direction of a _subject_. This includes directories, files, fields, screens, keyboards, memory, magnetic storage, printers or any other data storage or moving device. An object is a data container or a system resource. Access to an object effectively means access to its data. * _subject_: any active entity that causes information to flow between _objects_ such as a user, user process, or system process. On FreeBSD, this is almost always a thread acting in a process on behalf of a user. * _policy_: a collection of rules which defines how objectives are to be achieved. A policy usually documents how certain items are to be handled. This chapter considers a policy to be a collection of rules which controls the flow of data and information and defines who has access to that data and information. * _high-watermark_: this type of policy permits the raising of security levels for the purpose of accessing higher level information. In most cases, the original level is restored after the process is complete. Currently, the FreeBSD MAC framework does not include this type of policy. * _low-watermark_: this type of policy permits lowering security levels for the purpose of accessing information which is less secure. In most cases, the original security level of the user is restored after the process is complete. The only security policy module in FreeBSD to use this is man:mac_lomac[4]. * _sensitivity_: usually used when discussing Multilevel Security (MLS). A sensitivity level describes how important or secret the data should be. As the sensitivity level increases, so does the importance of the secrecy, or confidentiality, of the data. [[mac-understandlabel]] == Understanding MAC Labels A MAC label is a security attribute which may be applied to subjects and objects throughout the system. When setting a label, the administrator must understand its implications in order to prevent unexpected or undesired behavior of the system. The attributes available on an object depend on the loaded policy module, as policy modules interpret their attributes in different ways. The security label on an object is used as a part of a security access control decision by a policy. With some policies, the label contains all of the information necessary to make a decision. In other policies, the labels may be processed as part of a larger rule set. There are two types of label policies: single label and multi label. By default, the system will use single label. The administrator should be aware of the pros and cons of each in order to implement policies which meet the requirements of the system's security model. A single label security policy only permits one label to be used for every subject or object. Since a single label policy enforces one set of access permissions across the entire system, it provides lower administration overhead, but decreases the flexibility of policies which support labeling. However, in many environments, a single label policy may be all that is required. A single label policy is somewhat similar to DAC as `root` configures the policies so that users are placed in the appropriate categories and access levels. A notable difference is that many policy modules can also restrict `root`. Basic control over objects will then be released to the group, but `root` may revoke or modify the settings at any time. When appropriate, a multi label policy can be set on a UFS file system by passing `multilabel` to man:tunefs[8]. A multi label policy permits each subject or object to have its own independent MAC label. The decision to use a multi label or single label policy is only required for policies which implement the labeling feature, such as `biba`, `lomac`, and `mls`. Some policies, such as `seeotheruids`, `portacl` and `partition`, do not use labels at all. Using a multi label policy on a partition and establishing a multi label security model can increase administrative overhead as everything in that file system has a label. This includes directories, files, and even device nodes. The following command will set `multilabel` on the specified UFS file system. This may only be done in single-user mode and is not a requirement for the swap file system: [source,bash] .... # tunefs -l enable / .... [NOTE] ==== Some users have experienced problems with setting the `multilabel` flag on the root partition. If this is the case, please review <>. ==== Since the multi label policy is set on a per-file system basis, a multi label policy may not be needed if the file system layout is well designed. Consider an example security MAC model for a FreeBSD web server. This machine uses the single label, `biba/high`, for everything in the default file systems. If the web server needs to run at `biba/low` to prevent write up capabilities, it could be installed to a separate UFS [.filename]#/usr/local# file system set at `biba/low`. === Label Configuration Virtually all aspects of label policy module configuration will be performed using the base system utilities. These commands provide a simple interface for object or subject configuration or the manipulation and verification of the configuration. All configuration may be done using `setfmac`, which is used to set MAC labels on system objects, and `setpmac`, which is used to set the labels on system subjects. For example, to set the `biba` MAC label to `high` on [.filename]#test#: [source,bash] .... # setfmac biba/high test .... If the configuration is successful, the prompt will be returned without error. A common error is `Permission denied` which usually occurs when the label is being set or modified on a restricted object. Other conditions may produce different failures. For instance, the file may not be owned by the user attempting to relabel the object, the object may not exist, or the object may be read-only. A mandatory policy will not allow the process to relabel the file, maybe because of a property of the file, a property of the process, or a property of the proposed new label value. For example, if a user running at low integrity tries to change the label of a high integrity file, or a user running at low integrity tries to change the label of a low integrity file to a high integrity label, these operations will fail. The system administrator may use `setpmac` to override the policy module's settings by assigning a different label to the invoked process: [source,bash] .... # setfmac biba/high test Permission denied # setpmac biba/low setfmac biba/high test # getfmac test test: biba/high .... For currently running processes, such as sendmail, `getpmac` is usually used instead. This command takes a process ID (PID) in place of a command name. If users attempt to manipulate a file not in their access, subject to the rules of the loaded policy modules, the `Operation not permitted` error will be displayed. === Predefined Labels A few FreeBSD policy modules which support the labeling feature offer three predefined labels: `low`, `equal`, and `high`, where: * `low` is considered the lowest label setting an object or subject may have. Setting this on objects or subjects blocks their access to objects or subjects marked high. * `equal` sets the subject or object to be disabled or unaffected and should only be placed on objects considered to be exempt from the policy. * `high` grants an object or subject the highest setting available in the Biba and MLS policy modules. Such policy modules include man:mac_biba[4], man:mac_mls[4] and man:mac_lomac[4]. Each of the predefined labels establishes a different information flow directive. Refer to the manual page of the module to determine the traits of the generic label configurations. === Numeric Labels The Biba and MLS policy modules support a numeric label which may be set to indicate the precise level of hierarchical control. This numeric level is used to partition or sort information into different groups of classification, only permitting access to that group or a higher group level. For example: [.programlisting] .... biba/10:2+3+6(5:2+3-20:2+3+4+5+6) .... may be interpreted as "Biba Policy Label/Grade 10:Compartments 2, 3 and 6: (grade 5 ...") In this example, the first grade would be considered the effective grade with effective compartments, the second grade is the low grade, and the last one is the high grade. In most configurations, such fine-grained settings are not needed as they are considered to be advanced configurations. System objects only have a current grade and compartment. System subjects reflect the range of available rights in the system, and network interfaces, where they are used for access control. The grade and compartments in a subject and object pair are used to construct a relationship known as _dominance_, in which a subject dominates an object, the object dominates the subject, neither dominates the other, or both dominate each other. The "both dominate" case occurs when the two labels are equal. Due to the information flow nature of Biba, a user has rights to a set of compartments that might correspond to projects, but objects also have a set of compartments. Users may have to subset their rights using `su` or `setpmac` in order to access objects in a compartment from which they are not restricted. === User Labels Users are required to have labels so that their files and processes properly interact with the security policy defined on the system. This is configured in [.filename]#/etc/login.conf# using login classes. Every policy module that uses labels will implement the user class setting. To set the user class default label which will be enforced by MAC, add a `label` entry. An example `label` entry containing every policy module is displayed below. Note that in a real configuration, the administrator would never enable every policy module. It is recommended that the rest of this chapter be reviewed before any configuration is implemented. [.programlisting] .... default:\ :copyright=/etc/COPYRIGHT:\ :welcome=/etc/motd:\ :setenv=MAIL=/var/mail/$,BLOCKSIZE=K:\ :path=~/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:\ - :manpath=/usr/shared/man /usr/local/man:\ + :manpath=/usr/share/man /usr/local/man:\ :nologin=/usr/sbin/nologin:\ :cputime=1h30m:\ :datasize=8M:\ :vmemoryuse=100M:\ :stacksize=2M:\ :memorylocked=4M:\ :memoryuse=8M:\ :filesize=8M:\ :coredumpsize=8M:\ :openfiles=24:\ :maxproc=32:\ :priority=0:\ :requirehome:\ :passwordtime=91d:\ :umask=022:\ :ignoretime@:\ :label=partition/13,mls/5,biba/10(5-15),lomac/10[2]: .... While users can not modify the default value, they may change their label after they login, subject to the constraints of the policy. The example above tells the Biba policy that a process's minimum integrity is `5`, its maximum is `15`, and the default effective label is `10`. The process will run at `10` until it chooses to change label, perhaps due to the user using `setpmac`, which will be constrained by Biba to the configured range. After any change to [.filename]#login.conf#, the login class capability database must be rebuilt using `cap_mkdb`. Many sites have a large number of users requiring several different user classes. In depth planning is required as this can become difficult to manage. === Network Interface Labels Labels may be set on network interfaces to help control the flow of data across the network. Policies using network interface labels function in the same way that policies function with respect to objects. Users at high settings in Biba, for example, will not be permitted to access network interfaces with a label of `low`. When setting the MAC label on network interfaces, `maclabel` may be passed to `ifconfig`: [source,bash] .... # ifconfig bge0 maclabel biba/equal .... This example will set the MAC label of `biba/equal` on the `bge0` interface. When using a setting similar to `biba/high(low-high)`, the entire label should be quoted to prevent an error from being returned. Each policy module which supports labeling has a tunable which may be used to disable the MAC label on network interfaces. Setting the label to `equal` will have a similar effect. Review the output of `sysctl`, the policy manual pages, and the information in the rest of this chapter for more information on those tunables. [[mac-planning]] == Planning the Security Configuration Before implementing any MAC policies, a planning phase is recommended. During the planning stages, an administrator should consider the implementation requirements and goals, such as: * How to classify information and resources available on the target systems. * Which information or resources to restrict access to along with the type of restrictions that should be applied. * Which MAC modules will be required to achieve this goal. A trial run of the trusted system and its configuration should occur _before_ a MAC implementation is used on production systems. Since different environments have different needs and requirements, establishing a complete security profile will decrease the need of changes once the system goes live. Consider how the MAC framework augments the security of the system as a whole. The various security policy modules provided by the MAC framework could be used to protect the network and file systems or to block users from accessing certain ports and sockets. Perhaps the best use of the policy modules is to load several security policy modules at a time in order to provide a MLS environment. This approach differs from a hardening policy, which typically hardens elements of a system which are used only for specific purposes. The downside to MLS is increased administrative overhead. The overhead is minimal when compared to the lasting effect of a framework which provides the ability to pick and choose which policies are required for a specific configuration and which keeps performance overhead down. The reduction of support for unneeded policies can increase the overall performance of the system as well as offer flexibility of choice. A good implementation would consider the overall security requirements and effectively implement the various security policy modules offered by the framework. A system utilizing MAC guarantees that a user will not be permitted to change security attributes at will. All user utilities, programs, and scripts must work within the constraints of the access rules provided by the selected security policy modules and control of the MAC access rules is in the hands of the system administrator. It is the duty of the system administrator to carefully select the correct security policy modules. For an environment that needs to limit access control over the network, the man:mac_portacl[4], man:mac_ifoff[4], and man:mac_biba[4] policy modules make good starting points. For an environment where strict confidentiality of file system objects is required, consider the man:mac_bsdextended[4] and man:mac_mls[4] policy modules. Policy decisions could be made based on network configuration. If only certain users should be permitted access to man:ssh[1], the man:mac_portacl[4] policy module is a good choice. In the case of file systems, access to objects might be considered confidential to some users, but not to others. As an example, a large development team might be broken off into smaller projects where developers in project A might not be permitted to access objects written by developers in project B. Yet both projects might need to access objects created by developers in project C. Using the different security policy modules provided by the MAC framework, users could be divided into these groups and then given access to the appropriate objects. Each security policy module has a unique way of dealing with the overall security of a system. Module selection should be based on a well thought out security policy which may require revision and reimplementation. Understanding the different security policy modules offered by the MAC framework will help administrators choose the best policies for their situations. The rest of this chapter covers the available modules, describes their use and configuration, and in some cases, provides insight on applicable situations. [CAUTION] ==== Implementing MAC is much like implementing a firewall since care must be taken to prevent being completely locked out of the system. The ability to revert back to a previous configuration should be considered and the implementation of MAC over a remote connection should be done with extreme caution. ==== [[mac-policies]] == Available MAC Policies The default FreeBSD kernel includes `options MAC`. This means that every module included with the MAC framework can be loaded with `kldload` as a run-time kernel module. After testing the module, add the module name to [.filename]#/boot/loader.conf# so that it will load during boot. Each module also provides a kernel option for those administrators who choose to compile their own custom kernel. FreeBSD includes a group of policies that will cover most security requirements. Each policy is summarized below. The last three policies support integer settings in place of the three default labels. [[mac-seeotheruids]] === The MAC See Other UIDs Policy Module name: [.filename]#mac_seeotheruids.ko# Kernel configuration line: `options MAC_SEEOTHERUIDS` Boot option: `mac_seeotheruids_load="YES"` The man:mac_seeotheruids[4] module extends the `security.bsd.see_other_uids` and `security.bsd.see_other_gids sysctl` tunables. This option does not require any labels to be set before configuration and can operate transparently with other modules. After loading the module, the following `sysctl` tunables may be used to control its features: * `security.mac.seeotheruids.enabled` enables the module and implements the default settings which deny users the ability to view processes and sockets owned by other users. * `security.mac.seeotheruids.specificgid_enabled` allows specified groups to be exempt from this policy. To exempt specific groups, use the `security.mac.seeotheruids.specificgid=_XXX_ sysctl` tunable, replacing _XXX_ with the numeric group ID to be exempted. * `security.mac.seeotheruids.primarygroup_enabled` is used to exempt specific primary groups from this policy. When using this tunable, `security.mac.seeotheruids.specificgid_enabled` may not be set. [[mac-bsdextended]] === The MAC BSD Extended Policy Module name: [.filename]#mac_bsdextended.ko# Kernel configuration line: `options MAC_BSDEXTENDED` Boot option: `mac_bsdextended_load="YES"` The man:mac_bsdextended[4] module enforces a file system firewall. It provides an extension to the standard file system permissions model, permitting an administrator to create a firewall-like ruleset to protect files, utilities, and directories in the file system hierarchy. When access to a file system object is attempted, the list of rules is iterated until either a matching rule is located or the end is reached. This behavior may be changed using `security.mac.bsdextended.firstmatch_enabled`. Similar to other firewall modules in FreeBSD, a file containing the access control rules can be created and read by the system at boot time using an man:rc.conf[5] variable. The rule list may be entered using man:ugidfw[8] which has a syntax similar to man:ipfw[8]. More tools can be written by using the functions in the man:libugidfw[3] library. After the man:mac_bsdextended[4] module has been loaded, the following command may be used to list the current rule configuration: [source,bash] .... # ugidfw list 0 slots, 0 rules .... By default, no rules are defined and everything is completely accessible. To create a rule which blocks all access by users but leaves `root` unaffected: [source,bash] .... # ugidfw add subject not uid root new object not uid root mode n .... While this rule is simple to implement, it is a very bad idea as it blocks all users from issuing any commands. A more realistic example blocks `user1` all access, including directory listings, to ``_user2_``'s home directory: [source,bash] .... # ugidfw set 2 subject uid user1 object uid user2 mode n # ugidfw set 3 subject uid user1 object gid user2 mode n .... Instead of `user1`, `not uid _user2_` could be used in order to enforce the same access restrictions for all users. However, the `root` user is unaffected by these rules. [NOTE] ==== Extreme caution should be taken when working with this module as incorrect use could block access to certain parts of the file system. ==== [[mac-ifoff]] === The MAC Interface Silencing Policy Module name: [.filename]#mac_ifoff.ko# Kernel configuration line: `options MAC_IFOFF` Boot option: `mac_ifoff_load="YES"` The man:mac_ifoff[4] module is used to disable network interfaces on the fly and to keep network interfaces from being brought up during system boot. It does not use labels and does not depend on any other MAC modules. Most of this module's control is performed through these `sysctl` tunables: * `security.mac.ifoff.lo_enabled` enables or disables all traffic on the loopback, man:lo[4], interface. * `security.mac.ifoff.bpfrecv_enabled` enables or disables all traffic on the Berkeley Packet Filter interface, man:bpf[4]. * `security.mac.ifoff.other_enabled` enables or disables traffic on all other interfaces. One of the most common uses of man:mac_ifoff[4] is network monitoring in an environment where network traffic should not be permitted during the boot sequence. Another use would be to write a script which uses an application such as package:security/aide[] to automatically block network traffic if it finds new or altered files in protected directories. [[mac-portacl]] === The MAC Port Access Control List Policy Module name: [.filename]#mac_portacl.ko# Kernel configuration line: `MAC_PORTACL` Boot option: `mac_portacl_load="YES"` The man:mac_portacl[4] module is used to limit binding to local TCP and UDP ports, making it possible to allow non-`root` users to bind to specified privileged ports below 1024. Once loaded, this module enables the MAC policy on all sockets. The following tunables are available: * `security.mac.portacl.enabled` enables or disables the policy completely. * `security.mac.portacl.port_high` sets the highest port number that man:mac_portacl[4] protects. * `security.mac.portacl.suser_exempt`, when set to a non-zero value, exempts the `root` user from this policy. * `security.mac.portacl.rules` specifies the policy as a text string of the form `rule[,rule,...]`, with as many rules as needed, and where each rule is of the form `idtype:id:protocol:port`. The `idtype` is either `uid` or `gid`. The `protocol` parameter can be `tcp` or `udp`. The `port` parameter is the port number to allow the specified user or group to bind to. Only numeric values can be used for the user ID, group ID, and port parameters. By default, ports below 1024 can only be used by privileged processes which run as `root`. For man:mac_portacl[4] to allow non-privileged processes to bind to ports below 1024, set the following tunables as follows: [source,bash] .... # sysctl security.mac.portacl.port_high=1023 # sysctl net.inet.ip.portrange.reservedlow=0 # sysctl net.inet.ip.portrange.reservedhigh=0 .... To prevent the `root` user from being affected by this policy, set `security.mac.portacl.suser_exempt` to a non-zero value. [source,bash] .... # sysctl security.mac.portacl.suser_exempt=1 .... To allow the `www` user with UID 80 to bind to port 80 without ever needing `root` privilege: [source,bash] .... # sysctl security.mac.portacl.rules=uid:80:tcp:80 .... This next example permits the user with the UID of 1001 to bind to TCP ports 110 (POP3) and 995 (POP3s): [source,bash] .... # sysctl security.mac.portacl.rules=uid:1001:tcp:110,uid:1001:tcp:995 .... [[mac-partition]] === The MAC Partition Policy Module name: [.filename]#mac_partition.ko# Kernel configuration line: `options MAC_PARTITION` Boot option: `mac_partition_load="YES"` The man:mac_partition[4] policy drops processes into specific "partitions" based on their MAC label. Most configuration for this policy is done using man:setpmac[8]. One `sysctl` tunable is available for this policy: * `security.mac.partition.enabled` enables the enforcement of MAC process partitions. When this policy is enabled, users will only be permitted to see their processes, and any others within their partition, but will not be permitted to work with utilities outside the scope of this partition. For instance, a user in the `insecure` class will not be permitted to access `top` as well as many other commands that must spawn a process. This example adds `top` to the label set on users in the `insecure` class. All processes spawned by users in the `insecure` class will stay in the `partition/13` label. [source,bash] .... # setpmac partition/13 top .... This command displays the partition label and the process list: [source,bash] .... # ps Zax .... This command displays another user's process partition label and that user's currently running processes: [source,bash] .... # ps -ZU trhodes .... [NOTE] ==== Users can see processes in ``root``'s label unless the man:mac_seeotheruids[4] policy is loaded. ==== [[mac-mls]] === The MAC Multi-Level Security Module Module name: [.filename]#mac_mls.ko# Kernel configuration line: `options MAC_MLS` Boot option: `mac_mls_load="YES"` The man:mac_mls[4] policy controls access between subjects and objects in the system by enforcing a strict information flow policy. In MLS environments, a "clearance" level is set in the label of each subject or object, along with compartments. Since these clearance levels can reach numbers greater than several thousand, it would be a daunting task to thoroughly configure every subject or object. To ease this administrative overhead, three labels are included in this policy: `mls/low`, `mls/equal`, and `mls/high`, where: * Anything labeled with `mls/low` will have a low clearance level and not be permitted to access information of a higher level. This label also prevents objects of a higher clearance level from writing or passing information to a lower level. * `mls/equal` should be placed on objects which should be exempt from the policy. * `mls/high` is the highest level of clearance possible. Objects assigned this label will hold dominance over all other objects in the system; however, they will not permit the leaking of information to objects of a lower class. MLS provides: * A hierarchical security level with a set of non-hierarchical categories. * Fixed rules of `no read up, no write down`. This means that a subject can have read access to objects on its own level or below, but not above. Similarly, a subject can have write access to objects on its own level or above, but not beneath. * Secrecy, or the prevention of inappropriate disclosure of data. * A basis for the design of systems that concurrently handle data at multiple sensitivity levels without leaking information between secret and confidential. The following `sysctl` tunables are available: * `security.mac.mls.enabled` is used to enable or disable the MLS policy. * `security.mac.mls.ptys_equal` labels all man:pty[4] devices as `mls/equal` during creation. * `security.mac.mls.revocation_enabled` revokes access to objects after their label changes to a label of a lower grade. * `security.mac.mls.max_compartments` sets the maximum number of compartment levels allowed on a system. To manipulate MLS labels, use man:setfmac[8]. To assign a label to an object: [source,bash] .... # setfmac mls/5 test .... To get the MLS label for the file [.filename]#test#: [source,bash] .... # getfmac test .... Another approach is to create a master policy file in [.filename]#/etc/# which specifies the MLS policy information and to feed that file to `setfmac`. When using the MLS policy module, an administrator plans to control the flow of sensitive information. The default `block read up block write down` sets everything to a low state. Everything is accessible and an administrator slowly augments the confidentiality of the information. Beyond the three basic label options, an administrator may group users and groups as required to block the information flow between them. It might be easier to look at the information in clearance levels using descriptive words, such as classifications of `Confidential`, `Secret`, and `Top Secret`. Some administrators instead create different groups based on project levels. Regardless of the classification method, a well thought out plan must exist before implementing a restrictive policy. Some example situations for the MLS policy module include an e-commerce web server, a file server holding critical company information, and financial institution environments. [[mac-biba]] === The MAC Biba Module Module name: [.filename]#mac_biba.ko# Kernel configuration line: `options MAC_BIBA` Boot option: `mac_biba_load="YES"` The man:mac_biba[4] module loads the MAC Biba policy. This policy is similar to the MLS policy with the exception that the rules for information flow are slightly reversed. This is to prevent the downward flow of sensitive information whereas the MLS policy prevents the upward flow of sensitive information. In Biba environments, an "integrity" label is set on each subject or object. These labels are made up of hierarchical grades and non-hierarchical components. As a grade ascends, so does its integrity. Supported labels are `biba/low`, `biba/equal`, and `biba/high`, where: * `biba/low` is considered the lowest integrity an object or subject may have. Setting this on objects or subjects blocks their write access to objects or subjects marked as `biba/high`, but will not prevent read access. * `biba/equal` should only be placed on objects considered to be exempt from the policy. * `biba/high` permits writing to objects set at a lower label, but does not permit reading that object. It is recommended that this label be placed on objects that affect the integrity of the entire system. Biba provides: * Hierarchical integrity levels with a set of non-hierarchical integrity categories. * Fixed rules are `no write up, no read down`, the opposite of MLS. A subject can have write access to objects on its own level or below, but not above. Similarly, a subject can have read access to objects on its own level or above, but not below. * Integrity by preventing inappropriate modification of data. * Integrity levels instead of MLS sensitivity levels. The following tunables can be used to manipulate the Biba policy: * `security.mac.biba.enabled` is used to enable or disable enforcement of the Biba policy on the target machine. * `security.mac.biba.ptys_equal` is used to disable the Biba policy on man:pty[4] devices. * `security.mac.biba.revocation_enabled` forces the revocation of access to objects if the label is changed to dominate the subject. To access the Biba policy setting on system objects, use `setfmac` and `getfmac`: [source,bash] .... # setfmac biba/low test # getfmac test test: biba/low .... Integrity, which is different from sensitivity, is used to guarantee that information is not manipulated by untrusted parties. This includes information passed between subjects and objects. It ensures that users will only be able to modify or access information they have been given explicit access to. The man:mac_biba[4] security policy module permits an administrator to configure which files and programs a user may see and invoke while assuring that the programs and files are trusted by the system for that user. During the initial planning phase, an administrator must be prepared to partition users into grades, levels, and areas. The system will default to a high label once this policy module is enabled, and it is up to the administrator to configure the different grades and levels for users. Instead of using clearance levels, a good planning method could include topics. For instance, only allow developers modification access to the source code repository, source code compiler, and other development utilities. Other users would be grouped into other categories such as testers, designers, or end users and would only be permitted read access. A lower integrity subject is unable to write to a higher integrity subject and a higher integrity subject cannot list or read a lower integrity object. Setting a label at the lowest possible grade could make it inaccessible to subjects. Some prospective environments for this security policy module would include a constrained web server, a development and test machine, and a source code repository. A less useful implementation would be a personal workstation, a machine used as a router, or a network firewall. [[mac-lomac]] === The MAC Low-watermark Module Module name: [.filename]#mac_lomac.ko# Kernel configuration line: `options MAC_LOMAC` Boot option: `mac_lomac_load="YES"` Unlike the MAC Biba policy, the man:mac_lomac[4] policy permits access to lower integrity objects only after decreasing the integrity level to not disrupt any integrity rules. The Low-watermark integrity policy works almost identically to Biba, with the exception of using floating labels to support subject demotion via an auxiliary grade compartment. This secondary compartment takes the form `[auxgrade]`. When assigning a policy with an auxiliary grade, use the syntax `lomac/10[2]`, where `2` is the auxiliary grade. This policy relies on the ubiquitous labeling of all system objects with integrity labels, permitting subjects to read from low integrity objects and then downgrading the label on the subject to prevent future writes to high integrity objects using `[auxgrade]`. The policy may provide greater compatibility and require less initial configuration than Biba. Like the Biba and MLS policies, `setfmac` and `setpmac` are used to place labels on system objects: [source,bash] .... # setfmac /usr/home/trhodes lomac/high[low] # getfmac /usr/home/trhodes lomac/high[low] .... The auxiliary grade `low` is a feature provided only by the MACLOMAC policy. [[mac-userlocked]] == User Lock Down This example considers a relatively small storage system with fewer than fifty users. Users will have login capabilities and are permitted to store data and access resources. For this scenario, the man:mac_bsdextended[4] and man:mac_seeotheruids[4] policy modules could co-exist and block access to system objects while hiding user processes. Begin by adding the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... mac_seeotheruids_load="YES" .... The man:mac_bsdextended[4] security policy module may be activated by adding this line to [.filename]#/etc/rc.conf#: [.programlisting] .... ugidfw_enable="YES" .... Default rules stored in [.filename]#/etc/rc.bsdextended# will be loaded at system initialization. However, the default entries may need modification. Since this machine is expected only to service users, everything may be left commented out except the last two lines in order to force the loading of user owned system objects by default. Add the required users to this machine and reboot. For testing purposes, try logging in as a different user across two consoles. Run `ps aux` to see if processes of other users are visible. Verify that running man:ls[1] on another user's home directory fails. Do not try to test with the `root` user unless the specific ``sysctl``s have been modified to block super user access. [NOTE] ==== When a new user is added, their man:mac_bsdextended[4] rule will not be in the ruleset list. To update the ruleset quickly, unload the security policy module and reload it again using man:kldunload[8] and man:kldload[8]. ==== [[mac-implementing]] == Nagios in a MAC Jail This section demonstrates the steps that are needed to implement the Nagios network monitoring system in a MAC environment. This is meant as an example which still requires the administrator to test that the implemented policy meets the security requirements of the network before using in a production environment. This example requires `multilabel` to be set on each file system. It also assumes that package:net-mgmt/nagios-plugins[], package:net-mgmt/nagios[], and package:www/apache22[] are all installed, configured, and working correctly before attempting the integration into the MAC framework. === Create an Insecure User Class Begin the procedure by adding the following user class to [.filename]#/etc/login.conf#: [.programlisting] .... insecure:\ :copyright=/etc/COPYRIGHT:\ :welcome=/etc/motd:\ :setenv=MAIL=/var/mail/$,BLOCKSIZE=K:\ :path=~/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin -:manpath=/usr/shared/man /usr/local/man:\ +:manpath=/usr/share/man /usr/local/man:\ :nologin=/usr/sbin/nologin:\ :cputime=1h30m:\ :datasize=8M:\ :vmemoryuse=100M:\ :stacksize=2M:\ :memorylocked=4M:\ :memoryuse=8M:\ :filesize=8M:\ :coredumpsize=8M:\ :openfiles=24:\ :maxproc=32:\ :priority=0:\ :requirehome:\ :passwordtime=91d:\ :umask=022:\ :ignoretime@:\ :label=biba/10(10-10): .... Then, add the following line to the default user class section: [.programlisting] .... :label=biba/high: .... Save the edits and issue the following command to rebuild the database: [source,bash] .... # cap_mkdb /etc/login.conf .... === Configure Users Set the `root` user to the default class using: [source,bash] .... # pw usermod root -L default .... All user accounts that are not `root` will now require a login class. The login class is required, otherwise users will be refused access to common commands. The following `sh` script should do the trick: [source,bash] .... # for x in `awk -F: '($3 >= 1001) && ($3 != 65534) { print $1 }' \ /etc/passwd`; do pw usermod $x -L default; done; .... Next, drop the `nagios` and `www` accounts into the insecure class: [source,bash] .... # pw usermod nagios -L insecure # pw usermod www -L insecure .... === Create the Contexts File A contexts file should now be created as [.filename]#/etc/policy.contexts#: [.programlisting] .... # This is the default BIBA policy for this system. # System: /var/run(/.*)? biba/equal /dev/(/.*)? biba/equal /var biba/equal /var/spool(/.*)? biba/equal /var/log(/.*)? biba/equal /tmp(/.*)? biba/equal /var/tmp(/.*)? biba/equal /var/spool/mqueue biba/equal /var/spool/clientmqueue biba/equal # For Nagios: /usr/local/etc/nagios(/.*)? biba/10 /var/spool/nagios(/.*)? biba/10 # For apache /usr/local/etc/apache(/.*)? biba/10 .... This policy enforces security by setting restrictions on the flow of information. In this specific configuration, users, including `root`, should never be allowed to access Nagios. Configuration files and processes that are a part of Nagios will be completely self contained or jailed. This file will be read after running `setfsmac` on every file system. This example sets the policy on the root file system: [source,bash] .... # setfsmac -ef /etc/policy.contexts / .... Next, add these edits to the main section of [.filename]#/etc/mac.conf#: [.programlisting] .... default_labels file ?biba default_labels ifnet ?biba default_labels process ?biba default_labels socket ?biba .... === Loader Configuration To finish the configuration, add the following lines to [.filename]#/boot/loader.conf#: [.programlisting] .... mac_biba_load="YES" mac_seeotheruids_load="YES" security.mac.biba.trust_all_interfaces=1 .... And the following line to the network card configuration stored in [.filename]#/etc/rc.conf#. If the primary network configuration is done via DHCP, this may need to be configured manually after every system boot: [.programlisting] .... maclabel biba/equal .... === Testing the Configuration First, ensure that the web server and Nagios will not be started on system initialization and reboot. Ensure that `root` cannot access any of the files in the Nagios configuration directory. If `root` can list the contents of [.filename]#/var/spool/nagios#, something is wrong. Instead, a "permission denied" error should be returned. If all seems well, Nagios, Apache, and Sendmail can now be started: [source,bash] .... # cd /etc/mail && make stop && \ setpmac biba/equal make start && setpmac biba/10\(10-10\) apachectl start && \ setpmac biba/10\(10-10\) /usr/local/etc/rc.d/nagios.sh forcestart .... Double check to ensure that everything is working properly. If not, check the log files for error messages. If needed, use man:sysctl[8] to disable the man:mac_biba[4] security policy module and try starting everything again as usual. [NOTE] ==== The `root` user can still change the security enforcement and edit its configuration files. The following command will permit the degradation of the security policy to a lower grade for a newly spawned shell: [source,bash] .... # setpmac biba/10 csh .... To block this from happening, force the user into a range using man:login.conf[5]. If man:setpmac[8] attempts to run a command outside of the compartment's range, an error will be returned and the command will not be executed. In this case, set root to `biba/high(high-high)`. ==== [[mac-troubleshoot]] == Troubleshooting the MAC Framework This section discusses common configuration errors and how to resolve them. The `multilabel` flag does not stay enabled on the root ([.filename]#/#) partition::: The following steps may resolve this transient error: [.procedure] ==== . Edit [.filename]#/etc/fstab# and set the root partition to `ro` for read-only. . Reboot into single user mode. . Run `tunefs -l enable` on [.filename]#/#. . Reboot the system. . Run `mount -urw`[.filename]#/# and change the `ro` back to `rw` in [.filename]#/etc/fstab# and reboot the system again. . Double-check the output from `mount` to ensure that `multilabel` has been properly set on the root file system. ==== After establishing a secure environment with MAC, Xorg no longer starts::: This could be caused by the MAC `partition` policy or by a mislabeling in one of the MAC labeling policies. To debug, try the following: [.procedure] ==== . Check the error message. If the user is in the `insecure` class, the `partition` policy may be the culprit. Try setting the user's class back to the `default` class and rebuild the database with `cap_mkdb`. If this does not alleviate the problem, go to step two. . Double-check that the label policies are set correctly for the user, Xorg, and the [.filename]#/dev# entries. . If neither of these resolve the problem, send the error message and a description of the environment to the {freebsd-questions}. ==== The `_secure_path: unable to stat .login_conf` error appears::: This error can appear when a user attempts to switch from the `root` user to another user in the system. This message usually occurs when the user has a higher label setting than that of the user they are attempting to become. For instance, if `joe` has a default label of `biba/low` and `root` has a label of `biba/high`, `root` cannot view ``joe``'s home directory. This will happen whether or not `root` has used `su` to become `joe` as the Biba integrity model will not permit `root` to view objects set at a lower integrity level. The system no longer recognizes `root`::: When this occurs, `whoami` returns `0` and `su` returns `who are you?`. + This can happen if a labeling policy has been disabled by man:sysctl[8] or the policy module was unloaded. If the policy is disabled, the login capabilities database needs to be reconfigured. Double check [.filename]#/etc/login.conf# to ensure that all `label` options have been removed and rebuild the database with `cap_mkdb`. + This may also happen if a policy restricts access to [.filename]#master.passwd#. This is usually caused by an administrator altering the file under a label which conflicts with the general policy being used by the system. In these cases, the user information would be read by the system and access would be blocked as the file has inherited the new label. Disable the policy using man:sysctl[8] and everything should return to normal. diff --git a/documentation/content/en/books/handbook/ports/_index.adoc b/documentation/content/en/books/handbook/ports/_index.adoc index 17fb3863ef..ef304f4b65 100644 --- a/documentation/content/en/books/handbook/ports/_index.adoc +++ b/documentation/content/en/books/handbook/ports/_index.adoc @@ -1,1148 +1,1148 @@ --- title: "Chapter 4. Installing Applications: Packages and Ports" part: Part I. Getting Started prev: books/handbook/basics next: books/handbook/x11 --- [[ports]] = Installing Applications: Packages and Ports :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 4 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/ports/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/ports/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/ports/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[ports-synopsis]] == Synopsis FreeBSD is bundled with a rich collection of system tools as part of the base system. In addition, FreeBSD provides two complementary technologies for installing third-party software: the FreeBSD Ports Collection, for installing from source, and packages, for installing from pre-built binaries. Either method may be used to install software from local media or from the network. After reading this chapter, you will know: * The difference between binary packages and ports. * How to find third-party software that has been ported to FreeBSD. * How to manage binary packages using pkg. * How to build third-party software from source using the Ports Collection. * How to find the files installed with the application for post-installation configuration. * What to do if a software installation fails. [[ports-overview]] == Overview of Software Installation The typical steps for installing third-party software on a UNIX(R) system include: [.procedure] . Find and download the software, which might be distributed in source code format or as a binary. . Unpack the software from its distribution format. This is typically a tarball compressed with a program such as man:compress[1], man:gzip[1], man:bzip2[1] or man:xz[1]. . Locate the documentation in [.filename]#INSTALL#, [.filename]#README# or some file in a [.filename]#doc/# subdirectory and read up on how to install the software. . If the software was distributed in source format, compile it. This may involve editing a [.filename]#Makefile# or running a `configure` script. . Test and install the software. A FreeBSD _port_ is a collection of files designed to automate the process of compiling an application from source code. The files that comprise a port contain all the necessary information to automatically download, extract, patch, compile, and install the application. If the software has not already been adapted and tested on FreeBSD, the source code might need editing in order for it to install and run properly. However, over link:https://www.FreeBSD.org/ports/[{numports}] third-party applications have already been ported to FreeBSD. When feasible, these applications are made available for download as pre-compiled _packages_. Packages can be manipulated with the FreeBSD package management commands. Both packages and ports understand dependencies. If a package or port is used to install an application and a dependent library is not already installed, the library will automatically be installed first. A FreeBSD package contains pre-compiled copies of all the commands for an application, as well as any configuration files and documentation. A package can be manipulated with the man:pkg[8] commands, such as `pkg install`. While the two technologies are similar, packages and ports each have their own strengths. Select the technology that meets your requirements for installing a particular application. .Package Benefits * A compressed package tarball is typically smaller than the compressed tarball containing the source code for the application. * Packages do not require compilation time. For large applications, such as Mozilla, KDE, or GNOME, this can be important on a slow system. * Packages do not require any understanding of the process involved in compiling software on FreeBSD. .Port Benefits * Packages are normally compiled with conservative options because they have to run on the maximum number of systems. By compiling from the port, one can change the compilation options. * Some applications have compile-time options relating to which features are installed. For example, Apache can be configured with a wide variety of different built-in options. + In some cases, multiple packages will exist for the same application to specify certain settings. For example, Ghostscript is available as a [.filename]#ghostscript# package and a [.filename]#ghostscript-nox11# package, depending on whether or not Xorg is installed. Creating multiple packages rapidly becomes impossible if an application has more than one or two different compile-time options. * The licensing conditions of some software forbid binary distribution. Such software must be distributed as source code which must be compiled by the end-user. * Some people do not trust binary distributions or prefer to read through source code in order to look for potential problems. * Source code is needed in order to apply custom patches. To keep track of updated ports, subscribe to the {freebsd-ports} and the {freebsd-ports-bugs}. [WARNING] ==== Before installing any application, check https://vuxml.freebsd.org/[] for security issues related to the application or type `pkg audit -F` to check all installed applications for known vulnerabilities. ==== The remainder of this chapter explains how to use packages and ports to install and manage third-party software on FreeBSD. [[ports-finding-applications]] == Finding Software FreeBSD's list of available applications is growing all the time. There are a number of ways to find software to install: * The FreeBSD web site maintains an up-to-date searchable list of all the available applications, at link:https://www.FreeBSD.org/ports/[https://www.FreeBSD.org/ports/]. The ports can be searched by application name or by software category. * Dan Langille maintains http://www.FreshPorts.org/[FreshPorts.org] which provides a comprehensive search utility and also tracks changes to the applications in the Ports Collection. Registered users can create a customized watch list in order to receive an automated email when their watched ports are updated. * If finding a particular application becomes challenging, try searching a site like http://www.sourceforge.net/[SourceForge.net] or http://www.github.com/[GitHub.com] then check back at the link:https://www.FreeBSD.org/ports/[FreeBSD site] to see if the application has been ported. * To search the binary package repository for an application: + [source,bash] .... # pkg search subversion git-subversion-1.9.2 java-subversion-1.8.8_2 p5-subversion-1.8.8_2 py27-hgsubversion-1.6 py27-subversion-1.8.8_2 ruby-subversion-1.8.8_2 subversion-1.8.8_2 subversion-book-4515 subversion-static-1.8.8_2 subversion16-1.6.23_4 subversion17-1.7.16_2 .... + Package names include the version number and, in the case of ports based on python, the version number of the version of python the package was built with. Some ports also have multiple versions available. In the case of Subversion, there are different versions available, as well as different compile options. In this case, the statically linked version of Subversion. When indicating which package to install, it is best to specify the application by the port origin, which is the path in the ports tree. Repeat the `pkg search` with `-o` to list the origin of each package: + [source,bash] .... # pkg search -o subversion devel/git-subversion java/java-subversion devel/p5-subversion devel/py-hgsubversion devel/py-subversion devel/ruby-subversion devel/subversion16 devel/subversion17 devel/subversion devel/subversion-book devel/subversion-static .... + Searching by shell globs, regular expressions, exact match, by description, or any other field in the repository database is also supported by `pkg search`. After installing package:ports-mgmt/pkg[] or package:ports-mgmt/pkg-devel[], see man:pkg-search[8] for more details. * If the Ports Collection is already installed, there are several methods to query the local version of the ports tree. To find out which category a port is in, type `whereis _file_`, where _file_ is the program to be installed: + [source,bash] .... # whereis lsof lsof: /usr/ports/sysutils/lsof .... + Alternately, an man:echo[1] statement can be used: + [source,bash] .... # echo /usr/ports/*/*lsof* /usr/ports/sysutils/lsof .... + Note that this will also return any matched files downloaded into the [.filename]#/usr/ports/distfiles# directory. * Another way to find software is by using the Ports Collection's built-in search mechanism. To use the search feature, cd to [.filename]#/usr/ports# then run `make search name=program-name` where _program-name_ is the name of the software. For example, to search for `lsof`: + [source,bash] .... # cd /usr/ports # make search name=lsof Port: lsof-4.88.d,8 Path: /usr/ports/sysutils/lsof Info: Lists information about open files (similar to fstat(1)) Maint: ler@lerctr.org Index: sysutils B-deps: R-deps: .... + [TIP] ==== The built-in search mechanism uses a file of index information. If a message indicates that the [.filename]#INDEX# is required, run `make fetchindex` to download the current index file. With the [.filename]#INDEX# present, `make search` will be able to perform the requested search. ==== + The "Path:" line indicates where to find the port. + To receive less information, use the `quicksearch` feature: + [source,bash] .... # cd /usr/ports # make quicksearch name=lsof Port: lsof-4.88.d,8 Path: /usr/ports/sysutils/lsof Info: Lists information about open files (similar to fstat(1)) .... + For more in-depth searching, use `make search key=_string_` or `make quicksearch key=_string_`, where _string_ is some text to search for. The text can be in comments, descriptions, or dependencies in order to find ports which relate to a particular subject when the name of the program is unknown. + When using `search` or `quicksearch`, the search string is case-insensitive. Searching for "LSOF" will yield the same results as searching for "lsof". [[pkgng-intro]] == Using pkg for Binary Package Management pkg is the next generation replacement for the traditional FreeBSD package management tools, offering many features that make dealing with binary packages faster and easier. For sites wishing to only use prebuilt binary packages from the FreeBSD mirrors, managing packages with pkg can be sufficient. However, for those sites building from source or using their own repositories, a separate <> will be needed. Since pkg only works with binary packages, it is not a replacement for such tools. Those tools can be used to install software from both binary packages and the Ports Collection, while pkg installs only binary packages. [[pkgng-initial-setup]] === Getting Started with pkg FreeBSD includes a bootstrap utility which can be used to download and install pkg and its manual pages. This utility is designed to work with versions of FreeBSD starting with 10._X_. [NOTE] ==== Not all FreeBSD versions and architectures support this bootstrap process. The current list is at https://pkg.freebsd.org/[]. For other cases, pkg must instead be installed from the Ports Collection or as a binary package. ==== To bootstrap the system, run: [source,bash] .... # /usr/sbin/pkg .... You must have a working Internet connection for the bootstrap process to succeed. Otherwise, to install the port, run: [source,bash] .... # cd /usr/ports/ports-mgmt/pkg # make # make install clean .... When upgrading an existing system that originally used the older pkg_* tools, the database must be converted to the new format, so that the new tools are aware of the already installed packages. Once pkg has been installed, the package database must be converted from the traditional format to the new format by running this command: [source,bash] .... # pkg2ng .... [NOTE] ==== This step is not required for new installations that do not yet have any third-party software installed. ==== [IMPORTANT] ==== This step is not reversible. Once the package database has been converted to the pkg format, the traditional `pkg_*` tools should no longer be used. ==== [NOTE] ==== The package database conversion may emit errors as the contents are converted to the new version. Generally, these errors can be safely ignored. However, a list of software that was not successfully converted is shown after `pkg2ng` finishes. These applications must be manually reinstalled. ==== To ensure that the Ports Collection registers new software with pkg instead of the traditional packages database, FreeBSD versions earlier than 10._X_ require this line in [.filename]#/etc/make.conf#: [.programlisting] .... WITH_PKGNG= yes .... By default, pkg uses the binary packages from the FreeBSD package mirrors (the _repository_). For information about building a custom package repository, see <>. Additional pkg configuration options are described in man:pkg.conf[5]. Usage information for pkg is available in the man:pkg[8] manual page or by running `pkg` without additional arguments. Each pkg command argument is documented in a command-specific manual page. To read the manual page for `pkg install`, for example, run either of these commands: [source,bash] .... # pkg help install .... [source,bash] .... # man pkg-install .... The rest of this section demonstrates common binary package management tasks which can be performed using pkg. Each demonstrated command provides many switches to customize its use. Refer to a command's help or man page for details and more examples. [[quarterly-latest-branch]] === Quarterly and Latest Ports Branches The `Quarterly` branch provides users with a more predictable and stable experience for port and package installation and upgrades. This is done essentially by only allowing non-feature updates. Quarterly branches aim to receive security fixes (that may be version updates, or backports of commits), bug fixes and ports compliance or framework changes. The Quarterly branch is cut from HEAD at the beginning of every (yearly) quarter in January, April, July, and October. Branches are named according to the year (YYYY) and quarter (Q1-4) they are created in. For example, the quarterly branch created in January 2016, is named 2016Q1. And the `Latest` branch provides the latest versions of the packages to the users. To switch from quarterly to latest run the following commands: [source,bash] .... # mkdir -p /usr/local/etc/pkg/repos # cp /etc/pkg/FreeBSD.conf /usr/local/etc/pkg/repos/FreeBSD.conf .... Edit the file [.filename]#/usr/local/etc/pkg/repos/FreeBSD.conf# and change the string _quarterly_ to _latest_ in the `url:` line. The result should be similar to the following: [.programlisting] .... FreeBSD: { url: "pkg+http://pkg.FreeBSD.org/${ABI}/latest", mirror_type: "srv", signature_type: "fingerprints", - fingerprints: "/usr/shared/keys/pkg", + fingerprints: "/usr/share/keys/pkg", enabled: yes } .... And finally run this command to update from the new (latest) repository metadata. [source,bash] .... # pkg update -f .... [[pkgng-pkg-info]] === Obtaining Information About Installed Packages Information about the packages installed on a system can be viewed by running `pkg info` which, when run without any switches, will list the package version for either all installed packages or the specified package. For example, to see which version of pkg is installed, run: [source,bash] .... # pkg info pkg pkg-1.1.4_1 .... [[pkgng-installing-deinstalling]] === Installing and Removing Packages To install a binary package use the following command, where _packagename_ is the name of the package to install: [source,bash] .... # pkg install packagename .... This command uses repository data to determine which version of the software to install and if it has any uninstalled dependencies. For example, to install curl: [source,bash] .... # pkg install curl Updating repository catalogue /usr/local/tmp/All/curl-7.31.0_1.txz 100% of 1181 kB 1380 kBps 00m01s /usr/local/tmp/All/ca_root_nss-3.15.1_1.txz 100% of 288 kB 1700 kBps 00m00s Updating repository catalogue The following 2 packages will be installed: Installing ca_root_nss: 3.15.1_1 Installing curl: 7.31.0_1 The installation will require 3 MB more space 0 B to be downloaded Proceed with installing packages [y/N]: y Checking integrity... done [1/2] Installing ca_root_nss-3.15.1_1... done [2/2] Installing curl-7.31.0_1... done Cleaning up cache files...Done .... The new package and any additional packages that were installed as dependencies can be seen in the installed packages list: [source,bash] .... # pkg info ca_root_nss-3.15.1_1 The root certificate bundle from the Mozilla Project curl-7.31.0_1 Non-interactive tool to get files from FTP, GOPHER, HTTP(S) servers pkg-1.1.4_6 New generation package manager .... Packages that are no longer needed can be removed with `pkg delete`. For example: [source,bash] .... # pkg delete curl The following packages will be deleted: curl-7.31.0_1 The deletion will free 3 MB Proceed with deleting packages [y/N]: y [1/1] Deleting curl-7.31.0_1... done .... [[pkgng-upgrading]] === Upgrading Installed Packages Installed packages can be upgraded to their latest versions by running: [source,bash] .... # pkg upgrade .... This command will compare the installed versions with those available in the repository catalogue and upgrade them from the repository. [[pkgng-auditing]] === Auditing Installed Packages Software vulnerabilities are regularly discovered in third-party applications. To address this, pkg includes a built-in auditing mechanism. To determine if there are any known vulnerabilities for the software installed on the system, run: [source,bash] .... # pkg audit -F .... [[pkgng-autoremove]] === Automatically Removing Unused Packages Removing a package may leave behind dependencies which are no longer required. Unneeded packages that were installed as dependencies (leaf packages) can be automatically detected and removed using: [source,bash] .... # pkg autoremove Packages to be autoremoved: ca_root_nss-3.15.1_1 The autoremoval will free 723 kB Proceed with autoremoval of packages [y/N]: y Deinstalling ca_root_nss-3.15.1_1... done .... Packages installed as dependencies are called _automatic_ packages. Non-automatic packages, i.e the packages that were explicity installed not as a dependency to another package, can be listed using: [source,bash] .... # pkg prime-list nginx openvpn sudo .... `pkg prime-list` is an alias command declared in [.filename]#/usr/local/etc/pkg.conf#. There are many others that can be used to query the package database of the system. For instance, command `pkg prime-origins` can be used to get the origin port directory of the list mentioned above: [source,bash] .... # pkg prime-origins www/nginx security/openvpn security/sudo .... This list can be used to rebuild all packages installed on a system using build tools such as package:ports-mgmt/poudriere[] or package:ports-mgmt/synth[]. Marking an installed package as automatic can be done using: [source,bash] .... # pkg set -A 1 devel/cmake .... Once a package is a leaf package and is marked as automatic, it gets selected by `pkg autoremove`. Marking an installed package as _not_ automatic can be done using: [source,bash] .... # pkg set -A 0 devel/cmake .... [[pkgng-backup]] === Restoring the Package Database Unlike the traditional package management system, pkg includes its own package database backup mechanism. This functionality is enabled by default. [TIP] ==== To disable the periodic script from backing up the package database, set `daily_backup_pkgdb_enable="NO"` in man:periodic.conf[5]. ==== To restore the contents of a previous package database backup, run the following command replacing _/path/to/pkg.sql_ with the location of the backup: [source,bash] .... # pkg backup -r /path/to/pkg.sql .... [NOTE] ==== If restoring a backup taken by the periodic script, it must be decompressed prior to being restored. ==== To run a manual backup of the pkg database, run the following command, replacing _/path/to/pkg.sql_ with a suitable file name and location: [source,bash] .... # pkg backup -d /path/to/pkg.sql .... [[pkgng-clean]] === Removing Stale Packages By default, pkg stores binary packages in a cache directory defined by `PKG_CACHEDIR` in man:pkg.conf[5]. Only copies of the latest installed packages are kept. Older versions of pkg kept all previous packages. To remove these outdated binary packages, run: [source,bash] .... # pkg clean .... The entire cache may be cleared by running: [source,bash] .... # pkg clean -a .... [[pkgng-set]] === Modifying Package Metadata Software within the FreeBSD Ports Collection can undergo major version number changes. To address this, pkg has a built-in command to update package origins. This can be useful, for example, if package:lang/php5[] is renamed to package:lang/php53[] so that package:lang/php5[] can now represent version `5.4`. To change the package origin for the above example, run: [source,bash] .... # pkg set -o lang/php5:lang/php53 .... As another example, to update package:lang/ruby18[] to package:lang/ruby19[], run: [source,bash] .... # pkg set -o lang/ruby18:lang/ruby19 .... As a final example, to change the origin of the [.filename]#libglut# shared libraries from package:graphics/libglut[] to package:graphics/freeglut[], run: [source,bash] .... # pkg set -o graphics/libglut:graphics/freeglut .... [NOTE] ==== When changing package origins, it is important to reinstall packages that are dependent on the package with the modified origin. To force a reinstallation of dependent packages, run: [source,bash] .... # pkg install -Rf graphics/freeglut .... ==== [[ports-using]] == Using the Ports Collection The Ports Collection is a set of [.filename]#Makefiles#, patches, and description files. Each set of these files is used to compile and install an individual application on FreeBSD, and is called a _port_. By default, the Ports Collection itself is stored as a subdirectory of [.filename]#/usr/ports#. Before an application can be compiled using a port, the Ports Collection must first be installed. If it was not installed during the installation of FreeBSD, use one of the following methods to install it: [[ports-using-portsnap-method]] [.procedure] **** *Procedure: Portsnap Method* The base system of FreeBSD includes Portsnap. This is a fast and user-friendly tool for retrieving the Ports Collection and is the recommended choice for most users. This utility connects to a FreeBSD site, verifies the secure key, and downloads a new copy of the Ports Collection. The key is used to verify the integrity of all downloaded files. . To download a compressed snapshot of the Ports Collection into [.filename]#/var/db/portsnap#: + [source,bash] .... # portsnap fetch .... + . When running Portsnap for the first time, extract the snapshot into [.filename]#/usr/ports#: + [source,bash] .... # portsnap extract .... + . After the first use of Portsnap has been completed as shown above, [.filename]#/usr/ports# can be updated as needed by running: + [source,bash] .... # portsnap fetch # portsnap update .... + When using `fetch`, the `extract` or the `update` operation may be run consecutively, like so: + [source,bash] .... # portsnap fetch update .... **** [[ports-using-subversion-method]] [.procedure] **** *Procedure: Subversion Method* If more control over the ports tree is needed or if local changes need to be maintained, Subversion can be used to obtain the Ports Collection. Refer to link:{committers-guide}#subversion-primer[the Subversion Primer] for a detailed description of Subversion. . Subversion must be installed before it can be used to check out the ports tree. If a copy of the ports tree is already present, install Subversion like this: + [source,bash] .... # cd /usr/ports/devel/subversion # make install clean .... + If the ports tree is not available, or pkg is being used to manage packages, Subversion can be installed as a package: + [source,bash] .... # pkg install subversion .... + . Check out a copy of the ports tree: + [source,bash] .... # svn checkout https://svn.FreeBSD.org/ports/head /usr/ports .... + . As needed, update [.filename]#/usr/ports# after the initial Subversion checkout: + [source,bash] .... # svn update /usr/ports .... **** The Ports Collection contains directories for software categories. Inside each category are subdirectories for individual applications. Each application subdirectory contains a set of files that tells FreeBSD how to compile and install that program, called a _ports skeleton_. Each port skeleton includes these files and directories: * [.filename]#Makefile#: contains statements that specify how the application should be compiled and where its components should be installed. * [.filename]#distinfo#: contains the names and checksums of the files that must be downloaded to build the port. * [.filename]#files/#: this directory contains any patches needed for the program to compile and install on FreeBSD. This directory may also contain other files used to build the port. * [.filename]#pkg-descr#: provides a more detailed description of the program. * [.filename]#pkg-plist#: a list of all the files that will be installed by the port. It also tells the ports system which files to remove upon deinstallation. Some ports include [.filename]#pkg-message# or other files to handle special situations. For more details on these files, and on ports in general, refer to the link:{porters-handbook}[FreeBSD Porter's Handbook]. The port does not include the actual source code, also known as a [.filename]#distfile#. The extract portion of building a port will automatically save the downloaded source to [.filename]#/usr/ports/distfiles#. [[ports-skeleton]] === Installing Ports This section provides basic instructions on using the Ports Collection to install or remove software. The detailed description of available `make` targets and environment variables is available in man:ports[7]. [WARNING] ==== Before compiling any port, be sure to update the Ports Collection as described in the previous section. Since the installation of any third-party software can introduce security vulnerabilities, it is recommended to first check https://vuxml.freebsd.org/[] for known security issues related to the port. Alternately, run `pkg audit -F` before installing a new port. This command can be configured to automatically perform a security audit and an update of the vulnerability database during the daily security system check. For more information, refer to man:pkg-audit[8] and man:periodic[8]. ==== Using the Ports Collection assumes a working Internet connection. It also requires superuser privilege. To compile and install the port, change to the directory of the port to be installed, then type `make install` at the prompt. Messages will indicate the progress: [source,bash] .... # cd /usr/ports/sysutils/lsof # make install >> lsof_4.88D.freebsd.tar.gz doesn't seem to exist in /usr/ports/distfiles/. >> Attempting to fetch from ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/. ===> Extracting for lsof-4.88 ... [extraction output snipped] ... >> Checksum OK for lsof_4.88D.freebsd.tar.gz. ===> Patching for lsof-4.88.d,8 ===> Applying FreeBSD patches for lsof-4.88.d,8 ===> Configuring for lsof-4.88.d,8 ... [configure output snipped] ... ===> Building for lsof-4.88.d,8 ... [compilation output snipped] ... ===> Installing for lsof-4.88.d,8 ... [installation output snipped] ... ===> Generating temporary packing list ===> Compressing manual pages for lsof-4.88.d,8 ===> Registering installation for lsof-4.88.d,8 ===> SECURITY NOTE: This port has installed the following binaries which execute with increased privileges. /usr/local/sbin/lsof # .... Since `lsof` is a program that runs with increased privileges, a security warning is displayed as it is installed. Once the installation is complete, the prompt will be returned. Some shells keep a cache of the commands that are available in the directories listed in the `PATH` environment variable, to speed up lookup operations for the executable file of these commands. Users of the `tcsh` shell should type `rehash` so that a newly installed command can be used without specifying its full path. Use `hash -r` instead for the `sh` shell. Refer to the documentation for the shell for more information. During installation, a working subdirectory is created which contains all the temporary files used during compilation. Removing this directory saves disk space and minimizes the chance of problems later when upgrading to the newer version of the port: [source,bash] .... # make clean ===> Cleaning for lsof-88.d,8 # .... [NOTE] ==== To save this extra step, instead use `make install clean` when compiling the port. ==== ==== Customizing Ports Installation Some ports provide build options which can be used to enable or disable application components, provide security options, or allow for other customizations. Examples include package:www/firefox[], package:security/gpgme[], and package:mail/sylpheed-claws[]. If the port depends upon other ports which have configurable options, it may pause several times for user interaction as the default behavior is to prompt the user to select options from a menu. To avoid this and do all of the configuration in one batch, run `make config-recursive` within the port skeleton. Then, run `make install [clean]` to compile and install the port. [TIP] ==== When using `config-recursive`, the list of ports to configure are gathered by the `all-depends-list` target. It is recommended to run `make config-recursive` until all dependent ports options have been defined, and ports options screens no longer appear, to be certain that all dependency options have been configured. ==== There are several ways to revisit a port's build options menu in order to add, remove, or change these options after a port has been built. One method is to `cd` into the directory containing the port and type `make config`. Another option is to use `make showconfig`. Another option is to execute `make rmconfig` which will remove all selected options and allow you to start over. All of these options, and others, are explained in great detail in man:ports[7]. The ports system uses man:fetch[1] to download the source files, which supports various environment variables. The `FTP_PASSIVE_MODE`, `FTP_PROXY`, and `FTP_PASSWORD` variables may need to be set if the FreeBSD system is behind a firewall or FTP/HTTP proxy. See man:fetch[3] for the complete list of supported variables. For users who cannot be connected to the Internet all the time, `make fetch` can be run within [.filename]#/usr/ports#, to fetch all distfiles, or within a category, such as [.filename]#/usr/ports/net#, or within the specific port skeleton. Note that if a port has any dependencies, running this command in a category or ports skeleton will _not_ fetch the distfiles of ports from another category. Instead, use `make fetch-recursive` to also fetch the distfiles for all the dependencies of a port. In rare cases, such as when an organization has a local distfiles repository, the `MASTER_SITES` variable can be used to override the download locations specified in the [.filename]#Makefile#. When using, specify the alternate location: [source,bash] .... # cd /usr/ports/directory # make MASTER_SITE_OVERRIDE= \ ftp://ftp.organization.org/pub/FreeBSD/ports/distfiles/ fetch .... The `WRKDIRPREFIX` and `PREFIX` variables can override the default working and target directories. For example: [source,bash] .... # make WRKDIRPREFIX=/usr/home/example/ports install .... will compile the port in [.filename]#/usr/home/example/ports# and install everything under [.filename]#/usr/local#. [source,bash] .... # make PREFIX=/usr/home/example/local install .... will compile the port in [.filename]#/usr/ports# and install it in [.filename]#/usr/home/example/local#. And: [source,bash] .... # make WRKDIRPREFIX=../ports PREFIX=../local install .... will combine the two. These can also be set as environmental variables. Refer to the manual page for your shell for instructions on how to set an environmental variable. [[ports-removing]] === Removing Installed Ports Installed ports can be uninstalled using `pkg delete`. Examples for using this command can be found in the man:pkg-delete[8] manual page. Alternately, `make deinstall` can be run in the port's directory: [source,bash] .... # cd /usr/ports/sysutils/lsof # make deinstall ===> Deinstalling for sysutils/lsof ===> Deinstalling Deinstallation has been requested for the following 1 packages: lsof-4.88.d,8 The deinstallation will free 229 kB [1/1] Deleting lsof-4.88.d,8... done .... It is recommended to read the messages as the port is uninstalled. If the port has any applications that depend upon it, this information will be displayed but the uninstallation will proceed. In such cases, it may be better to reinstall the application in order to prevent broken dependencies. [[ports-upgrading]] === Upgrading Ports Over time, newer versions of software become available in the Ports Collection. This section describes how to determine which software can be upgraded and how to perform the upgrade. To determine if newer versions of installed ports are available, ensure that the latest version of the ports tree is installed, using the updating command described in either <> or <>. On FreeBSD 10 and later, or if the system has been converted to pkg, the following command will list the installed ports which are out of date: [source,bash] .... # pkg version -l "<" .... For FreeBSD 9._X_ and lower, the following command will list the installed ports that are out of date: [source,bash] .... # pkg_version -l "<" .... [IMPORTANT] ==== Before attempting an upgrade, read [.filename]#/usr/ports/UPDATING# from the top of the file to the date closest to the last time ports were upgraded or the system was installed. This file describes various issues and additional steps users may encounter and need to perform when updating a port, including such things as file format changes, changes in locations of configuration files, or any incompatibilities with previous versions. Make note of any instructions which match any of the ports that need upgrading and follow these instructions when performing the upgrade. ==== [[ports-upgrading-tools]] ==== Tools to Upgrade and Manage Ports The Ports Collection contains several utilities to perform the actual upgrade. Each has its strengths and weaknesses. Historically, most installations used either Portmaster or Portupgrade. Synth is a newer alternative. [NOTE] ==== The choice of which tool is best for a particular system is up to the system administrator. It is recommended practice to back up your data before using any of these tools. ==== [[portmaster]] ==== Upgrading Ports Using Portmaster package:ports-mgmt/portmaster[] is a very small utility for upgrading installed ports. It is designed to use the tools installed with the FreeBSD base system without depending on other ports or databases. To install this utility as a port: [source,bash] .... # cd /usr/ports/ports-mgmt/portmaster # make install clean .... Portmaster defines four categories of ports: * Root port: has no dependencies and is not a dependency of any other ports. * Trunk port: has no dependencies, but other ports depend upon it. * Branch port: has dependencies and other ports depend upon it. * Leaf port: has dependencies but no other ports depend upon it. To list these categories and search for updates: [source,bash] .... # portmaster -L ===>>> Root ports (No dependencies, not depended on) ===>>> ispell-3.2.06_18 ===>>> screen-4.0.3 ===>>> New version available: screen-4.0.3_1 ===>>> tcpflow-0.21_1 ===>>> 7 root ports ... ===>>> Branch ports (Have dependencies, are depended on) ===>>> apache22-2.2.3 ===>>> New version available: apache22-2.2.8 ... ===>>> Leaf ports (Have dependencies, not depended on) ===>>> automake-1.9.6_2 ===>>> bash-3.1.17 ===>>> New version available: bash-3.2.33 ... ===>>> 32 leaf ports ===>>> 137 total installed ports ===>>> 83 have new versions available .... This command is used to upgrade all outdated ports: [source,bash] .... # portmaster -a .... [NOTE] ==== By default, Portmaster makes a backup package before deleting the existing port. If the installation of the new version is successful, Portmaster deletes the backup. Using `-b` instructs Portmaster not to automatically delete the backup. Adding `-i` starts Portmaster in interactive mode, prompting for confirmation before upgrading each port. Many other options are available. Read through the manual page for man:portmaster[8] for details regarding their usage. ==== If errors are encountered during the upgrade process, add `-f` to upgrade and rebuild all ports: [source,bash] .... # portmaster -af .... Portmaster can also be used to install new ports on the system, upgrading all dependencies before building and installing the new port. To use this function, specify the location of the port in the Ports Collection: [source,bash] .... # portmaster shells/bash .... More information about package:ports-mgmt/portmaster[] may be found in its [.filename]#pkg-descr#. [[portupgrade]] ==== Upgrading Ports Using Portupgrade package:ports-mgmt/portupgrade[] is another utility that can be used to upgrade ports. It installs a suite of applications which can be used to manage ports. However, it is dependent upon Ruby. To install the port: [source,bash] .... # cd /usr/ports/ports-mgmt/portupgrade # make install clean .... Before performing an upgrade using this utility, it is recommended to scan the list of installed ports using `pkgdb -F` and to fix all the inconsistencies it reports. To upgrade all the outdated ports installed on the system, use `portupgrade -a`. Alternately, include `-i` to be asked for confirmation of every individual upgrade: [source,bash] .... # portupgrade -ai .... To upgrade only a specified application instead of all available ports, use `portupgrade _pkgname_`. It is very important to include `-R` to first upgrade all the ports required by the given application: [source,bash] .... # portupgrade -R firefox .... If `-P` is included, Portupgrade searches for available packages in the local directories listed in `PKG_PATH`. If none are available locally, it then fetches packages from a remote site. If packages can not be found locally or fetched remotely, Portupgrade will use ports. To avoid using ports entirely, specify `-PP`. This last set of options tells Portupgrade to abort if no packages are available: [source,bash] .... # portupgrade -PP gnome3 .... To just fetch the port distfiles, or packages, if `-P` is specified, without building or installing anything, use `-F`. For further information on all of the available switches, refer to the manual page for `portupgrade`. More information about package:ports-mgmt/portupgrade[] may be found in its [.filename]#pkg-descr#. [[ports-disk-space]] === Ports and Disk Space Using the Ports Collection will use up disk space over time. After building and installing a port, running `make clean` within the ports skeleton will clean up the temporary [.filename]#work# directory. If Portmaster is used to install a port, it will automatically remove this directory unless `-K` is specified. If Portupgrade is installed, this command will remove all [.filename]#work# directories found within the local copy of the Ports Collection: [source,bash] .... # portsclean -C .... In addition, outdated source distribution files accumulate in [.filename]#/usr/ports/distfiles# over time. To use Portupgrade to delete all the distfiles that are no longer referenced by any ports: [source,bash] .... # portsclean -D .... Portupgrade can remove all distfiles not referenced by any port currently installed on the system: [source,bash] .... # portsclean -DD .... If Portmaster is installed, use: [source,bash] .... # portmaster --clean-distfiles .... By default, this command is interactive and prompts the user to confirm if a distfile should be deleted. In addition to these commands, package:ports-mgmt/pkg_cutleaves[] automates the task of removing installed ports that are no longer needed. [[ports-poudriere]] == Building Packages with Poudriere Poudriere is a `BSD`-licensed utility for creating and testing FreeBSD packages. It uses FreeBSD jails to set up isolated compilation environments. These jails can be used to build packages for versions of FreeBSD that are different from the system on which it is installed, and also to build packages for i386 if the host is an amd64 system. Once the packages are built, they are in a layout identical to the official mirrors. These packages are usable by man:pkg[8] and other package management tools. Poudriere is installed using the package:ports-mgmt/poudriere[] package or port. The installation includes a sample configuration file [.filename]#/usr/local/etc/poudriere.conf.sample#. Copy this file to [.filename]#/usr/local/etc/poudriere.conf#. Edit the copied file to suit the local configuration. While `ZFS` is not required on the system running poudriere, it is beneficial. When `ZFS` is used, `ZPOOL` must be specified in [.filename]#/usr/local/etc/poudriere.conf# and `FREEBSD_HOST` should be set to a nearby mirror. Defining `CCACHE_DIR` enables the use of package:devel/ccache[] to cache compilation and reduce build times for frequently-compiled code. It may be convenient to put poudriere datasets in an isolated tree mounted at [.filename]#/poudriere#. Defaults for the other configuration values are adequate. The number of processor cores detected is used to define how many builds will run in parallel. Supply enough virtual memory, either with `RAM` or swap space. If virtual memory runs out, the compilation jails will stop and be torn down, resulting in weird error messages. [[poudriere-initialization]] === Initialize Jails and Port Trees After configuration, initialize poudriere so that it installs a jail with the required FreeBSD tree and a ports tree. Specify a name for the jail using `-j` and the FreeBSD version with `-v`. On systems running FreeBSD/amd64, the architecture can be set with `-a` to either `i386` or `amd64`. The default is the architecture shown by `uname`. [source,bash] .... # poudriere jail -c -j 11amd64 -v 11.4-RELEASE [00:00:00] Creating 11amd64 fs at /poudriere/jails/11amd64... done [00:00:00] Using pre-distributed MANIFEST for FreeBSD 11.4-RELEASE amd64 [00:00:00] Fetching base for FreeBSD 11.4-RELEASE amd64 /poudriere/jails/11amd64/fromftp/base.txz 125 MB 4110 kBps 31s [00:00:33] Extracting base... done [00:00:54] Fetching src for FreeBSD 11.4-RELEASE amd64 /poudriere/jails/11amd64/fromftp/src.txz 154 MB 4178 kBps 38s [00:01:33] Extracting src... done [00:02:31] Fetching lib32 for FreeBSD 11.4-RELEASE amd64 /poudriere/jails/11amd64/fromftp/lib32.txz 24 MB 3969 kBps 06s [00:02:38] Extracting lib32... done [00:02:42] Cleaning up... done [00:02:42] Recording filesystem state for clean... done [00:02:42] Upgrading using ftp /etc/resolv.conf -> /poudriere/jails/11amd64/etc/resolv.conf Looking up update.FreeBSD.org mirrors... 3 mirrors found. Fetching public key from update4.freebsd.org... done. Fetching metadata signature for 11.4-RELEASE from update4.freebsd.org... done. Fetching metadata index... done. Fetching 2 metadata files... done. Inspecting system... done. Preparing to download files... done. Fetching 124 patches.....10....20....30....40....50....60....70....80....90....100....110....120.. done. Applying patches... done. Fetching 6 files... done. The following files will be added as part of updating to 11.4-RELEASE-p1: /usr/src/contrib/unbound/.github /usr/src/contrib/unbound/.github/FUNDING.yml /usr/src/contrib/unbound/contrib/drop2rpz /usr/src/contrib/unbound/contrib/unbound_portable.service.in /usr/src/contrib/unbound/services/rpz.c /usr/src/contrib/unbound/services/rpz.h /usr/src/lib/libc/tests/gen/spawnp_enoexec.sh The following files will be updated as part of updating to 11.4-RELEASE-p1: […] -Installing updates...Scanning //usr/shared/certs/blacklisted for certificates... -Scanning //usr/shared/certs/trusted for certificates... +Installing updates...Scanning //usr/share/certs/blacklisted for certificates... +Scanning //usr/share/certs/trusted for certificates... done. 11.4-RELEASE-p1 [00:04:06] Recording filesystem state for clean... done [00:04:07] Jail 11amd64 11.4-RELEASE-p1 amd64 is ready to be used .... [source,bash] .... # poudriere ports -c -p local -m svn+https [00:00:00] Creating local fs at /poudriere/ports/local... done [00:00:00] Checking out the ports tree... done .... On a single computer, poudriere can build ports with multiple configurations, in multiple jails, and from different port trees. Custom configurations for these combinations are called _sets_. See the CUSTOMIZATION section of man:poudriere[8] for details after package:ports-mgmt/poudriere[] or package:ports-mgmt/poudriere-devel[] is installed. The basic configuration shown here puts a single jail-, port-, and set-specific [.filename]#make.conf# in [.filename]#/usr/local/etc/poudriere.d#. The filename in this example is created by combining the jail name, port name, and set name: [.filename]#10amd64-local-workstation-make.conf#. The system [.filename]#make.conf# and this new file are combined at build time to create the [.filename]#make.conf# used by the build jail. Packages to be built are entered in [.filename]#10amd64-local-workstation-pkglist#: [.programlisting] .... editors/emacs devel/git ports-mgmt/pkg ... .... Options and dependencies for the specified ports are configured: [source,bash] .... # poudriere options -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist .... Finally, packages are built and a package repository is created: [source,bash] .... # poudriere bulk -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist .... While running, pressing kbd:[Ctrl+t] displays the current state of the build. Poudriere also builds files in [.filename]#/poudriere/logs/bulk/jailname# that can be used with a web server to display build information. After completion, the new packages are now available for installation from the poudriere repository. For more information on using poudriere, see man:poudriere[8] and the main web site, https://github.com/freebsd/poudriere/wiki[]. === Configuring pkg Clients to Use a Poudriere Repository While it is possible to use both a custom repository along side of the official repository, sometimes it is useful to disable the official repository. This is done by creating a configuration file that overrides and disables the official configuration file. Create [.filename]#/usr/local/etc/pkg/repos/FreeBSD.conf# that contains the following: [.programlisting] .... FreeBSD: { enabled: no } .... Usually it is easiest to serve a poudriere repository to the client machines via HTTP. Set up a webserver to serve up the package directory, for instance: [.filename]#/usr/local/poudriere/data/packages/10amd64#, where [.filename]#10amd64# is the name of the build. If the URL to the package repository is: `http://pkg.example.com/10amd64`, then the repository configuration file in [.filename]#/usr/local/etc/pkg/repos/custom.conf# would look like: [.programlisting] .... custom: { url: "http://pkg.example.com/10amd64", enabled: yes, } .... [[ports-nextsteps]] == Post-Installation Considerations Regardless of whether the software was installed from a binary package or port, most third-party applications require some level of configuration after installation. The following commands and locations can be used to help determine what was installed with the application. * Most applications install at least one default configuration file in [.filename]#/usr/local/etc#. In cases where an application has a large number of configuration files, a subdirectory will be created to hold them. Often, sample configuration files are installed which end with a suffix such as [.filename]#.sample#. The configuration files should be reviewed and possibly edited to meet the system's needs. To edit a sample file, first copy it without the [.filename]#.sample# extension. * Applications which provide documentation will install it into [.filename]#/usr/local/shared/doc# and many applications also install manual pages. This documentation should be consulted before continuing. * Some applications run services which must be added to [.filename]#/etc/rc.conf# before starting the application. These applications usually install a startup script in [.filename]#/usr/local/etc/rc.d#. See crossref:config[configtuning-starting-services,Starting Services] for more information. + [NOTE] ==== By design, applications do not run their startup script upon installation, nor do they run their stop script upon deinstallation or upgrade. This decision is left to the individual system administrator. ==== * Users of man:csh[1] should run `rehash` to rebuild the known binary list in the shells `PATH`. * Use `pkg info` to determine which files, man pages, and binaries were installed with the application. [[ports-broken]] == Dealing with Broken Ports When a port does not build or install, try the following: . Search to see if there is a fix pending for the port in the link:https://www.FreeBSD.org/support/[Problem Report database]. If so, implementing the proposed fix may fix the issue. . Ask the maintainer of the port for help. Type `make maintainer` in the ports skeleton or read the port's [.filename]#Makefile# to find the maintainer's email address. Remember to include the `$FreeBSD:` line from the port's [.filename]#Makefile# and the output leading up to the error in the email to the maintainer. + [NOTE] ==== Some ports are not maintained by an individual but instead by a group maintainer represented by a link:{mailing-list-faq}[mailing list]. Many, but not all, of these addresses look like mailto:freebsd-listname@FreeBSD.org[freebsd-listname@FreeBSD.org]. Please take this into account when sending an email. In particular, ports maintained by mailto:ports@FreeBSD.org[ports@FreeBSD.org] are not maintained by a specific individual. Instead, any fixes and support come from the general community who subscribe to that mailing list. More volunteers are always needed! ==== + If there is no response to the email, use Bugzilla to submit a bug report using the instructions in link:{problem-reports}[Writing FreeBSD Problem Reports]. . Fix it! The link:{porters-handbook}[Porter's Handbook] includes detailed information on the ports infrastructure so that you can fix the occasional broken port or even submit your own! . Install the package instead of the port using the instructions in <>. diff --git a/documentation/content/en/books/handbook/ppp-and-slip/_index.adoc b/documentation/content/en/books/handbook/ppp-and-slip/_index.adoc index 0d058a254b..bb6502f17f 100644 --- a/documentation/content/en/books/handbook/ppp-and-slip/_index.adoc +++ b/documentation/content/en/books/handbook/ppp-and-slip/_index.adoc @@ -1,827 +1,827 @@ --- title: Chapter 28. PPP part: IV. Network Communication prev: books/handbook/serialcomms next: books/handbook/mail --- [[ppp-and-slip]] = PPP :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 28 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/ppp-and-slip/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/ppp-and-slip/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/ppp-and-slip/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[ppp-and-slip-synopsis]] == Synopsis FreeBSD supports the Point-to-Point (PPP) protocol which can be used to establish a network or Internet connection using a dial-up modem. This chapter describes how to configure modem-based communication services in FreeBSD. After reading this chapter, you will know: * How to configure, use, and troubleshoot a PPP connection. * How to set up PPP over Ethernet (PPPoE). * How to set up PPP over ATM (PPPoA). Before reading this chapter, you should: * Be familiar with basic network terminology. * Understand the basics and purpose of a dial-up connection and PPP. [[userppp]] == Configuring PPP FreeBSD provides built-in support for managing dial-up PPP connections using man:ppp[8]. The default FreeBSD kernel provides support for [.filename]#tun# which is used to interact with a modem hardware. Configuration is performed by editing at least one configuration file, and configuration files containing examples are provided. Finally, `ppp` is used to start and manage connections. In order to use a PPP connection, the following items are needed: * A dial-up account with an Internet Service Provider (ISP). * A dial-up modem. * The dial-up number for the ISP. * The login name and password assigned by the ISP. * The IP address of one or more DNS servers. Normally, the ISP provides these addresses. If it did not, FreeBSD can be configured to use DNS negotiation. If any of the required information is missing, contact the ISP. The following information may be supplied by the ISP, but is not necessary: * The IP address of the default gateway. If this information is unknown, the ISP will automatically provide the correct value during connection setup. When configuring PPP on FreeBSD, this address is referred to as `HISADDR`. * The subnet mask. If the ISP has not provided one, `255.255.255.255` will be used in the man:ppp[8] configuration file. * + If the ISP has assigned a static IP address and hostname, it should be input into the configuration file. Otherwise, this information will be automatically provided during connection setup. -The rest of this section demonstrates how to configure FreeBSD for common PPP connection scenarios. The required configuration file is [.filename]#/etc/ppp/ppp.conf# and additional files and examples are available in [.filename]#/usr/shared/examples/ppp/#. +The rest of this section demonstrates how to configure FreeBSD for common PPP connection scenarios. The required configuration file is [.filename]#/etc/ppp/ppp.conf# and additional files and examples are available in [.filename]#/usr/share/examples/ppp/#. [NOTE] ==== Throughout this section, many of the file examples display line numbers. These line numbers have been added to make it easier to follow the discussion and are not meant to be placed in the actual file. When editing a configuration file, proper indentation is important. Lines that end in a `:` start in the first column (beginning of the line) while all other lines should be indented as shown using spaces or tabs. ==== [[userppp-staticIP]] === Basic Configuration In order to configure a PPP connection, first edit [.filename]#/etc/ppp/ppp.conf# with the dial-in information for the ISP. This file is described as follows: [.programlisting] .... 1 default: 2 set log Phase Chat LCP IPCP CCP tun command 3 ident user-ppp VERSION 4 set device /dev/cuau0 5 set speed 115200 6 set dial "ABORT BUSY ABORT NO\\sCARRIER TIMEOUT 5 \ 7 \"\" AT OK-AT-OK ATE1Q0 OK \\dATDT\\T TIMEOUT 40 CONNECT" 8 set timeout 180 9 enable dns 10 11 provider: 12 set phone "(123) 456 7890" 13 set authname foo 14 set authkey bar 15 set timeout 300 16 set ifaddr x.x.x.x/0 y.y.y.y/0 255.255.255.255 0.0.0.0 17 add default HISADDR .... Line 1::: Identifies the `default` entry. Commands in this entry (lines 2 through 9) are executed automatically when `ppp` is run. Line 2::: Enables verbose logging parameters for testing the connection. Once the configuration is working satisfactorily, this line should be reduced to: + [.programlisting] .... set log phase tun .... Line 3::: Displays the version of man:ppp[8] to the PPP software running on the other side of the connection. Line 4::: Identifies the device to which the modem is connected, where [.filename]#COM1# is [.filename]#/dev/cuau0# and [.filename]#COM2# is [.filename]#/dev/cuau1#. Line 5::: Sets the connection speed. If `115200` does not work on an older modem, try `38400` instead. Lines 6 & 7::: The dial string written as an expect-send syntax. Refer to man:chat[8] for more information. + Note that this command continues onto the next line for readability. Any command in [.filename]#ppp.conf# may do this if the last character on the line is `\`. Line 8::: Sets the idle timeout for the link in seconds. Line 9::: Instructs the peer to confirm the DNS settings. If the local network is running its own DNS server, this line should be commented out, by adding a `#` at the beginning of the line, or removed. Line 10::: A blank line for readability. Blank lines are ignored by man:ppp[8]. Line 11::: Identifies an entry called `provider`. This could be changed to the name of the ISP so that `load _ISP_` can be used to start the connection. Line 12::: Use the phone number for the ISP. Multiple phone numbers may be specified using the colon (`:`) or pipe character (`|`) as a separator. To rotate through the numbers, use a colon. To always attempt to dial the first number first and only use the other numbers if the first number fails, use the pipe character. Always enclose the entire set of phone numbers between quotation marks (`"`) to prevent dialing failures. Lines 13 & 14::: Use the user name and password for the ISP. Line 15::: Sets the default idle timeout in seconds for the connection. In this example, the connection will be closed automatically after 300 seconds of inactivity. To prevent a timeout, set this value to zero. Line 16::: Sets the interface addresses. The values used depend upon whether a static IP address has been obtained from the ISP or if it instead negotiates a dynamic IP address during connection. + If the ISP has allocated a static IP address and default gateway, replace _x.x.x.x_ with the static IP address and replace _y.y.y.y_ with the IP address of the default gateway. If the ISP has only provided a static IP address without a gateway address, replace _y.y.y.y_ with `10.0.0.2/0`. + If the IP address changes whenever a connection is made, change this line to the following value. This tells man:ppp[8] to use the IP Configuration Protocol (IPCP) to negotiate a dynamic IP address: + [.programlisting] .... set ifaddr 10.0.0.1/0 10.0.0.2/0 255.255.255.255 0.0.0.0 .... Line 17::: Keep this line as-is as it adds a default route to the gateway. The `HISADDR` will automatically be replaced with the gateway address specified on line 16. It is important that this line appears after line 16. Depending upon whether man:ppp[8] is started manually or automatically, a [.filename]#/etc/ppp/ppp.linkup# may also need to be created which contains the following lines. This file is required when running `ppp` in `-auto` mode. This file is used after the connection has been established. At this point, the IP address will have been assigned and it is now possible to add the routing table entries. When creating this file, make sure that _provider_ matches the value demonstrated in line 11 of [.filename]#ppp.conf#. [.programlisting] .... provider: add default HISADDR .... -This file is also needed when the default gateway address is "guessed" in a static IP address configuration. In this case, remove line 17 from [.filename]#ppp.conf# and create [.filename]#/etc/ppp/ppp.linkup# with the above two lines. More examples for this file can be found in [.filename]#/usr/shared/examples/ppp/#. +This file is also needed when the default gateway address is "guessed" in a static IP address configuration. In this case, remove line 17 from [.filename]#ppp.conf# and create [.filename]#/etc/ppp/ppp.linkup# with the above two lines. More examples for this file can be found in [.filename]#/usr/share/examples/ppp/#. By default, `ppp` must be run as `root`. To change this default, add the account of the user who should run `ppp` to the `network` group in [.filename]#/etc/group#. Then, give the user access to one or more entries in [.filename]#/etc/ppp/ppp.conf# with `allow`. For example, to give `fred` and `mary` permission to only the `provider:` entry, add this line to the `provider:` section: [.programlisting] .... allow users fred mary .... To give the specified users access to all entries, put that line in the `default` section instead. === Advanced Configuration It is possible to configure PPP to supply DNS and NetBIOS nameserver addresses on demand. To enable these extensions with PPP version 1.x, the following lines might be added to the relevant section of [.filename]#/etc/ppp/ppp.conf#. [.programlisting] .... enable msext set ns 203.14.100.1 203.14.100.2 set nbns 203.14.100.5 .... And for PPP version 2 and above: [.programlisting] .... accept dns set dns 203.14.100.1 203.14.100.2 set nbns 203.14.100.5 .... This will tell the clients the primary and secondary name server addresses, and a NetBIOS nameserver host. In version 2 and above, if the `set dns` line is omitted, PPP will use the values found in [.filename]#/etc/resolv.conf#. [[userppp-PAPnCHAP]] ==== PAP and CHAP Authentication Some ISPs set their system up so that the authentication part of the connection is done using either of the PAP or CHAP authentication mechanisms. If this is the case, the ISP will not give a `login:` prompt at connection, but will start talking PPP immediately. PAP is less secure than CHAP, but security is not normally an issue here as passwords, although being sent as plain text with PAP, are being transmitted down a serial line only. There is not much room for crackers to "eavesdrop". The following alterations must be made: [.programlisting] .... 13 set authname MyUserName 14 set authkey MyPassword 15 set login .... Line 13::: This line specifies the PAP/CHAP user name. Insert the correct value for _MyUserName_. Line 14::: This line specifies the PAP/CHAP password. Insert the correct value for _MyPassword_. You may want to add an additional line, such as: + [.programlisting] .... 16 accept PAP .... + or + [.programlisting] .... 16 accept CHAP .... + to make it obvious that this is the intention, but PAP and CHAP are both accepted by default. Line 15::: The ISP will not normally require a login to the server when using PAP or CHAP. Therefore, disable the "set login" string. [[userppp-nat]] ==== Using PPP Network Address Translation Capability PPP has ability to use internal NAT without kernel diverting capabilities. This functionality may be enabled by the following line in [.filename]#/etc/ppp/ppp.conf#: [.programlisting] .... nat enable yes .... Alternatively, NAT may be enabled by command-line option `-nat`. There is also [.filename]#/etc/rc.conf# knob named `ppp_nat`, which is enabled by default. When using this feature, it may be useful to include the following [.filename]#/etc/ppp/ppp.conf# options to enable incoming connections forwarding: [.programlisting] .... nat port tcp 10.0.0.2:ftp ftp nat port tcp 10.0.0.2:http http .... or do not trust the outside at all [.programlisting] .... nat deny_incoming yes .... [[userppp-final]] === Final System Configuration While `ppp` is now configured, some edits still need to be made to [.filename]#/etc/rc.conf#. Working from the top down in this file, make sure the `hostname=` line is set: [.programlisting] .... hostname="foo.example.com" .... If the ISP has supplied a static IP address and name, use this name as the host name. Look for the `network_interfaces` variable. To configure the system to dial the ISP on demand, make sure the [.filename]#tun0# device is added to the list, otherwise remove it. [.programlisting] .... network_interfaces="lo0 tun0" ifconfig_tun0= .... [NOTE] ==== The `ifconfig_tun0` variable should be empty, and a file called [.filename]#/etc/start_if.tun0# should be created. This file should contain the line: [.programlisting] .... ppp -auto mysystem .... This script is executed at network configuration time, starting the ppp daemon in automatic mode. If this machine acts as a gateway, consider including `-alias`. Refer to the manual page for further details. ==== Make sure that the router program is set to `NO` with the following line in [.filename]#/etc/rc.conf#: [.programlisting] .... router_enable="NO" .... It is important that the `routed` daemon is not started, as `routed` tends to delete the default routing table entries created by `ppp`. It is probably a good idea to ensure that the `sendmail_flags` line does not include the `-q` option, otherwise `sendmail` will attempt to do a network lookup every now and then, possibly causing your machine to dial out. You may try: [.programlisting] .... sendmail_flags="-bd" .... The downside is that `sendmail` is forced to re-examine the mail queue whenever the ppp link. To automate this, include `!bg` in [.filename]#ppp.linkup#: [.programlisting] .... 1 provider: 2 delete ALL 3 add 0 0 HISADDR 4 !bg sendmail -bd -q30m .... An alternative is to set up a "dfilter" to block SMTP traffic. Refer to the sample files for further details. === Using `ppp` All that is left is to reboot the machine. After rebooting, either type: [source,bash] .... # ppp .... and then `dial provider` to start the PPP session, or, to configure `ppp` to establish sessions automatically when there is outbound traffic and [.filename]#start_if.tun0# does not exist, type: [source,bash] .... # ppp -auto provider .... It is possible to talk to the `ppp` program while it is running in the background, but only if a suitable diagnostic port has been set up. To do this, add the following line to the configuration: [.programlisting] .... set server /var/run/ppp-tun%d DiagnosticPassword 0177 .... This will tell PPP to listen to the specified UNIX(R) domain socket, asking clients for the specified password before allowing access. The `%d` in the name is replaced with the [.filename]#tun# device number that is in use. Once a socket has been set up, the man:pppctl[8] program may be used in scripts that wish to manipulate the running program. [[userppp-mgetty]] === Configuring Dial-in Services crossref:serialcomms[dialup,“Dial-in Service”] provides a good description on enabling dial-up services using man:getty[8]. An alternative to `getty` is package:comms/mgetty+sendfax[] port), a smarter version of `getty` designed with dial-up lines in mind. The advantages of using `mgetty` is that it actively _talks_ to modems, meaning if port is turned off in [.filename]#/etc/ttys# then the modem will not answer the phone. Later versions of `mgetty` (from 0.99beta onwards) also support the automatic detection of PPP streams, allowing clients scriptless access to the server. Refer to http://mgetty.greenie.net/doc/mgetty_toc.html[http://mgetty.greenie.net/doc/mgetty_toc.html] for more information on `mgetty`. By default the package:comms/mgetty+sendfax[] port comes with the `AUTO_PPP` option enabled allowing `mgetty` to detect the LCP phase of PPP connections and automatically spawn off a ppp shell. However, since the default login/password sequence does not occur it is necessary to authenticate users using either PAP or CHAP. This section assumes the user has successfully compiled, and installed the package:comms/mgetty+sendfax[] port on his system. Ensure that [.filename]#/usr/local/etc/mgetty+sendfax/login.config# has the following: [.programlisting] .... /AutoPPP/ - - /etc/ppp/ppp-pap-dialup .... This tells `mgetty` to run [.filename]#ppp-pap-dialup# for detected PPP connections. Create an executable file called [.filename]#/etc/ppp/ppp-pap-dialup# containing the following: [.programlisting] .... #!/bin/sh exec /usr/sbin/ppp -direct pap$IDENT .... For each dial-up line enabled in [.filename]#/etc/ttys#, create a corresponding entry in [.filename]#/etc/ppp/ppp.conf#. This will happily co-exist with the definitions we created above. [.programlisting] .... pap: enable pap set ifaddr 203.14.100.1 203.14.100.20-203.14.100.40 enable proxy .... Each user logging in with this method will need to have a username/password in [.filename]#/etc/ppp/ppp.secret#, or alternatively add the following option to authenticate users via PAP from [.filename]#/etc/passwd#. [.programlisting] .... enable passwdauth .... -To assign some users a static IP number, specify the number as the third argument in [.filename]#/etc/ppp/ppp.secret#. See [.filename]#/usr/shared/examples/ppp/ppp.secret.sample# for examples. +To assign some users a static IP number, specify the number as the third argument in [.filename]#/etc/ppp/ppp.secret#. See [.filename]#/usr/share/examples/ppp/ppp.secret.sample# for examples. [[ppp-troubleshoot]] == Troubleshooting PPP Connections This section covers a few issues which may arise when using PPP over a modem connection. Some ISPs present the `ssword` prompt while others present `password`. If the `ppp` script is not written accordingly, the login attempt will fail. The most common way to debug `ppp` connections is by connecting manually as described in this section. === Check the Device Nodes When using a custom kernel, make sure to include the following line in the kernel configuration file: [.programlisting] .... device uart .... The [.filename]#uart# device is already included in the `GENERIC` kernel, so no additional steps are necessary in this case. Just check the `dmesg` output for the modem device with: [source,bash] .... # dmesg | grep uart .... This should display some pertinent output about the [.filename]#uart# devices. These are the COM ports we need. If the modem acts like a standard serial port, it should be listed on [.filename]#uart1#, or [.filename]#COM2#. If so, a kernel rebuild is not required. When matching up, if the modem is on [.filename]#uart1#, the modem device would be [.filename]#/dev/cuau1#. === Connecting Manually Connecting to the Internet by manually controlling `ppp` is quick, easy, and a great way to debug a connection or just get information on how the ISP treats `ppp` client connections. Lets start PPP from the command line. Note that in all of our examples we will use _example_ as the hostname of the machine running PPP. To start `ppp`: [source,bash] .... # ppp .... [source,bash] .... ppp ON example> set device /dev/cuau1 .... This second command sets the modem device to [.filename]#cuau1#. [source,bash] .... ppp ON example> set speed 115200 .... This sets the connection speed to 115,200 kbps. [source,bash] .... ppp ON example> enable dns .... This tells `ppp` to configure the resolver and add the nameserver lines to [.filename]#/etc/resolv.conf#. If `ppp` cannot determine the hostname, it can manually be set later. [source,bash] .... ppp ON example> term .... This switches to "terminal" mode in order to manually control the modem. [.programlisting] .... deflink: Entering terminal mode on /dev/cuau1 type '~h' for help .... [source,bash] .... at OK atdt123456789 .... Use `at` to initialize the modem, then use `atdt` and the number for the ISP to begin the dial in process. [source,bash] .... CONNECT .... Confirmation of the connection, if we are going to have any connection problems, unrelated to hardware, here is where we will attempt to resolve them. [source,bash] .... ISP Login:myusername .... At this prompt, return the prompt with the username that was provided by the ISP. [source,bash] .... ISP Pass:mypassword .... At this prompt, reply with the password that was provided by the ISP. Just like logging into FreeBSD, the password will not echo. [source,bash] .... Shell or PPP:ppp .... Depending on the ISP, this prompt might not appear. If it does, it is asking whether to use a shell on the provider or to start `ppp`. In this example, `ppp` was selected in order to establish an Internet connection. [source,bash] .... Ppp ON example> .... Notice that in this example the first `p` has been capitalized. This shows that we have successfully connected to the ISP. [source,bash] .... Ppp ON example> .... We have successfully authenticated with our ISP and are waiting for the assigned IP address. [source,bash] .... PPP ON example> .... We have made an agreement on an IP address and successfully completed our connection. [source,bash] .... PPP ON example>add default HISADDR .... Here we add our default route, we need to do this before we can talk to the outside world as currently the only established connection is with the peer. If this fails due to existing routes, put a bang character `!` in front of the `add`. Alternatively, set this before making the actual connection and it will negotiate a new route accordingly. If everything went good we should now have an active connection to the Internet, which could be thrown into the background using kbd:[CTRL+z]. If `PPP` returns to `ppp` the connection has been lost. This is good to know because it shows the connection status. Capital P's represent a connection to the ISP and lowercase p's show that the connection has been lost. === Debugging If a connection cannot be established, turn hardware flow CTS/RTS to off using `set ctsrts off`. This is mainly the case when connected to some PPP-capable terminal servers, where PPP hangs when it tries to write data to the communication link, and waits for a Clear To Send (CTS) signal which may never come. When using this option, include `set accmap` as it may be required to defeat hardware dependent on passing certain characters from end to end, most of the time XON/XOFF. Refer to man:ppp[8] for more information on this option and how it is used. An older modem may need `set parity even`. Parity is set at none be default, but is used for error checking with a large increase in traffic, on older modems. PPP may not return to the command mode, which is usually a negotiation error where the ISP is waiting for negotiating to begin. At this point, using `~p` will force ppp to start sending the configuration information. If a login prompt never appears, PAP or CHAP authentication is most likely required. To use PAP or CHAP, add the following options to PPP before going into terminal mode: [source,bash] .... ppp ON example> set authname myusername .... Where _myusername_ should be replaced with the username that was assigned by the ISP. [source,bash] .... ppp ON example> set authkey mypassword .... Where _mypassword_ should be replaced with the password that was assigned by the ISP. If a connection is established, but cannot seem to find any domain name, try to man:ping[8] an IP address. If there is 100 percent (100%) packet loss, it is likely that a default route was not assigned. Double check that `add default HISADDR` was set during the connection. If a connection can be made to a remote IP address, it is possible that a resolver address has not been added to [.filename]#/etc/resolv.conf#. This file should look like: [.programlisting] .... domain example.com nameserver x.x.x.x nameserver y.y.y.y .... Where _x.x.x.x_ and _y.y.y.y_ should be replaced with the IP address of the ISP's DNS servers. To configure man:syslog[3] to provide logging for the PPP connection, make sure this line exists in [.filename]#/etc/syslog.conf#: [.programlisting] .... !ppp *.* /var/log/ppp.log .... [[pppoe]] == Using PPP over Ethernet (PPPoE) This section describes how to set up PPP over Ethernet (PPPoE). Here is an example of a working [.filename]#ppp.conf#: [.programlisting] .... default: set log Phase tun command # you can add more detailed logging if you wish set ifaddr 10.0.0.1/0 10.0.0.2/0 name_of_service_provider: set device PPPoE:xl1 # replace xl1 with your Ethernet device set authname YOURLOGINNAME set authkey YOURPASSWORD set dial set login add default HISADDR .... As `root`, run: [source,bash] .... # ppp -ddial name_of_service_provider .... Add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... ppp_enable="YES" ppp_mode="ddial" ppp_nat="YES" # if you want to enable nat for your local network, otherwise NO ppp_profile="name_of_service_provider" .... === Using a PPPoE Service Tag Sometimes it will be necessary to use a service tag to establish the connection. Service tags are used to distinguish between different PPPoE servers attached to a given network. Any required service tag information should be in the documentation provided by the ISP. As a last resort, one could try installing the package:net/rr-pppoe[] package or port. Bear in mind however, this may de-program your modem and render it useless, so think twice before doing it. Simply install the program shipped with the modem. Then, access the menu:System[] menu from the program. The name of the profile should be listed there. It is usually _ISP_. The profile name (service tag) will be used in the PPPoE configuration entry in [.filename]#ppp.conf# as the provider part for `set device`. Refer to man:ppp[8] for full details. It should look like this: [.programlisting] .... set device PPPoE:xl1:ISP .... Do not forget to change _xl1_ to the proper device for the Ethernet card. Do not forget to change _ISP_ to the profile. For additional information, refer to http://renaud.waldura.com/doc/freebsd/pppoe/[Cheaper Broadband with FreeBSD on DSL] by Renaud Waldura. [[ppp-3com]] === PPPoE with a 3Com(R) HomeConnect(TM) ADSL Modem Dual Link This modem does not follow the PPPoE specification defined in http://www.faqs.org/rfcs/rfc2516.html[RFC 2516]. In order to make FreeBSD capable of communicating with this device, a sysctl must be set. This can be done automatically at boot time by updating [.filename]#/etc/sysctl.conf#: [.programlisting] .... net.graph.nonstandard_pppoe=1 .... or can be done immediately with the command: [source,bash] .... # sysctl net.graph.nonstandard_pppoe=1 .... Unfortunately, because this is a system-wide setting, it is not possible to talk to a normal PPPoE client or server and a 3Com(R) HomeConnect(TM) ADSL Modem at the same time. [[pppoa]] == Using PPP over ATM (PPPoA) The following describes how to set up PPP over ATM (PPPoA). PPPoA is a popular choice among European DSL providers. === Using mpd The mpd application can be used to connect to a variety of services, in particular PPTP services. It can be installed using the package:net/mpd5[] package or port. Many ADSL modems require that a PPTP tunnel is created between the modem and computer. Once installed, configure mpd to suit the provider's settings. The port places a set of sample configuration files which are well documented in [.filename]#/usr/local/etc/mpd/#. A complete guide to configure mpd is available in HTML format in [.filename]#/usr/ports/shared/doc/mpd/#. Here is a sample configuration for connecting to an ADSL service with mpd. The configuration is spread over two files, first the [.filename]#mpd.conf#: [NOTE] ==== This example [.filename]#mpd.conf# only works with mpd 4.x. ==== [.programlisting] .... default: load adsl adsl: new -i ng0 adsl adsl set bundle authname username <.> set bundle password password <.> set bundle disable multilink set link no pap acfcomp protocomp set link disable chap set link accept chap set link keep-alive 30 10 set ipcp no vjcomp set ipcp ranges 0.0.0.0/0 0.0.0.0/0 set iface route default set iface disable on-demand set iface enable proxy-arp set iface idle 0 open .... <.> The username used to authenticate with your ISP. <.> The password used to authenticate with your ISP. Information about the link, or links, to establish is found in [.filename]#mpd.links#. An example [.filename]#mpd.links# to accompany the above example is given beneath: [.programlisting] .... adsl: set link type pptp set pptp mode active set pptp enable originate outcall set pptp self 10.0.0.1 <.> set pptp peer 10.0.0.138 <.> .... <.> The IP address of FreeBSD computer running mpd. <.> The IP address of the ADSL modem. The Alcatel SpeedTouch(TM) Home defaults to `10.0.0.138`. It is possible to initialize the connection easily by issuing the following command as `root`: [source,bash] .... # mpd -b adsl .... To view the status of the connection: [source,bash] .... % ifconfig ng0 ng0: flags=88d1 mtu 1500 inet 216.136.204.117 --> 204.152.186.171 netmask 0xffffffff .... Using mpd is the recommended way to connect to an ADSL service with FreeBSD. === Using pptpclient It is also possible to use FreeBSD to connect to other PPPoA services using package:net/pptpclient[]. To use package:net/pptpclient[] to connect to a DSL service, install the port or package, then edit [.filename]#/etc/ppp/ppp.conf#. An example section of [.filename]#ppp.conf# is given below. For further information on [.filename]#ppp.conf# options consult man:ppp[8]. [.programlisting] .... adsl: set log phase chat lcp ipcp ccp tun command set timeout 0 enable dns set authname username <.> set authkey password <.> set ifaddr 0 0 add default HISADDR .... <.> The username for the DSL provider. <.> The password for your account. [WARNING] ==== Since the account's password is added to [.filename]#ppp.conf# in plain text form, make sure nobody can read the contents of this file: [source,bash] .... # chown root:wheel /etc/ppp/ppp.conf # chmod 600 /etc/ppp/ppp.conf .... ==== This will open a tunnel for a PPP session to the DSL router. Ethernet DSL modems have a preconfigured LAN IP address to connect to. In the case of the Alcatel SpeedTouch(TM) Home, this address is `10.0.0.138`. The router's documentation should list the address the device uses. To open the tunnel and start a PPP session: [source,bash] .... # pptp address adsl .... [TIP] ==== If an ampersand ("&") is added to the end of this command, pptp will return the prompt. ==== A [.filename]#tun# virtual tunnel device will be created for interaction between the pptp and ppp processes. Once the prompt is returned, or the pptp process has confirmed a connection, examine the tunnel: [source,bash] .... % ifconfig tun0 tun0: flags=8051 mtu 1500 inet 216.136.204.21 --> 204.152.186.171 netmask 0xffffff00 Opened by PID 918 .... If the connection fails, check the configuration of the router, which is usually accessible using a web browser. Also, examine the output of `pptp` and the contents of the log file, [.filename]#/var/log/ppp.log# for clues. diff --git a/documentation/content/en/books/handbook/printing/_index.adoc b/documentation/content/en/books/handbook/printing/_index.adoc index a7ecd2529d..e230fcb75f 100644 --- a/documentation/content/en/books/handbook/printing/_index.adoc +++ b/documentation/content/en/books/handbook/printing/_index.adoc @@ -1,768 +1,768 @@ --- title: Chapter 9. Printing part: Part II. Common Tasks prev: books/handbook/kernelconfig next: books/handbook/linuxemu --- [[printing]] = Printing :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 9 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/printing/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/printing/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/printing/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] Putting information on paper is a vital function, despite many attempts to eliminate it. Printing has two basic components. The data must be delivered to the printer, and must be in a form that the printer can understand. [[printing-quick-start]] == Quick Start Basic printing can be set up quickly. The printer must be capable of printing plain `ASCII` text. For printing to other types of files, see <>. [.procedure] **** . Create a directory to store files while they are being printed: + [source,bash] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... + . As `root`, create [.filename]#/etc/printcap# with these contents: + [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ <.> :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs: .... + <.> This line is for a printer connected to a `USB` port. + For a printer connected to a parallel or "printer" port, use: + [.programlisting] .... :lp=/dev/lpt0:\ .... + For a printer connected directly to a network, use: + [.programlisting] .... :lp=:rm=network-printer-name:rp=raw:\ .... + Replace _network-printer-name_ with the `DNS` host name of the network printer. + . Enable LPD by editing [.filename]#/etc/rc.conf#, adding this line: + [.programlisting] .... lpd_enable="YES" .... + Start the service: + [source,bash] .... # service lpd start Starting lpd. .... + . Print a test: + [source,bash] .... # printf "1. This printer can print.\n2. This is the second line.\n" | lpr .... + [TIP] ==== If both lines do not start at the left border, but "stairstep" instead, see <>. ==== + Text files can now be printed with `lpr`. Give the filename on the command line, or pipe output directly into `lpr`. + [source,bash] .... % lpr textfile.txt % ls -lh | lpr .... **** [[printing-connections]] == Printer Connections Printers are connected to computer systems in a variety of ways. Small desktop printers are usually connected directly to a computer's `USB` port. Older printers are connected to a parallel or "printer" port. Some printers are directly connected to a network, making it easy for multiple computers to share them. A few printers use a rare serial port connection. FreeBSD can communicate with all of these types of printers. [[printing-connections-usb]] `USB`:: `USB` printers can be connected to any available `USB` port on the computer. + When FreeBSD detects a `USB` printer, two device entries are created: [.filename]#/dev/ulpt0# and [.filename]#/dev/unlpt0#. Data sent to either device will be relayed to the printer. After each print job, [.filename]#ulpt0# resets the `USB` port. Resetting the port can cause problems with some printers, so the [.filename]#unlpt0# device is usually used instead. [.filename]#unlpt0# does not reset the USB port at all. [[printing-connections-parallel]] Parallel (`IEEE`-1284):: The parallel port device is [.filename]#/dev/lpt0#. This device appears whether a printer is attached or not, it is not autodetected. + Vendors have largely moved away from these "legacy" ports, and many computers no longer have them. Adapters can be used to connect a parallel printer to a `USB` port. With such an adapter, the printer can be treated as if it were actually a `USB` printer. Devices called _print servers_ can also be used to connect parallel printers directly to a network. [[printing-connections-serial]] Serial (RS-232):: Serial ports are another legacy port, rarely used for printers except in certain niche applications. Cables, connectors, and required wiring vary widely. + For serial ports built into a motherboard, the serial device name is [.filename]#/dev/cuau0# or [.filename]#/dev/cuau1#. Serial `USB` adapters can also be used, and these will appear as [.filename]#/dev/cuaU0#. + Several communication parameters must be known to communicate with a serial printer. The most important are _baud rate_ or `BPS` (Bits Per Second) and _parity_. Values vary, but typical serial printers use a baud rate of 9600 and no parity. [[printing-connections-network]] Network:: Network printers are connected directly to the local computer network. + The `DNS` hostname of the printer must be known. If the printer is assigned a dynamic address by `DHCP`, `DNS` should be dynamically updated so that the host name always has the correct `IP` address. Network printers are often given static `IP` addresses to avoid this problem. + Most network printers understand print jobs sent with the LPD protocol. A print queue name can also be specified. Some printers process data differently depending on which queue is used. For example, a `raw` queue prints the data unchanged, while the `text` queue adds carriage returns to plain text. + Many network printers can also print data sent directly to port 9100. [[printing-connections-summary]] === Summary Wired network connections are usually the easiest to set up and give the fastest printing. For direct connection to the computer, `USB` is preferred for speed and simplicity. Parallel connections work but have limitations on cable length and speed. Serial connections are more difficult to configure. Cable wiring differs between models, and communication parameters like baud rate and parity bits must add to the complexity. Fortunately, serial printers are rare. [[printing-pdls]] == Common Page Description Languages Data sent to a printer must be in a language that the printer can understand. These languages are called Page Description Languages, or PDLs. [[print-pdls-ascii]] `ASCII`:: Plain `ASCII` text is the simplest way to send data to a printer. Characters correspond one to one with what will be printed: an `A` in the data prints an `A` on the page. Very little formatting is available. There is no way to select a font or proportional spacing. The forced simplicity of plain `ASCII` means that text can be printed straight from the computer with little or no encoding or translation. The printed output corresponds directly with what was sent. + Some inexpensive printers cannot print plain `ASCII` text. This makes them more difficult to set up, but it is usually still possible. [[print-pdls-postscript]] PostScript(R):: PostScript(R) is almost the opposite of `ASCII`. Rather than simple text, a PostScript(R) program is a set of instructions that draw the final document. Different fonts and graphics can be used. However, this power comes at a price. The program that draws the page must be written. Usually this program is generated by application software, so the process is invisible to the user. + Inexpensive printers sometimes leave out PostScript(R) compatibility as a cost-saving measure. [[print-pdls-pcl]] `PCL` (Printer Command Language):: `PCL` is an extension of `ASCII`, adding escape sequences for formatting, font selection, and printing graphics. Many printers provide `PCL5` support. Some support the newer `PCL6` or `PCLXL`. These later versions are supersets of `PCL5` and can provide faster printing. [[print-pdls-host-based]] Host-Based:: Manufacturers can reduce the cost of a printer by giving it a simple processor and very little memory. These printers are not capable of printing plain text. Instead, bitmaps of text and graphics are drawn by a driver on the host computer and then sent to the printer. These are called _host-based_ printers. + Communication between the driver and a host-based printer is often through proprietary or undocumented protocols, making them functional only on the most common operating systems. [[print-pdls-table]] === Converting PostScript(R) to Other PDLs Many applications from the Ports Collection and FreeBSD utilities produce PostScript(R) output. This table shows the utilities available to convert that into other common PDLs: [[print-pdls-ps-to-other-tbl]] .Output PDLs [cols="1,1,1", frame="none", options="header"] |=== <| Output PDL <| Generated By <| Notes |`PCL` or `PCL5` |package:print/ghostscript9-base[] |`-sDEVICE=ljet4` for monochrome, `-sDEVICE=cljet5` for color |`PCLXL` or `PCL6` |package:print/ghostscript9-base[] |`-sDEVICE=pxlmono` for monochrome, `-sDEVICE=pxlcolor` for color |`ESC/P2` |package:print/ghostscript9-base[] |`-sDEVICE=uniprint` |`XQX` |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === Summary For the easiest printing, choose a printer that supports PostScript(R). Printers that support `PCL` are the next preferred. With package:print/ghostscript9-base[], these printers can be used as if they understood PostScript(R) natively. Printers that support PostScript(R) or `PCL` directly almost always support direct printing of plain `ASCII` text files also. Line-based printers like typical inkjets usually do not support PostScript(R) or `PCL`. They often can print plain `ASCII` text files. package:print/ghostscript9-base[] supports the PDLs used by some of these printers. However, printing an entire graphic-based page on these printers is often very slow due to the large amount of data to be transferred and printed. Host-based printers are often more difficult to set up. Some cannot be used at all because of proprietary PDLs. Avoid these printers when possible. Descriptions of many PDLs can be found at http://www.undocprint.org/formats/page_description_languages[]. The particular `PDL` used by various models of printers can be found at http://www.openprinting.org/printers[]. [[printing-direct]] == Direct Printing For occasional printing, files can be sent directly to a printer device without any setup. For example, a file called [.filename]#sample.txt# can be sent to a `USB` printer: [source,bash] .... # cp sample.txt /dev/unlpt0 .... Direct printing to network printers depends on the abilities of the printer, but most accept print jobs on port 9100, and man:nc[1] can be used with them. To print the same file to a printer with the `DNS` hostname of _netlaser_: [source,bash] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (Line Printer Daemon) Printing a file in the background is called _spooling_. A spooler allows the user to continue with other programs on the computer without waiting for the printer to slowly complete the print job. FreeBSD includes a spooler called man:lpd[8]. Print jobs are submitted with man:lpr[1]. [[printing-lpd-setup]] === Initial Setup A directory for storing print jobs is created, ownership is set, and the permissions are set to prevent other users from viewing the contents of those files: [source,bash] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... Printers are defined in [.filename]#/etc/printcap#. An entry for each printer includes details like a name, the port where it is attached, and various other settings. Create [.filename]#/etc/printcap# with these contents: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> The name of this printer. man:lpr[1] sends print jobs to the `lp` printer unless another printer is specified with `-P`, so the default printer should be named `lp`. <.> The device where the printer is connected. Replace this line with the appropriate one for the connection type shown here. <.> Suppress the printing of a header page at the start of a print job. <.> Do not limit the maximum size of a print job. <.> The path to the spooling directory for this printer. Each printer uses its own spooling directory. <.> The log file where errors on this printer will be reported. After creating [.filename]#/etc/printcap#, use man:chkprintcap[8] to test it for errors: [source,bash] .... # chkprintcap .... Fix any reported problems before continuing. Enable man:lpd[8] in [.filename]#/etc/rc.conf#: [.programlisting] .... lpd_enable="YES" .... Start the service: [source,bash] .... # service lpd start .... [[printing-lpd-lpr]] === Printing with man:lpr[1] Documents are sent to the printer with `lpr`. A file to be printed can be named on the command line or piped into `lpr`. These two commands are equivalent, sending the contents of [.filename]#doc.txt# to the default printer: [source,bash] .... % lpr doc.txt % cat doc.txt | lpr .... Printers can be selected with `-P`. To print to a printer called _laser_: [source,bash] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === Filters The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly. Some printers are not capable of printing plain text, and the input file might not even be plain text. _Filters_ allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript(R) or `PCL`. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read. The filters discussed here are _input filters_ or _text filters_. These filters convert the incoming file into different forms. Use man:su[1] to become `root` before creating the files. Filters are specified in [.filename]#/etc/printcap# with the `if=` identifier. To use [.filename]#/usr/local/libexec/lf2crlf# as a filter, modify [.filename]#/etc/printcap# like this: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifies the _input filter_ that will be used on incoming text. [TIP] ==== The backslash _line continuation_ characters at the end of the lines in [.filename]#printcap# entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== Preventing Stairstepping on Plain Text Printers Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will "stairstep" on a standard printer: [.programlisting] .... A printed file looks like the steps of a staircase scattered by the wind .... A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create [.filename]#/usr/local/libexec/lf2crlf# with these contents: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Set the permissions and make it executable: [source,bash] .... # chmod 555 /usr/local/libexec/lf2crlf .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page. [[printing-lpd-filters-enscript]] ==== Fancy Plain Text on PostScript(R) Printers with package:print/enscript[] GNUEnscript converts plain text files into nicely-formatted PostScript(R) for printing on PostScript(R) printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either package:print/enscript-letter[] or package:print/enscript-a4[] from the Ports Collection. Create [.filename]#/usr/local/libexec/enscript# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Set the permissions and make it executable: [source,bash] .... # chmod 555 /usr/local/libexec/enscript .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Test the filter by printing a plain text file. [[printing-lpd-filters-ps2pcl]] ==== Printing PostScript(R) to `PCL` Printers Many programs produce PostScript(R) documents. However, inexpensive printers often only understand plain text or `PCL`. This filter converts PostScript(R) files to `PCL` before sending them to the printer. Install the Ghostscript PostScript(R) interpreter, package:print/ghostscript9-base[], from the Ports Collection. Create [.filename]#/usr/local/libexec/ps2pcl# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Set the permissions and make it executable: [source,bash] .... # chmod 555 /usr/local/libexec/ps2pcl .... PostScript(R) input sent to this script will be rendered and converted to `PCL` before being sent on to the printer. Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Test the filter by sending a small PostScript(R) program to it: [source,bash] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== Smart Filters A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript(R) file are usually `%!`. A filter can detect those two characters. PostScript(R) files can be sent on to a PostScript(R) printer unchanged. Text files can be converted to PostScript(R) with Enscript as shown earlier. Create [.filename]#/usr/local/libexec/psif# with these contents: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Set the permissions and make it executable: [source,bash] .... # chmod 555 /usr/local/libexec/psif .... Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Test the filter by printing PostScript(R) and plain text files. [[printing-lpd-filters-othersmart]] ==== Other Smart Filters Writing a filter that detects many different types of input and formats them correctly is challenging. package:print/apsfilter[] from the Ports Collection is a smart "magic" filter that detects dozens of file types and automatically converts them to the `PDL` understood by the printer. See http://www.apsfilter.org[] for more details. [[printing-lpd-queues]] === Multiple Queues The entries in [.filename]#/etc/printcap# are really definitions of _queues_. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed. As an example, consider a networked PostScript(R) laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript(R) files directly. Two entries can be created for the same printer in [.filename]#/etc/printcap#: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Documents sent to `textprinter` will be formatted by the [.filename]#/usr/local/libexec/enscript# filter shown in an earlier example. Advanced users can print PostScript(R) files on `psprinter`, where no filtering is done. This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file. [[printing-lpd-monitor]] === Monitoring and Controlling Printing Several utilities are available to monitor print jobs and check and control printer operation. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] man:lpq[1] shows the status of a user's print jobs. Print jobs from other users are not shown. Show the current user's pending jobs on a single printer: [source,bash] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Show the current user's pending jobs on all printers: [source,bash] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] man:lprm[1] is used to remove print jobs. Normal users are only allowed to remove their own jobs. `root` can remove any or all jobs. Remove all pending jobs from a printer: [source,bash] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Remove a single job from a printer. man:lpq[1] is used to find the job number. [source,bash] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] man:lpc[8] is used to check and modify printer status. `lpc` is followed by a command and an optional printer name. `all` can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with man:lpc[8]. Only `root` can use commands which modify printer status. Show the status of all printers: [source,bash] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Prevent a printer from accepting new jobs, then begin accepting new jobs again: [source,bash] .... # lpc disable lp lp: queuing disabled # lpc enable lp lp: queuing enabled .... Stop printing, but continue to accept new jobs. Then begin printing again: [source,bash] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Restart a printer after some error condition: [source,bash] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Turn the print queue off and disable printing, with a message to explain the problem to users: [source,bash] .... # lpc down lp Repair parts will arrive on Monday lp: printer and queuing disabled status message is now: Repair parts will arrive on Monday .... Re-enable a printer that is down: [source,bash] .... # lpc up lp lp: printing enabled daemon started .... See man:lpc[8] for more commands and options. [[printing-lpd-shared]] === Shared Printers Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient. [[printing-shared-aliases]] ==== Aliases The printer name is set in the first line of the entry in [.filename]#/etc/printcap#. Additional names, or _aliases_, can be added after that name. Aliases are separated from the name and each other by vertical bars: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with [source,bash] .... % lpr -Psalesprinter sales-report.txt .... Users in the Repairs department print to _their_ printer with [source,bash] .... % lpr -Prepairsprinter repairs-report.txt .... All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer. [[printing-shared-headers]] ==== Header Pages It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. _Header pages_ were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called _banner_ or _separator_ pages. Enabling header pages differs depending on whether the printer is connected directly to the computer with a `USB`, parallel, or serial cable, or is connected remotely over a network. -Header pages on directly-connected printers are enabled by removing the `:sh:\` (Suppress Header) line from the entry in [.filename]#/etc/printcap#. These header pages only use line feed characters for new lines. Some printers will need the [.filename]#/usr/shared/examples/printing/hpif# filter to prevent stairstepped text. The filter configures `PCL` printers to print both carriage returns and line feeds when a line feed is received. +Header pages on directly-connected printers are enabled by removing the `:sh:\` (Suppress Header) line from the entry in [.filename]#/etc/printcap#. These header pages only use line feed characters for new lines. Some printers will need the [.filename]#/usr/share/examples/printing/hpif# filter to prevent stairstepped text. The filter configures `PCL` printers to print both carriage returns and line feeds when a line feed is received. Header pages for network printers must be configured on the printer itself. Header page entries in [.filename]#/etc/printcap# are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser. [[printing-lpd-references]] === References -Example files: [.filename]#/usr/shared/examples/printing/#. +Example files: [.filename]#/usr/share/examples/printing/#. -The _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/shared/doc/smm/07.lpd/paper.ascii.gz#. +The _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/share/doc/smm/07.lpd/paper.ascii.gz#. Manual pages: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == Other Printing Systems Several other printing systems are available in addition to the built-in man:lpd[8]. These systems offer support for other protocols or additional features. [[printing-other-cups]] === CUPS (Common UNIX(R) Printing System) CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: link:{cups}[CUPS] [[printing-other-hplip]] === HPLIP Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is package:print/hplip[]. The main web page is at http://hplipopensource.com/hplip-web/index.html[]. The port handles all the installation details on FreeBSD. Configuration information is shown at http://hplipopensource.com/hplip-web/install/manual/hp_setup.html[]. [[printing-other-lprng]] === LPRng LPRng was developed as an enhanced alternative to man:lpd[8]. The port is package:sysutils/LPRng[]. For details and documentation, see http://www.lprng.com/[]. diff --git a/documentation/content/en/books/handbook/security/_index.adoc b/documentation/content/en/books/handbook/security/_index.adoc index 1efe19cf19..d07f9f0413 100644 --- a/documentation/content/en/books/handbook/security/_index.adoc +++ b/documentation/content/en/books/handbook/security/_index.adoc @@ -1,2127 +1,2127 @@ --- title: Chapter 14. Security part: Part III. System Administration prev: books/handbook/boot next: books/handbook/jails --- [[security]] = Security :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :skip-front-matter: :xrefstyle: basic :relfileprefix: ../ :outfilesuffix: :sectnumoffset: 14 ifeval::["{backend}" == "html5"] :imagesdir: ../../../../images/books/handbook/security/ endif::[] ifeval::["{backend}" == "pdf"] :imagesdir: ../../../../static/images/books/handbook/security/ endif::[] ifeval::["{backend}" == "epub3"] :imagesdir: ../../../../static/images/books/handbook/security/ endif::[] include::shared/authors.adoc[] include::shared/releases.adoc[] include::shared/en/mailing-lists.adoc[] include::shared/en/teams.adoc[] include::shared/en/urls.adoc[] toc::[] [[security-synopsis]] == Synopsis Security, whether physical or virtual, is a topic so broad that an entire industry has evolved around it. 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. After reading this chapter, you will know: * Basic FreeBSD system security concepts. * The various crypt mechanisms available in FreeBSD. * How to set up one-time password authentication. * How to configure TCP Wrapper for use with man:inetd[8]. * How to set up Kerberos on FreeBSD. * How to configure IPsec and create a VPN. * How to configure and use OpenSSH 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. Before reading this chapter, you should: * Understand basic FreeBSD and Internet concepts. Additional security topics are covered elsewhere in this Handbook. For example, Mandatory Access Control is discussed in crossref:mac[mac,Mandatory Access Control] and Internet firewalls are discussed in crossref:firewalls[firewalls,Firewalls]. [[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 (availablility). 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. The rest of this introduction describes how some of these basic security configurations are performed on a FreeBSD system. The rest of this chapter describes some specific tools which can be used when implementing a security policy on a FreeBSD system. [[security-accounts]] === Preventing Logins In securing a system, a good starting point is an audit of accounts. Ensure that `root` has a strong password and that this password is not shared. Disable any accounts that do not need login access. To deny login access to accounts, two methods exist. The first is to lock the account. This example locks the `toor` account: [source,bash] .... # pw lock toor .... The second method is to prevent login access by changing the shell to [.filename]#/usr/sbin/nologin#. Only the superuser can change the shell for other users: [source,bash] .... # chsh -s /usr/sbin/nologin toor .... The [.filename]#/usr/sbin/nologin# shell prevents the system from assigning a shell to the user when they attempt to login. [[security-accountmgmt]] === Permitted Account Escalation In some cases, system administration needs to be shared with other users. FreeBSD has two methods to handle this. The first one, which is not recommended, is a shared root password used by members of the `wheel` group. With this method, a user types `su` and enters the password for `wheel` whenever superuser access is needed. The user should then type `exit` to leave privileged access after finishing the commands that required administrative access. To add a user to this group, edit [.filename]#/etc/group# and add the user to the end of the `wheel` entry. The user must be separated by a comma character with no space. The second, and recommended, method to permit privilege escalation is to install the package:security/sudo[] package or port. This software provides additional auditing, more fine-grained user control, and can be configured to lock users into running only the specified privileged commands. After installation, use `visudo` to edit [.filename]#/usr/local/etc/sudoers#. This example creates a new `webadmin` group, adds the `trhodes` account to that group, and configures that group access to restart package:apache24[]: [source,bash] .... # pw groupadd webadmin -M trhodes -g 6000 # visudo %webadmin ALL=(ALL) /usr/sbin/service apache24 * .... [[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 the DES, MD5, SHA256, SHA512, and Blowfish hash algorithms in its `crypt()` library. 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 `dru` 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,bash] .... # grep dru /etc/master.passwd dru:$6$pzIjSvCAn.PBYQBA$PXpSeWPx3g5kscj3IMiM7tUEUSPmGexxta.8Lt9TGSi2lNQqYGKszsBPuGME0:1001:1001::0:0:dru:/usr/home/dru:/bin/csh .... The hash mechanism is set in the user's login class. For this example, the user is in the `default` login class and the hash algorithm is set with this line in [.filename]#/etc/login.conf#: [.programlisting] .... :passwd_format=sha512:\ .... To change the algorithm to Blowfish, modify that line to look like this: [.programlisting] .... :passwd_format=blf:\ .... Then run `cap_mkdb /etc/login.conf` as described in <>. 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. For remote logins, two-factor authentication should be used. An example of two-factor authentication is "something you have", such as a key, and "something you know", such as the passphrase for that key. Since OpenSSH is part of the FreeBSD base system, all network logins should be over an encrypted connection and use key-based authentication instead of passwords. For more information, refer to <>. Kerberos users may need to make additional changes to implement OpenSSH in their network. These changes are described in <>. [[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 [.filename]#pam_passwdqc.so# 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 .... This example sets several requirements for new passwords. The `min` setting controls the minimum password length. It has five values because this module defines five different types of passwords based on their complexity. Complexity is defined by the type of characters that must exist in a password, such as letters, numbers, symbols, and case. The types of passwords are described in man:pam_passwdqc[8]. In this example, the first three types of passwords are disabled, meaning that passwords that meet those complexity requirements will not be accepted, regardless of their length. The `12` sets a minimum password policy of at least twelve characters, if the password also contains characters with three types of complexity. The `10` sets the password policy to also allow passwords of at least ten characters, if the password contains characters with four types of complexity. The `similar` setting denies passwords that are similar to the user's previous password. The `retry` setting provides a user with three opportunities to enter a new password. Once this file is saved, a user changing their password will see a message similar to the following: [source,bash] .... % passwd Changing local password for trhodes Old Password: You can now choose the new password. A valid password should be a mix of upper and lower case letters, digits and other characters. You can use a 12 character long password with characters from at least 3 of these 4 classes, or a 10 character long password containing characters from all the classes. Characters that form a common pattern are discarded by the check. Alternatively, if 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. Most password policies require passwords to expire after so many days. To set a password age time in FreeBSD, set `passwordtime` for 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 run `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,bash] .... # pw usermod -p 30-apr-2015 -n trhodes .... As seen here, an expiration date is set in the form of day, month, and year. For more information, see man:pw[8]. [[security-rkhunter]] === Detecting Rootkits A _rootkit_ is any unauthorized software that attempts to gain `root` access to a system. Once installed, this malicious software will normally open up another avenue of entry for an attacker. Realistically, once a system has been compromised by a rootkit and an investigation has been performed, the system should be reinstalled from scratch. There is tremendous risk that even the most prudent security or systems engineer will miss something an attacker left behind. A rootkit does do one thing useful for administrators: once detected, it is a sign that a compromise happened at some point. But, these types of applications tend to be very well hidden. This section demonstrates a tool that can be used to detect rootkits, package:security/rkhunter[]. After installation of this package or port, the system may be checked using the following command. It will produce a lot of information and will require some manual pressing of kbd:[ENTER]: [source,bash] .... # rkhunter -c .... After the process completes, a status message will be printed to the screen. This message will include the amount of files checked, suspect files, possible rootkits, and more. During the check, some generic security warnings may be produced about hidden files, the OpenSSH protocol selection, and known vulnerable versions of installed software. These can be handled now or after a more detailed analysis has been performed. Every administrator should know what is running on the systems they are responsible for. Third-party tools like rkhunter and package:sysutils/lsof[], and native commands such as `netstat` and `ps`, can show a great deal of information on the system. Take notes on what is normal, ask questions when something seems out of place, and be paranoid. While preventing a compromise is ideal, detecting a compromise is a must. [[security-ids]] === Binary Verification 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. 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 rsync server. The built-in `mtree` 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. The following example generates a set of SHA256 hashes, one for each system binary in [.filename]#/bin#, and saves those values to a hidden file in ``root``'s home directory, [.filename]#/root/.bin_chksum_mtree#: [source,bash] .... # mtree -s 3483151339707503 -c -K cksum,sha256digest -p /bin > /root/.bin_chksum_mtree # mtree: /bin checksum: 3427012225 .... The _3483151339707503_ represents the seed. This value should be remembered, but not shared. Viewing [.filename]#/root/.bin_cksum_mtree# should yield output similar to the following: [.programlisting] .... # user: root # machine: dreadnaught # tree: /bin # date: Mon Feb 3 10:19:53 2014 # . /set type=file uid=0 gid=0 mode=0555 nlink=1 flags=none . type=dir mode=0755 nlink=2 size=1024 \ time=1380277977.000000000 \133 nlink=2 size=11704 time=1380277977.000000000 \ cksum=484492447 \ sha256digest=6207490fbdb5ed1904441fbfa941279055c3e24d3a4049aeb45094596400662a cat size=12096 time=1380277975.000000000 cksum=3909216944 \ sha256digest=65ea347b9418760b247ab10244f47a7ca2a569c9836d77f074e7a306900c1e69 chflags size=8168 time=1380277975.000000000 cksum=3949425175 \ sha256digest=c99eb6fc1c92cac335c08be004a0a5b4c24a0c0ef3712017b12c89a978b2dac3 chio size=18520 time=1380277975.000000000 cksum=2208263309 \ sha256digest=ddf7c8cb92a58750a675328345560d8cc7fe14fb3ccd3690c34954cbe69fc964 chmod size=8640 time=1380277975.000000000 cksum=2214429708 \ sha256digest=a435972263bf814ad8df082c0752aa2a7bdd8b74ff01431ccbd52ed1e490bbe7 .... The machine's hostname, the date and time the specification was created, and the name of the user who created the specification are included in this report. There is a checksum, size, time, and SHA256 digest for each binary in the directory. 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,bash] .... # mtree -s 3483151339707503 -p /bin < /root/.bin_chksum_mtree >> /root/.bin_chksum_output # mtree: /bin checksum: 3427012225 .... 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]#/root/.bin_chksum_output# output file will be empty. To simulate a change, change the date on [.filename]#/bin/cat# using `touch` and run the verification command again: [source,bash] .... # touch /bin/cat # mtree -s 3483151339707503 -p /bin < /root/.bin_chksum_mtree >> /root/.bin_chksum_output # more /root/.bin_chksum_output cat changed modification time expected Fri Sep 27 06:32:55 2013 found Mon Feb 3 10:28:43 2014 .... 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#. More advanced IDS systems exist, such as package:security/aide[]. In most cases, `mtree` provides the functionality administrators need. It is important to keep the seed value and the checksum output hidden from malicious users. More information about `mtree` can be found in man:mtree[8]. [[security-tuning]] === System Tuning for Security In FreeBSD, many system features can be tuned using `sysctl`. A few of the security features which can be tuned to prevent Denial of Service (DoS) attacks will be covered in this section. More information about using `sysctl`, including how to temporarily change values and how to make the changes permanent after testing, can be found in crossref:config[configtuning-sysctl,“Tuning with sysctl(8)”]. [NOTE] ==== Any time a setting is changed with `sysctl`, the chance to cause undesired harm is increased, affecting the availability of the system. All changes should be monitored and, if possible, tried on a testing system before being used on a production system. ==== By default, the FreeBSD kernel boots with a security level of `-1`. This is called "insecure mode" because immutable file flags may be turned off and all devices may be read from or written to. The security level will remain at `-1` unless it is altered through `sysctl` or by a setting in the startup scripts. The security level may be increased during system startup by setting `kern_securelevel_enable` to `YES` in [.filename]#/etc/rc.conf#, and the value of `kern_securelevel` to the desired security level. See man:security[7] and man:init[8] for more information on these settings and the available security levels. [WARNING] ==== Increasing the `securelevel` can break Xorg and cause other issues. Be prepared to do some debugging. ==== The `net.inet.tcp.blackhole` and `net.inet.udp.blackhole` settings can be used to drop incoming SYN packets on closed ports without sending a return RST response. The default behavior is to return an RST to show a port is closed. Changing the default provides some level of protection against ports scans, which are used to determine which applications are running on a system. Set `net.inet.tcp.blackhole` to `2` and `net.inet.udp.blackhole` to `1`. Refer to man:blackhole[4] for more information about these settings. The `net.inet.icmp.drop_redirect` and `net.inet.ip.redirect` settings help prevent against _redirect attacks_. A redirect attack is a type of DoS which sends mass numbers of ICMP type 5 packets. Since these packets are not required, set `net.inet.icmp.drop_redirect` to `1` and set `net.inet.ip.redirect` to `0`. Source routing is a method for detecting and accessing non-routable addresses on the internal network. This should be disabled as non-routable addresses are normally not routable on purpose. To disable this feature, set `net.inet.ip.sourceroute` and `net.inet.ip.accept_sourceroute` to `0`. When a machine on the network needs to send messages to all hosts on a subnet, an ICMP echo request message is sent to the broadcast address. However, there is no reason for an external host to perform such an action. To reject all external broadcast requests, set `net.inet.icmp.bmcastecho` to `0`. Some additional settings are documented in man:security[7]. [[one-time-passwords]] == One-time Passwords By default, FreeBSD includes support for One-time Passwords In Everything (OPIE). OPIE is designed to prevent replay attacks, in which an attacker discovers a user's password and uses it to access a system. Since a password is only used once in OPIE, a discovered password is of little use to an attacker. OPIE uses a secure hash and a challenge/response system to manage passwords. The FreeBSD implementation uses the MD5 hash by default. OPIE uses three different types of passwords. The first is the usual UNIX(R) or Kerberos password. The second is the one-time password which is generated by `opiekey`. The third type of password is the "secret password" which is used to generate one-time passwords. The secret password has nothing to do with, and should be different from, the UNIX(R) password. There are two other pieces of data that are important to OPIE. One is the "seed" or "key", consisting of two letters and five digits. The other is the "iteration count", a number between 1 and 100. OPIE creates the one-time password by concatenating the seed and the secret password, applying the MD5 hash as many times as specified by the iteration count, and turning the result into six short English words which represent the one-time password. The authentication system keeps track of the last one-time password used, and the user is authenticated if the hash of the user-provided password is equal to the previous password. Since a one-way hash is used, it is impossible to generate future one-time passwords if a successfully used password is captured. The iteration count is decremented after each successful login to keep the user and the login program in sync. When the iteration count gets down to `1`, OPIE must be reinitialized. There are a few programs involved in this process. A one-time password, or a consecutive list of one-time passwords, is generated by passing an iteration count, a seed, and a secret password to man:opiekey[1]. In addition to initializing OPIE, man:opiepasswd[1] is used to change passwords, iteration counts, or seeds. The relevant credential files in [.filename]#/etc/opiekeys# are examined by man:opieinfo[1] which prints out the invoking user's current iteration count and seed. This section describes four different sorts of operations. The first is how to set up one-time-passwords for the first time over a secure connection. The second is how to use `opiepasswd` over an insecure connection. The third is how to log in over an insecure connection. The fourth is how to generate a number of keys which can be written down or printed out to use at insecure locations. === Initializing OPIE To initialize OPIE for the first time, run this command from a secure location: [source,bash] .... % opiepasswd -c Adding unfurl: Only use this method from the console; NEVER from remote. If you are using telnet, xterm, or a dial-in, type ^C now or exit with no password. Then run opiepasswd without the -c parameter. Using MD5 to compute responses. Enter new secret pass phrase: Again new secret pass phrase: ID unfurl OTP key is 499 to4268 MOS MALL GOAT ARM AVID COED .... The `-c` sets console mode which assumes that the command is being run from a secure location, such as a computer under the user's control or an SSH session to a computer under the user's control. When prompted, enter the secret password which will be used to generate the one-time login keys. This password should be difficult to guess and should be different than the password which is associated with the user's login account. It must be between 10 and 127 characters long. Remember this password. The `ID` line lists the login name (`unfurl`), default iteration count (`499`), and default seed (`to4268`). When logging in, the system will remember these parameters and display them, meaning that they do not have to be memorized. The last line lists the generated one-time password which corresponds to those parameters and the secret password. At the next login, use this one-time password. === Insecure Connection Initialization To initialize or change the secret password on an insecure system, a secure connection is needed to some place where `opiekey` can be run. This might be a shell prompt on a trusted machine. An iteration count is needed, where 100 is probably a good value, and the seed can either be specified or the randomly-generated one used. On the insecure connection, the machine being initialized, use man:opiepasswd[1]: [source,bash] .... % opiepasswd Updating unfurl: You need the response from an OTP generator. Old secret pass phrase: otp-md5 498 to4268 ext Response: GAME GAG WELT OUT DOWN CHAT New secret pass phrase: otp-md5 499 to4269 Response: LINE PAP MILK NELL BUOY TROY ID mark OTP key is 499 gr4269 LINE PAP MILK NELL BUOY TROY .... To accept the default seed, press kbd:[Return]. Before entering an access password, move over to the secure connection and give it the same parameters: [source,bash] .... % opiekey 498 to4268 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: GAME GAG WELT OUT DOWN CHAT .... Switch back over to the insecure connection, and copy the generated one-time password over to the relevant program. === Generating a Single One-time Password After initializing OPIE and logging in, a prompt like this will be displayed: [source,bash] .... % telnet example.com Trying 10.0.0.1... Connected to example.com Escape character is '^]'. FreeBSD/i386 (example.com) (ttypa) login: otp-md5 498 gr4269 ext Password: .... The OPIE prompts provides a useful feature. If kbd:[Return] is pressed at the password prompt, the prompt will turn echo on and display what is typed. This can be useful when attempting to type in a password by hand from a printout. At this point, generate the one-time password to answer this login prompt. This must be done on a trusted system where it is safe to run man:opiekey[1]. There are versions of this command for Windows(R), Mac OS(R) and FreeBSD. This command needs the iteration count and the seed as command line options. Use cut-and-paste from the login prompt on the machine being logged in to. On the trusted system: [source,bash] .... % opiekey 498 to4268 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: GAME GAG WELT OUT DOWN CHAT .... Once the one-time password is generated, continue to log in. === Generating Multiple One-time Passwords Sometimes there is no access to a trusted machine or secure connection. In this case, it is possible to use man:opiekey[1] to generate a number of one-time passwords beforehand. For example: [source,bash] .... % opiekey -n 5 30 zz99999 Using the MD5 algorithm to compute response. Reminder: Do not use opiekey from telnet or dial-in sessions. Enter secret pass phrase: 26: JOAN BORE FOSS DES NAY QUIT 27: LATE BIAS SLAY FOLK MUCH TRIG 28: SALT TIN ANTI LOON NEAL USE 29: RIO ODIN GO BYE FURY TIC 30: GREW JIVE SAN GIRD BOIL PHI .... The `-n 5` requests five keys in sequence, and `30` specifies what the last iteration number should be. Note that these are printed out in _reverse_ order of use. The really paranoid might want to write the results down by hand; otherwise, print the list. Each line shows both the iteration count and the one-time password. Scratch off the passwords as they are used. === Restricting Use of UNIX(R) Passwords OPIE can restrict the use of UNIX(R) passwords based on the IP address of a login session. The relevant file is [.filename]#/etc/opieaccess#, which is present by default. Refer to man:opieaccess[5] for more information on this file and which security considerations to be aware of when using it. Here is a sample [.filename]#opieaccess#: [.programlisting] .... permit 192.168.0.0 255.255.0.0 .... This line allows users whose IP source address (which is vulnerable to spoofing) matches the specified value and mask, to use UNIX(R) passwords at any time. If no rules in [.filename]#opieaccess# are matched, the default is to deny non-OPIE logins. [[tcpwrappers]] == TCP Wrapper TCP Wrapper is a host-based access control system which extends the abilities of crossref:network-servers[network-inetd,“The inetd Super-Server”]. It can be configured to provide logging support, return messages, and connection restrictions for the server daemons under the control of inetd. Refer to man:tcpd[8] for more information about TCP Wrapper and its features. TCP Wrapper should not be considered a replacement for a properly configured firewall. Instead, TCP Wrapper should be used in conjunction with a firewall and other security enhancements in order to provide another layer of protection in the implementation of a security policy. === Initial Configuration To enable TCP Wrapper in FreeBSD, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... inetd_enable="YES" inetd_flags="-Ww" .... Then, properly configure [.filename]#/etc/hosts.allow#. [NOTE] ==== Unlike other implementations of TCP Wrapper, 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 Wrapper uses a first rule match semantic, meaning that the configuration file is scanned from the beginning for a matching rule. When a match is found, the rule is applied and the search process stops. For example, to allow POP3 connections via the package:mail/qpopper[] daemon, the following lines should be appended to [.filename]#hosts.allow#: [.programlisting] .... # This line is required for POP3 connections: qpopper : ALL : allow .... Whenever this file is edited, restart inetd: [source,bash] .... # service inetd restart .... === Advanced Configuration TCP Wrapper provides advanced options to allow more control over the way connections are handled. In some cases, it may be appropriate to return a comment to certain hosts or daemon connections. In other cases, a log entry should be recorded or an email sent to the administrator. Other situations may require the use of a service for local connections only. This is all possible through the use of configuration options known as wildcards, expansion characters, and external command execution. Suppose that a situation occurs where a connection should be denied yet a reason should be sent to the host who attempted to establish that connection. That action is possible with `twist`. When a connection attempt is made, `twist` executes a shell command or script. An example exists in [.filename]#hosts.allow#: [.programlisting] .... # The rest of the daemons are protected. ALL : ALL \ : severity auth.info \ : twist /bin/echo "You are not welcome to use %d from %h." .... In this example, the message "You are not allowed to use _daemon name_ from _hostname_." will be returned for any daemon not configured in [.filename]#hosts.allow#. This is useful for sending a reply back to the connection initiator right after the established connection is dropped. Any message returned _must_ be wrapped in quote (`"`) characters. [WARNING] ==== It may be possible to launch a denial of service attack on the server if an attacker floods these daemons with connection requests. ==== Another possibility is to use `spawn`. Like `twist`, `spawn` implicitly denies the connection and may be used to run external shell commands or scripts. Unlike `twist`, `spawn` will not send a reply back to the host who established the connection. For example, consider the following configuration: [.programlisting] .... # We do not allow connections from example.com: ALL : .example.com \ : spawn (/bin/echo %a from %h attempted to access %d >> \ /var/log/connections.log) \ : deny .... This will deny all connection attempts from `*.example.com` and log the hostname, IP address, and the daemon to which access was attempted to [.filename]#/var/log/connections.log#. This example uses the substitution characters `%a` and `%h`. Refer to man:hosts_access[5] for the complete list. To match every instance of a daemon, domain, or IP address, use `ALL`. Another wildcard is `PARANOID` which may be used to match any host which provides an IP address that may be forged because the IP address differs from its resolved hostname. In this example, all connection requests to Sendmail which have an IP address that varies from its hostname will be denied: [.programlisting] .... # Block possibly spoofed requests to sendmail: sendmail : PARANOID : deny .... [CAUTION] ==== Using the `PARANOID` wildcard will result in denied connections if the client or server has a broken DNS setup. ==== To learn more about wildcards and their associated functionality, refer to man:hosts_access[5]. [NOTE] ==== When adding new configuration lines, make sure that any unneeded entries for that daemon are commented out in [.filename]#hosts.allow#. ==== [[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,bash] .... # pkg install heimdal .... Next, update [.filename]#/etc/rc.conf# using `sysrc` as follows: [source,bash] .... # 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,bash] .... # kstash 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,bash] .... # 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,bash] .... kadmin> add tillman 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,bash] .... # 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,bash] .... % kinit tillman tillman@EXAMPLE.ORG's Password: .... Confirm that a ticket was successfully obtained using `klist`: [source,bash] .... % klist 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,bash] .... % 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,bash] .... # kadmin 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,bash] .... # kadmin 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, the following edits should also be made to [.filename]#rc.conf#: [.programlisting] .... kdc_program="/usr/local/sbin/kdc" kadmind_program="/usr/local/sbin/kadmind" kdc_flags="" kdc_enable="YES" 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/shared/dict/words# might be useful. +* 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] [[openssl]] == OpenSSL OpenSSL is an open source implementation of the SSL and TLS protocols. It provides an encryption transport layer on top of the normal communications layer, allowing it to be intertwined with many network applications and services. The version of OpenSSL included in FreeBSD supports the Secure Sockets Layer 3.0 (SSLv3) and Transport Layer Security 1.0/1.1/1.2 (TLSv1/TLSv1.1/TLSv1.2) network security protocols and can be used as a general cryptographic library. In FreeBSD 12.0-RELEASE and above, OpenSSL also supports Transport Layer Security 1.3 (TLSv1.3). OpenSSL is often used to encrypt authentication of mail clients and to secure web based transactions such as credit card payments. Some ports, such as package:www/apache24[] and package:databases/postgresql11-server[], include a compile option for building with OpenSSL. If selected, the port will add support using OpenSSL from the base system. To instead have the port compile against OpenSSL from the package:security/openssl[] port, add the following to [.filename]#/etc/make.conf#: [.programlisting] .... DEFAULT_VERSIONS+= ssl=openssl .... Another common use of OpenSSL is to provide certificates for use with software applications. Certificates can be used to verify the credentials of a company or individual. If a certificate has not been signed by an external _Certificate Authority_ (CA), such as http://www.verisign.com[http://www.verisign.com], the application that uses the certificate will produce a warning. There is a cost associated with obtaining a signed certificate and using a signed certificate is not mandatory as certificates can be self-signed. However, using an external authority will prevent warnings and can put users at ease. This section demonstrates how to create and use certificates on a FreeBSD system. Refer to crossref:network-servers[ldap-config,“Configuring an LDAP Server”] for an example of how to create a CA for signing one's own certificates. For more information about SSL, read the free https://www.feistyduck.com/books/openssl-cookbook/[OpenSSL Cookbook]. === Generating Certificates To generate a certificate that will be signed by an external CA, issue the following command and input the information requested at the prompts. This input information will be written to the certificate. At the `Common Name` prompt, input the fully qualified name for the system that will use the certificate. If this name does not match the server, the application verifying the certificate will issue a warning to the user, rendering the verification provided by the certificate as useless. [source,bash] .... # openssl req -new -nodes -out req.pem -keyout cert.key -sha256 -newkey rsa:2048 Generating a 2048 bit 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]:US State or Province Name (full name) [Some-State]:PA Locality Name (eg, city) []:Pittsburgh Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company Organizational Unit Name (eg, section) []:Systems Administrator Common Name (eg, YOUR name) []:localhost.example.org Email Address []:trhodes@FreeBSD.org Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:Another Name .... Other options, such as the expire time and alternate encryption algorithms, are available when creating a certificate. A complete list of options is described in man:openssl[1]. This command will create two files in the current directory. The certificate request, [.filename]#req.pem#, can be sent to a CA who will validate the entered credentials, sign the request, and return the signed certificate. The second file, [.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. Alternately, if a signature from a CA is not required, a self-signed certificate can be created. First, generate the RSA key: [source,bash] .... # openssl genrsa -rand -genkey -out cert.key 2048 0 semi-random bytes loaded Generating RSA private key, 2048 bit long modulus .............................................+++ .................................................................................................................+++ e is 65537 (0x10001) .... Use this key to create a self-signed certificate. Follow the usual prompts for creating a certificate: [source,bash] .... # openssl req -new -x509 -days 365 -key cert.key -out cert.crt -sha256 You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:PA Locality Name (eg, city) []:Pittsburgh Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company Organizational Unit Name (eg, section) []:Systems Administrator Common Name (e.g. server FQDN or YOUR name) []:localhost.example.org Email Address []:trhodes@FreeBSD.org .... This will create two new files in the current directory: a 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`. === Using Certificates One use for a certificate is to encrypt connections to the Sendmail mail server in order to prevent the use of clear text authentication. [NOTE] ==== Some mail clients will display an error if the user has not installed a local copy of the certificate. Refer to the documentation included with the software for more information on certificate installation. ==== In FreeBSD 10.0-RELEASE and above, it is possible to create a self-signed certificate for Sendmail automatically. To enable this, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... sendmail_enable="YES" sendmail_cert_create="YES" sendmail_cert_cn="localhost.example.org" .... This will automatically create a self-signed certificate, [.filename]#/etc/mail/certs/host.cert#, a signing key, [.filename]#/etc/mail/certs/host.key#, and a CA certificate, [.filename]#/etc/mail/certs/cacert.pem#. The certificate will use the `Common Name` specified in `sendmail_cert_cn`. After saving the edits, restart Sendmail: [source,bash] .... # service sendmail restart .... If all went well, there will be no error messages in [.filename]#/var/log/maillog#. For a simple test, connect to the mail server's listening port using `telnet`: [source,bash] .... # telnet example.com 25 Trying 192.0.34.166... Connected to example.com. Escape character is '^]'. 220 example.com ESMTP Sendmail 8.14.7/8.14.7; Fri, 18 Apr 2014 11:50:32 -0400 (EDT) ehlo example.com 250-example.com Hello example.com [192.0.34.166], pleased to meet you 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-8BITMIME 250-SIZE 250-DSN 250-ETRN 250-AUTH LOGIN PLAIN 250-STARTTLS 250-DELIVERBY 250 HELP quit 221 2.0.0 example.com closing connection Connection closed by foreign host. .... If the `STARTTLS` line appears in the output, everything is working correctly. [[ipsec]] == VPN over IPsec Internet Protocol Security (IPsec) is a set of protocols which sit on top of the Internet Protocol (IP) layer. It allows two or more hosts to communicate in a secure manner by authenticating and encrypting each IP packet of a communication session. The FreeBSD IPsec network stack is based on the http://www.kame.net/[http://www.kame.net/] implementation and supports both IPv4 and IPv6 sessions. IPsec is comprised of the following sub-protocols: * _Encapsulated Security Payload (ESP)_: this protocol protects the IP packet data from third party interference by encrypting the contents using symmetric cryptography algorithms such as Blowfish and 3DES. * _Authentication Header (AH)_: this protocol protects the IP packet header from third party interference and spoofing by computing a cryptographic checksum and hashing the IP packet header fields with a secure hashing function. This is then followed by an additional header that contains the hash, to allow the information in the packet to be authenticated. * _IP Payload Compression Protocol (IPComp_): this protocol tries to increase communication performance by compressing the IP payload in order to reduce the amount of data sent. These protocols can either be used together or separately, depending on the environment. IPsec supports two modes of operation. The first mode, _Transport Mode_, protects communications between two hosts. The second mode, _Tunnel Mode_, is used to build virtual tunnels, commonly known as Virtual Private Networks (VPNs). Consult man:ipsec[4] for detailed information on the IPsec subsystem in FreeBSD. IPsec support is enabled by default on FreeBSD 11 and later. For previous versions of FreeBSD, add these options to a custom kernel configuration file and rebuild the kernel using the instructions in crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]: [source,bash] .... options IPSEC IP security device crypto .... If IPsec debugging support is desired, the following kernel option should also be added: [source,bash] .... options IPSEC_DEBUG debug for IP security .... This rest of this chapter demonstrates the process of setting up an IPsecVPN between a home network and a corporate network. In the example scenario: * Both sites are connected to the Internet through a gateway that is running FreeBSD. * The gateway on each network has at least one external IP address. In this example, the corporate LAN's external IP address is `172.16.5.4` and the home LAN's external IP address is `192.168.1.12`. * The internal addresses of the two networks can be either public or private IP addresses. However, the address space must not collide. For example, both networks cannot use `192.168.1.x`. In this example, the corporate LAN's internal IP address is `10.246.38.1` and the home LAN's internal IP address is `10.0.0.5`. === Configuring a VPN on FreeBSD To begin, package:security/ipsec-tools[] must be installed from the Ports Collection. This software provides a number of applications which support the configuration. The next requirement is to create two man:gif[4] pseudo-devices which will be used to tunnel packets and allow both networks to communicate properly. As `root`, run the following commands, replacing _internal_ and _external_ with the real IP addresses of the internal and external interfaces of the two gateways: [source,bash] .... # ifconfig gif0 create # ifconfig gif0 internal1 internal2 # ifconfig gif0 tunnel external1 external2 .... Verify the setup on each gateway, using `ifconfig`. Here is the output from Gateway 1: [.programlisting] .... gif0: flags=8051 mtu 1280 tunnel inet 172.16.5.4 --> 192.168.1.12 inet6 fe80::2e0:81ff:fe02:5881%gif0 prefixlen 64 scopeid 0x6 inet 10.246.38.1 --> 10.0.0.5 netmask 0xffffff00 .... Here is the output from Gateway 2: [.programlisting] .... gif0: flags=8051 mtu 1280 tunnel inet 192.168.1.12 --> 172.16.5.4 inet 10.0.0.5 --> 10.246.38.1 netmask 0xffffff00 inet6 fe80::250:bfff:fe3a:c1f%gif0 prefixlen 64 scopeid 0x4 .... Once complete, both internal IP addresses should be reachable using man:ping[8]: [source,bash] .... priv-net# ping 10.0.0.5 PING 10.0.0.5 (10.0.0.5): 56 data bytes 64 bytes from 10.0.0.5: icmp_seq=0 ttl=64 time=42.786 ms 64 bytes from 10.0.0.5: icmp_seq=1 ttl=64 time=19.255 ms 64 bytes from 10.0.0.5: icmp_seq=2 ttl=64 time=20.440 ms 64 bytes from 10.0.0.5: icmp_seq=3 ttl=64 time=21.036 ms --- 10.0.0.5 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max/stddev = 19.255/25.879/42.786/9.782 ms corp-net# ping 10.246.38.1 PING 10.246.38.1 (10.246.38.1): 56 data bytes 64 bytes from 10.246.38.1: icmp_seq=0 ttl=64 time=28.106 ms 64 bytes from 10.246.38.1: icmp_seq=1 ttl=64 time=42.917 ms 64 bytes from 10.246.38.1: icmp_seq=2 ttl=64 time=127.525 ms 64 bytes from 10.246.38.1: icmp_seq=3 ttl=64 time=119.896 ms 64 bytes from 10.246.38.1: icmp_seq=4 ttl=64 time=154.524 ms --- 10.246.38.1 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 28.106/94.594/154.524/49.814 ms .... As expected, both sides have the ability to send and receive ICMP packets from the privately configured addresses. Next, both gateways must be told how to route packets in order to correctly send traffic from either network. The following commands will achieve this goal: [source,bash] .... corp-net# route add 10.0.0.0 10.0.0.5 255.255.255.0 corp-net# route add net 10.0.0.0: gateway 10.0.0.5 priv-net# route add 10.246.38.0 10.246.38.1 255.255.255.0 priv-net# route add host 10.246.38.0: gateway 10.246.38.1 .... At this point, internal machines should be reachable from each gateway as well as from machines behind the gateways. Again, use man:ping[8] to confirm: [source,bash] .... corp-net# ping 10.0.0.8 PING 10.0.0.8 (10.0.0.8): 56 data bytes 64 bytes from 10.0.0.8: icmp_seq=0 ttl=63 time=92.391 ms 64 bytes from 10.0.0.8: icmp_seq=1 ttl=63 time=21.870 ms 64 bytes from 10.0.0.8: icmp_seq=2 ttl=63 time=198.022 ms 64 bytes from 10.0.0.8: icmp_seq=3 ttl=63 time=22.241 ms 64 bytes from 10.0.0.8: icmp_seq=4 ttl=63 time=174.705 ms --- 10.0.0.8 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.870/101.846/198.022/74.001 ms priv-net# ping 10.246.38.107 PING 10.246.38.1 (10.246.38.107): 56 data bytes 64 bytes from 10.246.38.107: icmp_seq=0 ttl=64 time=53.491 ms 64 bytes from 10.246.38.107: icmp_seq=1 ttl=64 time=23.395 ms 64 bytes from 10.246.38.107: icmp_seq=2 ttl=64 time=23.865 ms 64 bytes from 10.246.38.107: icmp_seq=3 ttl=64 time=21.145 ms 64 bytes from 10.246.38.107: icmp_seq=4 ttl=64 time=36.708 ms --- 10.246.38.107 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.145/31.721/53.491/12.179 ms .... Setting up the tunnels is the easy part. Configuring a secure link is a more in depth process. The following configuration uses pre-shared (PSK) RSA keys. Other than the IP addresses, the [.filename]#/usr/local/etc/racoon/racoon.conf# on both gateways will be identical and look similar to: [.programlisting] .... path pre_shared_key "/usr/local/etc/racoon/psk.txt"; #location of pre-shared key file log debug; #log verbosity setting: set to 'notify' when testing and debugging is complete padding # options are not to be changed { maximum_length 20; randomize off; strict_check off; exclusive_tail off; } timer # timing options. change as needed { counter 5; interval 20 sec; persend 1; # natt_keepalive 15 sec; phase1 30 sec; phase2 15 sec; } listen # address [port] that racoon will listen on { isakmp 172.16.5.4 [500]; isakmp_natt 172.16.5.4 [4500]; } remote 192.168.1.12 [500] { exchange_mode main,aggressive; doi ipsec_doi; situation identity_only; my_identifier address 172.16.5.4; peers_identifier address 192.168.1.12; lifetime time 8 hour; passive off; proposal_check obey; # nat_traversal off; generate_policy off; proposal { encryption_algorithm blowfish; hash_algorithm md5; authentication_method pre_shared_key; lifetime time 30 sec; dh_group 1; } } sainfo (address 10.246.38.0/24 any address 10.0.0.0/24 any) # address $network/$netmask $type address $network/$netmask $type ( $type being any or esp) { # $network must be the two internal networks you are joining. pfs_group 1; lifetime time 36000 sec; encryption_algorithm blowfish,3des; authentication_algorithm hmac_md5,hmac_sha1; compression_algorithm deflate; } .... For descriptions of each available option, refer to the manual page for [.filename]#racoon.conf#. The Security Policy Database (SPD) needs to be configured so that FreeBSD and racoon are able to encrypt and decrypt network traffic between the hosts. This can be achieved with a shell script, similar to the following, on the corporate gateway. This file will be used during system initialization and should be saved as [.filename]#/usr/local/etc/racoon/setkey.conf#. [.programlisting] .... flush; spdflush; # To the home network spdadd 10.246.38.0/24 10.0.0.0/24 any -P out ipsec esp/tunnel/172.16.5.4-192.168.1.12/use; spdadd 10.0.0.0/24 10.246.38.0/24 any -P in ipsec esp/tunnel/192.168.1.12-172.16.5.4/use; .... Once in place, racoon may be started on both gateways using the following command: [source,bash] .... # /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf -l /var/log/racoon.log .... The output should be similar to the following: [source,bash] .... corp-net# /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf Foreground mode. 2006-01-30 01:35:47: INFO: begin Identity Protection mode. 2006-01-30 01:35:48: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:35:55: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:36:04: INFO: ISAKMP-SA established 172.16.5.4[500]-192.168.1.12[500] spi:623b9b3bd2492452:7deab82d54ff704a 2006-01-30 01:36:05: INFO: initiate new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=28496098(0x1b2d0e2) 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=47784998(0x2d92426) 2006-01-30 01:36:13: INFO: respond new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=124397467(0x76a279b) 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=175852902(0xa7b4d66) .... To ensure the tunnel is working properly, switch to another console and use man:tcpdump[1] to view network traffic using the following command. Replace `em0` with the network interface card as required: [source,bash] .... # tcpdump -i em0 host 172.16.5.4 and dst 192.168.1.12 .... Data similar to the following should appear on the console. If not, there is an issue and debugging the returned data will be required. [.programlisting] .... 01:47:32.021683 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xa) 01:47:33.022442 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xb) 01:47:34.024218 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xc) .... At this point, both networks should be available and seem to be part of the same network. Most likely both networks are protected by a firewall. To allow traffic to flow between them, rules need to be added to pass packets. For the man:ipfw[8] firewall, add the following lines to the firewall configuration file: [.programlisting] .... ipfw add 00201 allow log esp from any to any ipfw add 00202 allow log ah from any to any ipfw add 00203 allow log ipencap from any to any ipfw add 00204 allow log udp from any 500 to any .... [NOTE] ==== The rule numbers may need to be altered depending on the current host configuration. ==== For users of man:pf[4] or man:ipf[8], the following rules should do the trick: [.programlisting] .... pass in quick proto esp from any to any pass in quick proto ah from any to any pass in quick proto ipencap from any to any pass in quick proto udp from any port = 500 to any port = 500 pass in quick on gif0 from any to any pass out quick proto esp from any to any pass out quick proto ah from any to any pass out quick proto ipencap from any to any pass out quick proto udp from any port = 500 to any port = 500 pass out quick on gif0 from any to any .... Finally, to allow the machine to start support for the VPN during system initialization, add the following lines to [.filename]#/etc/rc.conf#: [.programlisting] .... ipsec_enable="YES" ipsec_program="/usr/local/sbin/setkey" ipsec_file="/usr/local/etc/racoon/setkey.conf" # allows setting up spd policies on boot racoon_enable="yes" .... [[openssh]] == OpenSSH OpenSSH is a set of network connectivity tools used to provide secure access to remote machines. Additionally, TCP/IP connections can be tunneled or forwarded securely through SSH connections. OpenSSH encrypts all traffic to effectively eliminate eavesdropping, connection hijacking, and other network-level attacks. OpenSSH is maintained by the OpenBSD project and is installed by default in FreeBSD. It is compatible with both SSH version 1 and 2 protocols. When data is sent over the network in an unencrypted form, network sniffers anywhere in between the client and server can steal user/password information or data transferred during the session. OpenSSH offers a variety of authentication and encryption methods to prevent this from happening. More information about OpenSSH is available from http://www.openssh.com/[http://www.openssh.com/]. This section provides an overview of the built-in client utilities to securely access other systems and securely transfer files from a FreeBSD system. It then describes how to configure a SSH server on a FreeBSD system. More information is available in the man pages mentioned in this chapter. === Using the SSH Client Utilities To log into a SSH server, use `ssh` and specify a username that exists on that server and the IP address or hostname of the server. If this is the first time a connection has been made to the specified server, the user will be prompted to first verify the server's fingerprint: [source,bash] .... # ssh user@example.com The authenticity of host 'example.com (10.0.0.1)' can't be established. ECDSA key fingerprint is 25:cc:73:b5:b3:96:75:3d:56:19:49:d2:5c:1f:91:3b. Are you sure you want to continue connecting (yes/no)? yes Permanently added 'example.com' (ECDSA) to the list of known hosts. Password for user@example.com: user_password .... SSH utilizes a key fingerprint system to verify the authenticity of the server when the client connects. When the user accepts the key's fingerprint by typing `yes` when connecting for the first time, a copy of the key is saved to [.filename]#.ssh/known_hosts# in the user's home directory. Future attempts to login are verified against the saved key and `ssh` will display an alert if the server's key does not match the saved key. If this occurs, the user should first verify why the key has changed before continuing with the connection. By default, recent versions of OpenSSH only accept SSHv2 connections. By default, the client will use version 2 if possible and will fall back to version 1 if the server does not support version 2. To force `ssh` to only use the specified protocol, include `-1` or `-2`. Additional options are described in man:ssh[1]. Use man:scp[1] to securely copy a file to or from a remote machine. This example copies [.filename]#COPYRIGHT# on the remote system to a file of the same name in the current directory of the local system: [source,bash] .... # scp user@example.com:/COPYRIGHT COPYRIGHT Password for user@example.com: ******* COPYRIGHT 100% |*****************************| 4735 00:00 # .... Since the fingerprint was already verified for this host, the server's key is automatically checked before prompting for the user's password. The arguments passed to `scp` are similar to `cp`. The file or files to copy is the first argument and the destination to copy to is the second. Since the file is fetched over the network, one or more of the file arguments takes the form `user@host:`. Be aware when copying directories recursively that `scp` uses `-r`, whereas `cp` uses `-R`. To open an interactive session for copying files, use `sftp`. Refer to man:sftp[1] for a list of available commands while in an `sftp` session. [[security-ssh-keygen]] ==== Key-based Authentication Instead of using passwords, a client can be configured to connect to the remote machine using keys. To generate RSA authentication keys, use `ssh-keygen`. To generate a public and private key pair, specify the type of key and follow the prompts. It is recommended to protect the keys with a memorable, but hard to guess passphrase. [source,bash] .... % ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/user/.ssh/id_rsa): 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]-----+ .... <.> Type a passphrase here. It can contain spaces and symbols. <.> Retype the passphrase to verify it. 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] ==== Many users believe that keys are secure by design and will use a key without a passphrase. This is _dangerous_ behavior. An administrator can verify that a key pair is protected by a passphrase by viewing the private key manually. If the private key file contains the word `ENCRYPTED`, the key owner is using a passphrase. In addition, to better secure end users, `from` may be placed in the public key file. For example, adding `from="192.168.10.5"` in front of the `ssh-rsa` prefix will only allow that specific user to log in from that IP address. ==== The options and files vary with different versions of OpenSSH. To avoid problems, consult man:ssh-keygen[1]. If a passphrase is used, the user is prompted for the passphrase each time a connection is made to the server. To load SSH keys into memory and remove the need to type the passphrase each time, use man:ssh-agent[1] and man:ssh-add[1]. Authentication is handled by `ssh-agent`, using the private keys that are loaded into it. `ssh-agent` can be used to launch another application like a shell or a window manager. To use `ssh-agent` in a shell, start it with a shell as an argument. Add the identity by running `ssh-add` and entering the passphrase for the private key. The user will then be able to `ssh` to any host that has the corresponding public key installed. For example: [source,bash] .... % ssh-agent csh % ssh-add Enter passphrase for key '/usr/home/user/.ssh/id_rsa': <.> Identity added: /usr/home/user/.ssh/id_rsa (/usr/home/user/.ssh/id_rsa) % .... <.> Enter the passphrase for the key. To use `ssh-agent` in Xorg, add an entry for it in [.filename]#~/.xinitrc#. This provides the `ssh-agent` services to all programs launched in Xorg. An example [.filename]#~/.xinitrc# might look like this: [.programlisting] .... exec ssh-agent startxfce4 .... This launches `ssh-agent`, which in turn launches XFCE, every time Xorg starts. Once Xorg has been restarted so that the changes can take effect, run `ssh-add` to load all of the SSH keys. [[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 `ssh` to create a tunnel for telnet: [source,bash] .... % ssh -2 -N -f -L 5023:localhost:23 user@foo.example.com % .... This example uses the following options: `-2`:: Forces `ssh` to use version 2 to connect to the server. `-N`:: Indicates no command, or tunnel only. If omitted, `ssh` initiates a normal session. `-f`:: Forces `ssh` to run in the background. `-L`:: Indicates a local tunnel in _localport:remotehost:remoteport_ format. `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`. It then forwards any connections received on `localport` via the SSH connection to the specified `remotehost:remoteport`. In the example, port `5023` on the client is forwarded to port `23` on the remote machine. Since port 23 is used by telnet, this creates an encrypted telnet session through an SSH tunnel. This method can be used to wrap any number of insecure TCP protocols such as SMTP, POP3, and FTP, as seen in the following examples. .Create a Secure Tunnel for SMTP [example] ==== [source,bash] .... % ssh -2 -N -f -L 5025:localhost:25 user@mailserver.example.com user@mailserver.example.com's password: ***** % telnet localhost 5025 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 220 mailserver.example.com ESMTP .... This can be used in conjunction with `ssh-keygen` and additional user accounts to create a more seamless SSH tunneling environment. Keys can be used in place of typing a password, and the tunnels can be run as a separate user. ==== .Secure Access of a POP3 Server [example] ==== In this example, there is an SSH server that accepts connections from the outside. On the same network resides a mail server running a POP3 server. To check email in a secure manner, create an SSH connection to the SSH server and tunnel through to the mail server: [source,bash] .... % ssh -2 -N -f -L 2110:mail.example.com:110 user@ssh-server.example.com user@ssh-server.example.com's password: ****** .... Once the tunnel is up and running, point the email client to send POP3 requests to `localhost` on port 2110. This connection will be forwarded securely across the tunnel to `mail.example.com`. ==== .Bypassing a Firewall [example] ==== Some firewalls filter both incoming and outgoing connections. For example, a firewall might limit access from remote machines to ports 22 and 80 to only allow SSH and web surfing. This prevents access to any other service which uses a port other than 22 or 80. The solution is to create an SSH connection to a machine outside of the network's firewall and use it to tunnel to the desired service: [source,bash] .... % ssh -2 -N -f -L 8888:music.example.com:8000 user@unfirewalled-system.example.org user@unfirewalled-system.example.org's password: ******* .... In this example, a streaming Ogg Vorbis client can now be pointed to `localhost` port 8888, which will be forwarded over to `music.example.com` on port 8000, successfully bypassing the firewall. ==== === Enabling the SSH Server 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. To see if sshd is operating, use the man:service[8] command: [source,bash] .... # service sshd status .... If the service is not running, add the following line to [.filename]#/etc/rc.conf#. [.programlisting] .... sshd_enable="YES" .... This will start sshd, the daemon program for OpenSSH, the next time the system boots. To start it now: [source,bash] .... # 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. At this point, the sshd should be available to all users with a username and password on the system. === SSH Server Security 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. It is a good idea to limit which users can log into the SSH server and from where using the `AllowUsers` keyword in the OpenSSH server configuration file. For example, to only allow `root` to log in from `192.168.1.32`, add this line to [.filename]#/etc/ssh/sshd_config#: [.programlisting] .... AllowUsers root@192.168.1.32 .... To allow `admin` to log in from anywhere, list that user without specifying an IP address: [.programlisting] .... AllowUsers admin .... Multiple users should be listed on the same line, like so: [.programlisting] .... AllowUsers root@192.168.1.32 admin .... After making changes to [.filename]#/etc/ssh/sshd_config#, tell sshd to reload its configuration file by running: [source,bash] .... # service sshd reload .... [NOTE] ==== When this keyword is used, it is important to list each user that needs to log into this machine. Any user that is not specified in that line will be locked out. Also, the keywords used in the OpenSSH server configuration file are case-sensitive. If the keyword is not spelled correctly, including its case, it will be ignored. Always test changes to this file to make sure that the edits are working as expected. Refer to man:sshd_config[5] to verify the spelling and use of the available keywords. ==== In addition, users may be forced to use two factor authentication via the use of a public and private key. When required, the user may generate a key pair through the use of man:ssh-keygen[1] and send the administrator the public key. This key file will be placed in the [.filename]#authorized_keys# as described above in the client section. To force the users to use keys only, the following option may be configured: [.programlisting] .... AuthenticationMethods publickey .... [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. ==== [[fs-acl]] == Access Control Lists Access Control Lists (ACLs) extend the standard UNIX(R) permission model in a POSIX(R).1e compatible way. This permits an administrator to take advantage of a more fine-grained permissions model. The FreeBSD [.filename]#GENERIC# kernel provides ACL support for UFS file systems. Users who prefer to compile a custom kernel must include the following option in their custom kernel configuration file: [.programlisting] .... options UFS_ACL .... If this option is not compiled in, a warning message will be displayed when attempting to mount a file system with ACL support. ACLs rely on extended attributes which are natively supported in UFS2. This chapter describes how to enable ACL support and provides some usage examples. === Enabling ACL Support ACLs are enabled by the mount-time administrative flag, `acls`, which may be added to [.filename]#/etc/fstab#. The mount-time flag can also be automatically set in a persistent manner using man:tunefs[8] to modify a superblock ACLs flag in the file system header. In general, it is preferred to use the superblock flag for several reasons: * The superblock flag cannot be changed by a remount using `mount -u` as it requires a complete `umount` and fresh `mount`. This means that ACLs cannot be enabled on the root file system after boot. It also means that ACL support on a file system cannot be changed while the system is in use. * Setting the superblock flag causes the file system to always be mounted with ACLs enabled, even if there is not an [.filename]#fstab# entry or if the devices re-order. This prevents accidental mounting of the file system without ACL support. [NOTE] ==== It is desirable to discourage accidental mounting without ACLs enabled because nasty things can happen if ACLs are enabled, then disabled, then re-enabled without flushing the extended attributes. In general, once ACLs are enabled on a file system, they should not be disabled, as the resulting file protections may not be compatible with those intended by the users of the system, and re-enabling ACLs may re-attach the previous ACLs to files that have since had their permissions changed, resulting in unpredictable behavior. ==== File systems with ACLs enabled will show a plus (`+`) sign in their permission settings: [.programlisting] .... drwx------ 2 robert robert 512 Dec 27 11:54 private drwxrwx---+ 2 robert robert 512 Dec 23 10:57 directory1 drwxrwx---+ 2 robert robert 512 Dec 22 10:20 directory2 drwxrwx---+ 2 robert robert 512 Dec 27 11:57 directory3 drwxr-xr-x 2 robert robert 512 Nov 10 11:54 public_html .... In this example, [.filename]#directory1#, [.filename]#directory2#, and [.filename]#directory3# are all taking advantage of ACLs, whereas [.filename]#private# and [.filename]#public_html# are not. === Using ACLs File system ACLs can be viewed using `getfacl`. For instance, to view the ACL settings on [.filename]#test#: [source,bash] .... % getfacl test #file:test #owner:1001 #group:1001 user::rw- group::r-- other::r-- .... To change the ACL settings on this file, use `setfacl`. To remove all of the currently defined ACLs from a file or file system, include `-k`. However, the preferred method is to use `-b` as it leaves the basic fields required for ACLs to work. [source,bash] .... % setfacl -k test .... To modify the default ACL entries, use `-m`: [source,bash] .... % setfacl -m u:trhodes:rwx,group:web:r--,o::--- test .... In this example, there were no pre-defined entries, as they were removed by the previous command. This command restores the default options and assigns the options listed. If a user or group is added which does not exist on the system, an `Invalid argument` error will be displayed. Refer to man:getfacl[1] and man:setfacl[1] for more information about the options available for these commands. [[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. Please refer to crossref:ports[pkgng-intro,instructions] for installing pkg. Installation provides man:periodic[8] configuration files for maintaining the pkg audit database, and provides a programmatic method of keeping it updated. This functionality is enabled if `daily_status_security_pkgaudit_enable` is set to `YES` in man:periodic.conf[5]. Ensure that daily security run emails, which are sent to ``root``'s email account, are being read. 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,bash] .... # pkg audit -F .... pkg displays messages any published vulnerabilities in installed packages: [.programlisting] .... Affected package: cups-base-1.1.22.0_1 Type of problem: cups-base -- HPGL buffer overflow vulnerability. Reference: 1 problem(s) in your installed packages found. You are advised to update or deinstall the affected package(s) immediately. .... By pointing a web browser to the displayed URL, an administrator may obtain more information about the vulnerability. This will include the versions affected, by FreeBSD port version, along with other web sites which may contain security advisories. pkg is a powerful utility and is extremely useful when coupled with package:ports-mgmt/portmaster[]. [[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} mailing lists. This section describes the format of a FreeBSD security advisory. === Format of a Security Advisory Here is an example of a FreeBSD security advisory: [.programlisting] .... ============================================================================= -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 ============================================================================= FreeBSD-SA-14:04.bind Security Advisory The FreeBSD Project Topic: BIND remote denial of service vulnerability Category: contrib Module: bind Announced: 2014-01-14 Credits: ISC Affects: FreeBSD 8.x and FreeBSD 9.x Corrected: 2014-01-14 19:38:37 UTC (stable/9, 9.2-STABLE) 2014-01-14 19:42:28 UTC (releng/9.2, 9.2-RELEASE-p3) 2014-01-14 19:42:28 UTC (releng/9.1, 9.1-RELEASE-p10) 2014-01-14 19:38:37 UTC (stable/8, 8.4-STABLE) 2014-01-14 19:42:28 UTC (releng/8.4, 8.4-RELEASE-p7) 2014-01-14 19:42:28 UTC (releng/8.3, 8.3-RELEASE-p14) CVE Name: CVE-2014-0591 For general information regarding FreeBSD Security Advisories, including descriptions of the fields above, security branches, and the following sections, please visit . I. Background BIND 9 is an implementation of the Domain Name System (DNS) protocols. The named(8) daemon is an Internet Domain Name Server. II. Problem Description Because of a defect in handling queries for NSEC3-signed zones, BIND can crash with an "INSIST" failure in name.c when processing queries possessing certain properties. This issue only affects authoritative nameservers with at least one NSEC3-signed zone. Recursive-only servers are not at risk. III. Impact An attacker who can send a specially crafted query could cause named(8) to crash, resulting in a denial of service. IV. Workaround No workaround is available, but systems not running authoritative DNS service with at least one NSEC3-signed zone using named(8) are not vulnerable. V. Solution Perform one of the following: 1) Upgrade your vulnerable system to a supported FreeBSD stable or release / security branch (releng) dated after the correction date. 2) To update your vulnerable system via a source code patch: The following patches have been verified to apply to the applicable FreeBSD release branches. a) Download the relevant patch from the location below, and verify the detached PGP signature using your PGP utility. [FreeBSD 8.3, 8.4, 9.1, 9.2-RELEASE and 8.4-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch.asc # gpg --verify bind-release.patch.asc [FreeBSD 9.2-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch.asc # gpg --verify bind-stable-9.patch.asc b) Execute the following commands as root: # cd /usr/src # patch < /path/to/patch Recompile the operating system using buildworld and installworld as described in . Restart the applicable daemons, or reboot the system. 3) To update your vulnerable system via a binary patch: Systems running a RELEASE version of FreeBSD on the i386 or amd64 platforms can be updated via the freebsd-update(8) utility: # freebsd-update fetch # freebsd-update install VI. Correction details The following list contains the correction revision numbers for each affected branch. Branch/path Revision - ------------------------------------------------------------------------- stable/8/ r260646 releng/8.3/ r260647 releng/8.4/ r260647 stable/9/ r260646 releng/9.1/ r260647 releng/9.2/ r260647 - ------------------------------------------------------------------------- To see which files were modified by a particular revision, run the following command, replacing NNNNNN with the revision number, on a machine with Subversion installed: # svn diff -cNNNNNN --summarize svn://svn.freebsd.org/base Or visit the following URL, replacing NNNNNN with the revision number: VII. References The latest revision of this advisory is available at -----BEGIN PGP SIGNATURE----- iQIcBAEBCgAGBQJS1ZTYAAoJEO1n7NZdz2rnOvQP/2/68/s9Cu35PmqNtSZVVxVG ZSQP5EGWx/lramNf9566iKxOrLRMq/h3XWcC4goVd+gZFrvITJSVOWSa7ntDQ7TO XcinfRZ/iyiJbs/Rg2wLHc/t5oVSyeouyccqODYFbOwOlk35JjOTMUG1YcX+Zasg ax8RV+7Zt1QSBkMlOz/myBLXUjlTZ3Xg2FXVsfFQW5/g2CjuHpRSFx1bVNX6ysoG 9DT58EQcYxIS8WfkHRbbXKh9I1nSfZ7/Hky/kTafRdRMrjAgbqFgHkYTYsBZeav5 fYWKGQRJulYfeZQ90yMTvlpF42DjCC3uJYamJnwDIu8OhS1WRBI8fQfr9DRzmRua OK3BK9hUiScDZOJB6OqeVzUTfe7MAA4/UwrDtTYQ+PqAenv1PK8DZqwXyxA9ThHb zKO3OwuKOVHJnKvpOcr+eNwo7jbnHlis0oBksj/mrq2P9m2ueF9gzCiq5Ri5Syag Wssb1HUoMGwqU0roS8+pRpNC8YgsWpsttvUWSZ8u6Vj/FLeHpiV3mYXPVMaKRhVm 067BA2uj4Th1JKtGleox+Em0R7OFbCc/9aWC67wiqI6KRyit9pYiF3npph+7D5Eq 7zPsUdDd+qc+UTiLp3liCRp5w6484wWdhZO6wRtmUgxGjNkxFoNnX8CitzF8AaqO UWWemqWuz3lAZuORQ9KX =OQzQ -----END PGP SIGNATURE----- .... Every security advisory uses the following format: * Each security advisory is signed by the PGP key of the Security Officer. The public key for the Security Officer can be verified at 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 (`14:`), followed by the advisory number for that year (`04.`), followed by the name of the affected application or subsystem (`bind`). The advisory shown here is the fourth advisory for 2014 and it affects BIND. * The `Topic` field summarizes the vulnerability. * The `Category` refers to the affected part of the system which may be one of `core`, `contrib`, or `ports`. The `core` category means that the vulnerability affects a core component of the 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 `bind` module is affected; therefore, this vulnerability affects an application installed with the operating system. * The `Announced` field reflects the date the security advisory was published. This means that the security team has verified that the problem exists and that a patch has been committed to the 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 branch with the revision number that contains the corrected code. * The `References` field offers sources of additional information regarding the vulnerability. [[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,bash] .... # 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 `sa`. If issued without any options, `sa` prints information relating to the number of per-user calls, the total elapsed time in minutes, total CPU and user time in minutes, and the average number of I/O operations. Refer to man:sa[8] for the list of available options which control the output. To display the commands issued by users, use `lastcomm`. For example, this command prints out all usage of `ls` by `trhodes` on the `ttyp1` terminal: [source,bash] .... # 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 FreeBSD provides several methods for an administrator to limit the amount of system resources an individual may use. Disk quotas limit the amount of disk space available to users. Quotas are discussed in crossref:disks[quotas,"Disk Quotas"]. Limits to other resources, such as CPU and memory, can be set using either a flat file or a command to configure a resource limits database. 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. `rctl` 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. [[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_. [NOTE] ==== Whenever [.filename]#/etc/login.conf# is edited, the [.filename]#/etc/login.conf.db# must be updated by executing the following command: [source,bash] .... # cap_mkdb /etc/login.conf .... ==== Resource limits differ from the default login capabilities in two ways. First, for every limit, there is a _soft_ and _hard_ limit. A soft limit may be adjusted by the user or application, but may not be set higher than the hard limit. The hard limit may be lowered by the user, but can only be raised by the superuser. Second, most resource limits apply per process to a specific user. <> lists the most commonly used resource limits. All of the available resource limits and capabilities are described in detail in man:login.conf[5]. [[resource-limits]] .Login Class Resource Limits [cols="20%,80%", frame="none", options="header"] |=== | Resource Limit | Description |coredumpsize |The limit on the size of a core file generated by a program is subordinate to other limits on disk usage, such as `filesize` or disk quotas. This limit is often used as a less severe method of controlling disk space consumption. Since users do not generate core files and often do not delete them, this setting may save them from running out of disk space should a large program crash. |cputime |The maximum amount of CPU time a user's process may consume. Offending processes will be killed by the kernel. This is a limit on CPU _time_ consumed, not the percentage of the CPU as displayed in some of the fields generated by `top` and `ps`. |filesize |The maximum size of a file the user may own. Unlike disk quotas (crossref:disks[quotas,"Disk Quotas"]), this limit is enforced on individual files, not the set of all files a user owns. |maxproc |The maximum number of foreground and background processes a user can run. This limit may not be larger than the system limit specified by `kern.maxproc`. Setting this limit too small may hinder a user's productivity as some tasks, such as compiling a large program, start lots of processes. |memorylocked |The maximum amount of memory a process may request to be locked into main memory using man:mlock[2]. Some system-critical programs, such as man:amd[8], lock into main memory so that if the system begins to swap, they do not contribute to disk thrashing. |memoryuse |The maximum amount of memory a process may consume at any given time. It includes both core memory and swap usage. This is not a catch-all limit for restricting memory consumption, but is a good start. |openfiles |The maximum number of files a process may have open. In FreeBSD, files are used to represent sockets and IPC channels, so be careful not to set this too low. The system-wide limit for this is defined by `kern.maxfiles`. |sbsize |The limit on the amount of network memory a user may consume. This can be generally used to limit network communications. |stacksize |The maximum size of a process stack. This alone is not sufficient to limit the amount of memory a program may use, so it should be used in conjunction with other limits. |=== There are a few other things to remember when setting resource limits: * Processes started at system startup by [.filename]#/etc/rc# are assigned to the `daemon` login class. * Although the default [.filename]#/etc/login.conf# is a good source of reasonable values for most limits, they may not be appropriate for every system. Setting a limit too high may open the system up to abuse, while setting it too low may put a strain on productivity. * Xorg takes a lot of resources and encourages users to run more programs simultaneously. * Many limits apply to individual processes, not the user as a whole. For example, setting `openfiles` to `50` means that each process the user runs may open up to `50` files. The total amount of files a user may open is the value of `openfiles` multiplied by the value of `maxproc`. This also applies to memory consumption. For further information on resource limits and login classes and capabilities in general, refer to man:cap.mkdb[1], man:getrlimit[2], and man:login.conf[5]. === Enabling and Configuring Resource Limits The `kern.racct.enable` tunable must be set to a non-zero value. Custom kernels require specific configuration: [.programlisting] .... options RACCT options RCTL .... Once the system has rebooted into the new kernel, `rctl` may be used to set rules for the system. Rule syntax is controlled through the use of a subject, subject-id, resource, and action, as seen in this example rule: [.programlisting] .... user:trhodes:maxproc:deny=10/user .... In this rule, the subject is `user`, the subject-id is `trhodes`, the resource, `maxproc`, is the maximum number of processes, and the action is `deny`, which blocks any new processes from being created. This means that the user, `trhodes`, will be constrained to no greater than `10` processes. Other possible actions include logging to the console, passing a notification to man:devd[8], or sending a sigterm to the process. Some care must be taken when adding rules. Since this user is constrained to `10` processes, this example will prevent the user from performing other tasks after logging in and executing a `screen` session. Once a resource limit has been hit, an error will be printed, as in this example: [source,bash] .... % man test /usr/bin/man: Cannot fork: Resource temporarily unavailable eval: Cannot fork: Resource temporarily unavailable .... As another example, a jail can be prevented from exceeding a memory limit. This rule could be written as: [source,bash] .... # rctl -a jail:httpd:memoryuse:deny=2G/jail .... 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] .... # Block jail from using more than 2G memory: jail:httpd:memoryuse:deny=2G/jail .... To remove a rule, use `rctl` to remove it from the list: [source,bash] .... # rctl -r user:trhodes:maxproc:deny=10/user .... A method for removing all rules is documented in man:rctl[8]. However, if removing all rules for a single user is required, this command may be issued: [source,bash] .... # rctl -r user:trhodes .... Many other resources exist which can be used to exert additional control over various `subjects`. See man:rctl[8] to learn about them. [[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. 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. To use the man:pkg[8] tool: [source,bash] .... # 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,bash] .... % 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,bash] .... # pw groupadd -g 6001 -n webteam .... Using the same man:pw[8] command, the user is added to the webteam group: [source,bash] .... # 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], Sudo only requires the end user password. This adds an advantage where users will not need shared passwords, a finding in most security audits and just bad all the way around. Users permitted to run applications with Sudo 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. Sudo provides for these cases with 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-sudo-loggin]] === Logging Output An advantage to implementing Sudo is the ability to enable session logging. Using the built in log mechanisms and the included sudoreplay command, all commands initiated through Sudo are logged for later verification. To enable this feature, add a default log directory entry, this example uses a user variable. Several other log filename conventions exist, consult the manual page for sudoreplay for additional information. [.programlisting] .... Defaults iolog_dir=/var/log/sudo-io/%{user} .... [TIP] ==== This directory will be created automatically after the logging is configured. It is best to let the system create directory with default permissions just to be safe. In addition, this entry will also log administrators who use the sudoreplay command. To change this behavior, read and uncomment the logging options inside [.filename]#sudoers#. ==== Once this directive has been added to the [.filename]#sudoers# file, any user configuration can be updated with the request to log access. In the example shown, the updated _webteam_ entry would have the following additional changes: [.programlisting] .... %webteam ALL=(ALL) NOPASSWD: LOG_INPUT: LOG_OUTPUT: /usr/sbin/service webservice * .... From this point on, all _webteam_ members altering the status of the _webservice_ application will be logged. The list of previous and current sessions can be displayed with: [source,bash] .... # sudoreplay -l .... In the output, to replay a specific session, search for the `TSID=` entry, and pass that to sudoreplay with no other options to replay the session at normal speed. For example: [source,bash] .... # sudoreplay user1/00/00/02 .... [WARNING] ==== While sessions are logged, any administrator is able to remove sessions and leave only a question of why they had done so. It is worthwhile to add a daily check through an intrusion detection system (IDS) or similar software so that other administrators are alerted to manual alterations. ==== The `sudoreplay` is extremely extendable. Consult the documentation for more information.