FreeBSD Handbook


FreeBSD is a registered trademark of the FreeBSD Foundation.

IBM, AIX, OS/2, PowerPC, PS/2, S/390, and ThinkPad are trademarks of International Business Machines Corporation in the United States, other countries, or both.

IEEE, POSIX, and 802 are registered trademarks of Institute of Electrical and Electronics Engineers, Inc. in the United States.

Red Hat, RPM, are trademarks or registered trademarks of Red Hat, Inc. in the United States and other countries.

3Com and HomeConnect are registered trademarks of 3Com Corporation.

Adobe, Acrobat, Acrobat Reader, Flash and PostScript are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.

Apple, AirPort, FireWire, iMac, iPhone, iPad, Mac, Macintosh, Mac OS, Quicktime, and TrueType are trademarks of Apple Inc., registered in the U.S. and other countries.

Intel, Celeron, Centrino, Core, EtherExpress, i386, i486, Itanium, Pentium, and Xeon are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.

Linux is a registered trademark of Linus Torvalds.

Microsoft, IntelliMouse, MS-DOS, Outlook, Windows, Windows Media and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Motif, OSF/1, and UNIX are registered trademarks and IT DialTone and The Open Group are trademarks of The Open Group in the United States and other countries.

Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JRE, JSP, JVM, Netra, OpenJDK, Solaris, StarOffice, SunOS and VirtualBox are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

RealNetworks, RealPlayer, and RealAudio are the registered trademarks of RealNetworks, Inc.

Oracle is a registered trademark of Oracle Corporation.

3ware is a registered trademark of 3ware Inc.

ARM is a registered trademark of ARM Limited.

Adaptec is a registered trademark of Adaptec, Inc.

Android is a trademark of Google Inc.

Heidelberg, Helvetica, Palatino, and Times Roman are either registered trademarks or trademarks of Heidelberger Druckmaschinen AG in the U.S. and other countries.

Intuit and Quicken are registered trademarks and/or registered service marks of Intuit Inc., or one of its subsidiaries, in the United States and other countries.

LSI Logic, AcceleRAID, eXtremeRAID, MegaRAID and Mylex are trademarks or registered trademarks of LSI Logic Corp.

MATLAB is a registered trademark of The MathWorks, Inc.

SpeedTouch is a trademark of Thomson.

VMware is a trademark of VMware, Inc.

Mathematica is a registered trademark of Wolfram Research, Inc.

Ogg Vorbis and Xiph.Org are trademarks of Xiph.Org.

XFree86 is a trademark of The XFree86 Project, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this document, and the FreeBSD Project was aware of the trademark claim, the designations have been followed by the “™” or the “®” symbol.

Table of Contents

[ Split HTML / Single HTML ]


Welcome to FreeBSD! This handbook covers the installation and day to day use of FreeBSD 13.2-RELEASE and FreeBSD 12.4-RELEASE. This book is the result of ongoing work by many individuals. Some sections might be outdated. Those interested in helping to update and expand this document should send email to the FreeBSD documentation project mailing list.

The latest version of this book is available from the FreeBSD web site. Previous versions can be obtained from The book can be downloaded in a variety of formats and compression options from the FreeBSD download server or one of the numerous mirror sites. Searches can be performed on the handbook and other documents on the search page.


Intended Audience

The FreeBSD newcomer will find that the first section of this book guides the user through the FreeBSD installation process and gently introduces the concepts and conventions that underpin UNIX®. Working through this section requires little more than the desire to explore, and the ability to take on board new concepts as they are introduced.

Once you have traveled this far, the second, far larger, section of the Handbook is a comprehensive reference to all manner of topics of interest to FreeBSD system administrators. Some of these chapters may recommend that you do some prior reading, and this is noted in the synopsis at the beginning of each chapter.

For a list of additional sources of information, please see Bibliography.

Fourth Edition

The current version of the Handbook represents the cumulative effort of a working group that has been reviewing and updating all Handbook content. These are the major updates since the fourth edition of the Handbook.

Third Edition

The current online version of the Handbook represents the cumulative effort of many hundreds of contributors over the past 10 years. The following are some of the significant changes since the two volume third edition was published in 2004:

  • WINE has been added with information about how to run Windows® applications on FreeBSD.

  • DTrace has been added with information about the powerful DTrace performance analysis tool.

  • Other File Systems have been added with information about non-native file systems in FreeBSD, such as ZFS from Sun™.

  • Security Event Auditing has been added to cover the new auditing capabilities in FreeBSD and explain its use.

  • Virtualization has been added with information about installing FreeBSD on virtualization software.

  • Installing FreeBSD has been added to cover installation of FreeBSD using the new installation utility, bsdinstall.

Second Edition (2004)

The third edition was the culmination of over two years of work by the dedicated members of the FreeBSD Documentation Project. The printed edition grew to such a size that it was necessary to publish as two separate volumes. The following are the major changes in this new edition:

  • Configuration and Tuning has been expanded with new information about the ACPI power and resource management, the cron system utility, and more kernel tuning options.

  • Security has been expanded with new information about virtual private networks (VPNs), file system access control lists (ACLs), and security advisories.

  • Mandatory Access Control is a new chapter with this edition. It explains what MAC is and how this mechanism can be used to secure a FreeBSD system.

  • Storage has been expanded with new information about USB storage devices, file system snapshots, file system quotas, file and network backed filesystems, and encrypted disk partitions.

  • A troubleshooting section has been added to PPP.

  • Electronic Mail has been expanded with new information about using alternative transport agents, SMTP authentication, UUCP, fetchmail, procmail, and other advanced topics.

  • Network Servers is all new with this edition. This chapter includes information about setting up the Apache HTTP Server, ftpd, and setting up a server for Microsoft® Windows® clients with Samba. Some sections from Advanced Networking were moved here to improve the presentation.

  • Advanced Networking has been expanded with new information about using Bluetooth® devices with FreeBSD, setting up wireless networks, and Asynchronous Transfer Mode (ATM) networking.

  • A glossary has been added to provide a central location for the definitions of technical terms used throughout the book.

  • A number of aesthetic improvements have been made to the tables and figures throughout the book.

First Edition (2001)

The second edition was the culmination of over two years of work by the dedicated members of the FreeBSD Documentation Project. The following were the major changes in this edition:

  • A complete Index has been added.

  • All ASCII figures have been replaced by graphical diagrams.

  • A standard synopsis has been added to each chapter to give a quick summary of what information the chapter contains, and what the reader is expected to know.

  • The content has been logically reorganized into three parts: "Getting Started", "System Administration", and "Appendices".

  • FreeBSD Basics has been expanded to contain additional information about processes, daemons, and signals.

  • Installing Applications: Packages and Ports has been expanded to contain additional information about binary package management.

  • The X Window System has been completely rewritten with an emphasis on using modern desktop technologies such as KDE and GNOME on XFree86™ 4.X.

  • The FreeBSD Booting Process has been expanded.

  • Storage has been written from what used to be two separate chapters on "Disks" and "Backups". We feel that the topics are easier to comprehend when presented as a single chapter. A section on RAID (both hardware and software) has also been added.

  • Serial Communications has been completely reorganized and updated for FreeBSD 4.X/5.X.

  • PPP has been substantially updated.

  • Many new sections have been added to Advanced Networking.

  • Electronic Mail has been expanded to include more information about configuring sendmail.

  • Linux® Binary Compatibility has been expanded to include information about installing Oracle® and SAP® R/3®.

  • The following new topics are covered in this second edition:

Organization of This Book

This book is split into five logically distinct sections. The first section, Getting Started, covers the installation and basic usage of FreeBSD. It is expected that the reader will follow these chapters in sequence, possibly skipping chapters covering familiar topics. The second section, Common Tasks, covers some frequently used features of FreeBSD. This section, and all subsequent sections, can be read out of order. Each chapter begins with a succinct synopsis that describes what the chapter covers and what the reader is expected to already know. This is meant to allow the casual reader to skip around to find chapters of interest. The third section, System Administration, covers administration topics. The fourth section, Network Communication, covers networking and server topics. The fifth section contains appendices of reference information.


Introduces FreeBSD to a new user. It describes the history of the FreeBSD Project, its goals and development model.

Installing FreeBSD

Walks a user through the entire installation process of FreeBSD 9.x and later using bsdinstall.

FreeBSD Basics

Covers the basic commands and functionality of the FreeBSD operating system. If you are familiar with Linux® or another flavor of UNIX® then you can probably skip this chapter.

Installing Applications: Packages and Ports

Covers the installation of third-party software with both FreeBSD’s innovative "Ports Collection" and standard binary packages.

The X Window System

Describes the X Window System in general and using X11 on FreeBSD in particular. Also describes common desktop environments such as KDE and GNOME.


Describes the Wayland display server in general and using Wayland on FreeBSD in particular. Also describes common compositors such as Wayfire, Hikari and Sway.

Desktop Applications

Lists some common desktop applications, such as web browsers and productivity suites, and describes how to install them on FreeBSD.


Shows how to set up sound and video playback support for your system. Also describes some sample audio and video applications.

Configuring the FreeBSD Kernel

Explains why you might need to configure a new kernel and provides detailed instructions for configuring, building, and installing a custom kernel.


Describes managing printers on FreeBSD, including information about banner pages, printer accounting, and initial setup.

Linux® Binary Compatibility

Describes the Linux® compatibility features of FreeBSD. Also provides detailed installation instructions for many popular Linux® applications such as Oracle® and Mathematica®.


Describes WINE and provides detailed installation instructions. Also describes how WINE operates, how to install a GUI helper, how to run Windows® applications on FreeBSD, and offers other tips and solutions.

Configuration and Tuning

Describes the parameters available for system administrators to tune a FreeBSD system for optimum performance. Also describes the various configuration files used in FreeBSD and where to find them.

The FreeBSD Booting Process

Describes the FreeBSD boot process and explains how to control this process with configuration options.


Describes many different tools available to help keep your FreeBSD system secure, including Kerberos, IPsec and OpenSSH.


Describes the jails framework, and the improvements of jails over the traditional chroot support of FreeBSD.

Mandatory Access Control

Explains what Mandatory Access Control (MAC) is and how this mechanism can be used to secure a FreeBSD system.

Security Event Auditing

Describes what FreeBSD Event Auditing is, how it can be installed, configured, and how audit trails can be inspected or monitored.


Describes how to manage storage media and filesystems with FreeBSD. This includes physical disks, RAID arrays, optical and tape media, memory-backed disks, and network filesystems.

GEOM: Modular Disk Transformation Framework

Describes what the GEOM framework in FreeBSD is and how to configure various supported RAID levels.

The OpenZFS storage platform

Describes the OpenZFS storage platform and provides a quick-start guide and information about advanced topics running OpenZFS under FreeBSD.

Other File Systems

Examines support for non-native file systems under FreeBSD like ext2, ext3 and ext4.


Describes what virtualization systems offer, and how they can be used with FreeBSD.

Localization - i18n/L10n Usage and Setup

Describes how to use FreeBSD in languages other than English. Covers both system and application level localization.

Updating and Upgrading FreeBSD

Explains the differences between FreeBSD-STABLE, FreeBSD-CURRENT, and FreeBSD releases. Describes which users would benefit from tracking a development system and outlines that process. Covers the methods users may take to update their system to the latest security release.


Describes how to configure and use the DTrace tool from Sun™ on FreeBSD. Dynamic tracing can help locate performance issues, by performing real time system analysis.

USB Device Mode / USB OTG

Explains the use of USB Device Mode and USB On The Go (USB OTG) on FreeBSD.


Describes how to use PPP to connect to remote systems in FreeBSD.

Electronic Mail

Explains the different components of an email server and dives into simple configuration topics for the most popular mail server software: sendmail.

Network Servers

Provides detailed instructions and example configuration files to set up your FreeBSD machine as a network filesystem server, domain name server, network information system server, or time synchronization server.


Explains the philosophy behind software-based firewalls and provides detailed information about the configuration of the different firewalls available for FreeBSD.

Advanced Networking

Describes many networking topics, including sharing an Internet connection with other computers on your LAN, advanced routing topics, wireless networking, Bluetooth®, ATM, IPv6, and much more.

Obtaining FreeBSD

Lists different sources for obtaining FreeBSD media on CDROM or DVD as well as different sites on the Internet that allow you to download and install FreeBSD.


This book touches on many different subjects that may leave you hungry for a more detailed explanation. The bibliography lists many excellent books that are referenced in the text.

Resources on the Internet

Describes the many forums available for FreeBSD users to post questions and engage in technical conversations about FreeBSD.

OpenPGP Keys

Lists the PGP fingerprints of several FreeBSD Developers.

Conventions used in this book

To provide a consistent and easy to read text, several conventions are followed throughout the book.

Typographic Conventions


An italic font is used for filenames, URLs, emphasized text, and the first usage of technical terms.


A monospaced font is used for error messages, commands, environment variables, names of ports, hostnames, user names, group names, device names, variables, and code fragments.


A bold font is used for applications, commands, and keys.

User Input

Keys are shown in bold to stand out from other text. Key combinations that are meant to be typed simultaneously are shown with + between the keys, such as:


Meaning the user should type the Ctrl, Alt, and Del keys at the same time.

Keys that are meant to be typed in sequence will be separated with commas, for example:

Ctrl+X, Ctrl+S

Would mean that the user is expected to type the Ctrl and X keys simultaneously and then to type the Ctrl and S keys simultaneously.


Examples starting with C:\> indicate a MS-DOS® command. Unless otherwise noted, these commands may be executed from a "Command Prompt" window in a modern Microsoft® Windows® environment.

C:\> tools\fdimage floppies\kern.flp A:

Examples starting with # indicate a command that must be invoked as the superuser in FreeBSD. You can login as root to type the command, or login as your normal account and use su(1) to gain superuser privileges.

# dd if=kern.flp of=/dev/fd0

Examples starting with % indicate a command that should be invoked from a normal user account. Unless otherwise noted, C-shell syntax is used for setting environment variables and other shell commands.

% top


The book you are holding represents the efforts of many hundreds of people around the world. Whether they sent in fixes for typos, or submitted complete chapters, all the contributions have been useful.

Several companies have supported the development of this document by paying authors to work on it full-time, paying for publication, etc. In particular, BSDi (subsequently acquired by Wind River Systems) paid members of the FreeBSD Documentation Project to work on improving this book full time leading up to the publication of the first printed edition in March 2000 (ISBN 1-57176-241-8). Wind River Systems then paid several additional authors to make a number of improvements to the print-output infrastructure and to add additional chapters to the text. This work culminated in the publication of the second printed edition in November 2001 (ISBN 1-57176-303-1). In 2003-2004, FreeBSD Mall, Inc, paid several contributors to improve the Handbook in preparation for the third printed edition. The third printed edition has been split into two volumes. Both volumes have been published as The FreeBSD Handbook 3rd Edition Volume 1: User Guide (ISBN 1-57176-327-9) and The FreeBSD Handbook 3rd Edition Volume 2: Administrators Guide (ISBN 1-57176-328-7).

Part I: Getting Started

This part of the handbook is for users and administrators who are new to FreeBSD. These chapters:

  • Introduce FreeBSD.

  • Guide readers through the installation process.

  • Teach UNIX® basics and fundamentals.

  • Show how to install the wealth of third party applications available for FreeBSD.

  • Introduce X, the UNIX® windowing system, and detail how to configure a desktop environment that makes users more productive.

  • Introduce Wayland, a new display server for UNIX®.

The number of forward references in the text have been kept to a minimum so that this section can be read from front to back with minimal page flipping.

Chapter 1. Introduction

1.1. Synopsis

Thank you for your interest in FreeBSD! The following chapter covers various aspects of the FreeBSD Project, such as its history, goals, development model, and so on.

After reading this chapter you will know:

  • How FreeBSD relates to other computer operating systems.

  • The history of the FreeBSD Project.

  • The goals of the FreeBSD Project.

  • The basics of the FreeBSD open-source development model.

  • And of course: where the name "FreeBSD" comes from.

1.2. Welcome to FreeBSD!

FreeBSD is an Open Source, standards-compliant Unix-like operating system for x86 (both 32 and 64 bit), ARM, AArch64, RISC-V, POWER, and PowerPC computers. It provides all the features that are nowadays taken for granted, such as preemptive multitasking, memory protection, virtual memory, multi-user facilities, SMP support, all the Open Source development tools for different languages and frameworks, and desktop features centered around X Window System, KDE, or GNOME. Its particular strengths are:

  • Liberal Open Source license, which grants you rights to freely modify and extend its source code and incorporate it in both Open Source projects and closed products without imposing restrictions typical to copyleft licenses, as well as avoiding potential license incompatibility problems.

  • Strong TCP/IP networking - FreeBSD implements industry standard protocols with ever increasing performance and scalability. This makes it a good match in both server, and routing/firewalling roles - and indeed many companies and vendors use it precisely for that purpose.

  • Fully integrated OpenZFS support, including root-on-ZFS, ZFS Boot Environments, fault management, administrative delegation, support for jails, FreeBSD specific documentation, and system installer support.

  • Extensive security features, from the Mandatory Access Control framework to Capsicum capability and sandbox mechanisms.

  • Over 30 thousand prebuilt packages for all supported architectures, and the Ports Collection which makes it easy to build your own, customized ones.

  • Documentation - in addition to the Handbook and books from different authors that cover topics ranging from system administration to kernel internals, there are also the man(1) pages, not only for userspace daemons, utilities, and configuration files, but also for kernel driver APIs (section 9) and individual drivers (section 4).

  • Simple and consistent repository structure and build system - FreeBSD uses a single repository for all of its components, both kernel and userspace. This, along with a unified and easy to customize build system and a well thought-out development process makes it easy to integrate FreeBSD with build infrastructure for your own product.

  • Staying true to Unix philosophy, preferring composability instead of monolithic "all in one" daemons with hardcoded behavior.

  • Binary compatibility with Linux, which makes it possible to run many Linux binaries without the need for virtualisation.

FreeBSD is based on the 4.4BSD-Lite release from Computer Systems Research Group (CSRG) at the University of California at Berkeley, and carries on the distinguished tradition of BSD systems development. In addition to the fine work provided by CSRG, the FreeBSD Project has put in many thousands of man-hours into extending the functionality and fine-tuning the system for maximum performance and reliability in real-life load situations. FreeBSD offers performance and reliability on par with other Open Source and commercial offerings, combined with cutting-edge features not available anywhere else.

1.2.1. What Can FreeBSD Do?

The applications to which FreeBSD can be put are truly limited only by your own imagination. From software development to factory automation, inventory control to azimuth correction of remote satellite antenna; if it can be done with a commercial UNIX® product then it is more than likely that you can do it with FreeBSD too! FreeBSD also benefits significantly from literally thousands of high quality applications developed by research centers and universities around the world, often available at little to no cost.

Because the source code for FreeBSD itself is freely available, the system can also be customized to an almost unheard-of degree for special applications or projects, and in ways not generally possible with operating systems from most major commercial vendors. Here is just a sampling of some of the applications in which people are currently using FreeBSD:

  • Internet Services: The robust TCP/IP networking built into FreeBSD makes it an ideal platform for a variety of Internet services such as:

    • Web servers

    • IPv4 and IPv6 routing

    • Firewalls and NAT ("IP masquerading") gateways

    • FTP servers

    • Email servers

    • Storage servers

    • Virtualization servers

    • And more…​

  • Education: Are you a student of computer science or a related engineering field? There is no better way of learning about operating systems, computer architecture and networking than the hands-on, under-the-hood experience that FreeBSD can provide. A number of freely available CAD, mathematical and graphic design packages also make it highly useful to those whose primary interest in a computer is to get other work done!

  • Research: With source code for the entire system available, FreeBSD is an excellent platform for research in operating systems as well as other branches of computer science. FreeBSD’s freely available nature also makes it possible for remote groups to collaborate on ideas or shared development without having to worry about special licensing agreements or limitations on what may be discussed in open forums.

  • Networking: Need a new router? A name server (DNS)? A firewall to keep people out of your internal network? FreeBSD can easily turn that unused PC sitting in the corner into an advanced router with sophisticated packet-filtering capabilities.

  • Embedded: FreeBSD makes an excellent platform to build embedded systems upon. With support for the ARM, AArch64 and PowerPC platforms, coupled with a robust network stack, cutting edge features, and the permissive BSD license, FreeBSD makes an excellent foundation for building embedded routers, firewalls, and other devices.

  • Desktop: FreeBSD makes a fine choice for an inexpensive desktop solution using the freely available X11 server and Wayland display server. FreeBSD offers a choice from many open-source desktop environments, including the standard GNOME and KDE graphical user interfaces. FreeBSD can even boot "diskless" from a central server, making individual workstations even cheaper and easier to administer.

  • Software Development: The basic FreeBSD system comes with a full suite of development tools including a full C/C++ compiler and debugger suite. Support for many other languages are also available through the ports and packages collection.

FreeBSD is available to download free of charge, or can be obtained on either CD-ROM or DVD. Please see Obtaining FreeBSD for more information about obtaining FreeBSD.

1.2.2. Who Uses FreeBSD?

FreeBSD has been known for its web serving capabilities. A list of testimonials from companies basing their products and services on FreeBSD can be found at the FreeBSD Foundation website. Wikipedia also maintains a list of products based on FreeBSD.

1.3. About the FreeBSD Project

The following section provides some background information on the project, including a brief history, project goals, and the development model of the project.

1.3.1. A Brief History of FreeBSD

The FreeBSD Project had its genesis in the early part of 1993, partially as the brainchild of the Unofficial 386BSDPatchkit’s last 3 coordinators: Nate Williams, Rod Grimes and Jordan Hubbard.

The original goal was to produce an intermediate snapshot of 386BSD in order to fix a number of problems that the patchkit mechanism was just not capable of solving. The early working title for the project was 386BSD 0.5 or 386BSD Interim in reference to that fact.

386BSD was Bill Jolitz’s operating system, which had been up to that point suffering rather severely from almost a year’s worth of neglect. As the patchkit swelled ever more uncomfortably with each passing day, they decided to assist Bill by providing this interim "cleanup" snapshot. Those plans came to a rude halt when Bill Jolitz suddenly decided to withdraw his sanction from the project without any clear indication of what would be done instead.

The trio thought that the goal remained worthwhile, even without Bill’s support, and so they adopted the name "FreeBSD" coined by David Greenman. The initial objectives were set after consulting with the system’s current users and, once it became clear that the project was on the road to perhaps even becoming a reality, Jordan contacted Walnut Creek CDROM with an eye toward improving FreeBSD’s distribution channels for those many unfortunates without easy access to the Internet. Walnut Creek CDROM not only supported the idea of distributing FreeBSD on CD but also went so far as to provide the project with a machine to work on and a fast Internet connection. Without Walnut Creek CDROM’s almost unprecedented degree of faith in what was, at the time, a completely unknown project, it is quite unlikely that FreeBSD would have gotten as far, as fast, as it has today.

The first CD-ROM (and general net-wide) distribution was FreeBSD 1.0, released in December of 1993. This was based on the 4.3BSD-Lite ("Net/2") tape from U.C. Berkeley, with many components also provided by 386BSD and the Free Software Foundation. It was a fairly reasonable success for a first offering, and they followed it with the highly successful FreeBSD 1.1 release in May of 1994.

Around this time, some rather unexpected storm clouds formed on the horizon as Novell and U.C. Berkeley settled their long-running lawsuit over the legal status of the Berkeley Net/2 tape. A condition of that settlement was U.C. Berkeley’s concession that three files of Net/2 were "encumbered" code and had to be removed as they were the property of Novell, who had in turn acquired it from AT&T some time previously. What Berkeley got in return was Novell’s "blessing" that the 4.4BSD-Lite release, when it was finally released, would be declared unencumbered and all existing Net/2 users would be strongly encouraged to switch. This included FreeBSD, and the project was given until the end of July 1994 to stop shipping its own Net/2 based product. Under the terms of that agreement, the project was allowed one last release before the deadline, that release being FreeBSD

FreeBSD then set about the arduous task of literally re-inventing itself from a completely new and rather incomplete set of 4.4BSD-Lite bits. Although only three files having to do with System V shared memory and semaphores were removed, many other changes and bug fixes had been made to the BSD distribution, so it was a huge task to merge all the FreeBSD developments into 4.4BSD-Lite. It took the project until November of 1994 to make this transition, and in December it released FreeBSD 2.0 to the world. Despite being still more than a little rough around the edges, the release was a significant success and was followed by the more robust and easier to install FreeBSD 2.0.5 release in June of 1995.

Since that time, FreeBSD has made a series of releases each time improving the stability, speed, and feature set of the previous version.

For now, long-term development projects continue to take place in the 15.0-CURRENT (main) branch, and snapshot releases of 15.0 are continually made available from the snapshot server as work progresses.

1.3.2. FreeBSD Project Goals

The goals of the FreeBSD Project are to provide software that may be used for any purpose and without strings attached. Many of us have a significant investment in the code (and project) and would certainly not mind a little financial compensation now and then, but we are definitely not prepared to 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 is, I believe, one of the most fundamental goals of Free Software and one that we enthusiastically support.

That code in our source tree which falls under the GNU General Public License (GPL) or 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, prefer software submitted under the more relaxed BSD license when it is a reasonable option to do so.

1.3.3. The FreeBSD Development Model

The development of FreeBSD is a very open and flexible process, being literally built from the contributions of thousands of people around the world, as can be seen from our list of contributors. FreeBSD’s development infrastructure allows these thousands of contributors to collaborate over the Internet. We are constantly on the lookout for new volunteers, and those interested in becoming more closely involved should consult the article on Contributing to FreeBSD.

Useful things to know about the FreeBSD Project and its development process, whether working independently or in close cooperation:

The Git repositories

For several years, the central source tree for FreeBSD was maintained by CVS (Concurrent Versions System), a freely available source code control tool. In June 2008, the Project switched to using SVN (Subversion). The switch was deemed necessary, as the technical limitations imposed by CVS were becoming obvious due to the rapid expansion of the source tree and the amount of history already stored. The Documentation Project and Ports Collection repositories also moved from CVS to SVN in May 2012 and July 2012, respectively. In December 2020, the Project migrated Source and Documentation repositories to Git, with Ports following suit in April 2021. Please refer to the Obtaining the Source section for more information on obtaining the FreeBSD src/ repository and Using the Ports Collection for details on obtaining the FreeBSD Ports Collection.

The committers list

The committers are the people who have push access to the Git repository, and are authorized to make modifications to the FreeBSD source (the term "committer" comes from commit, the source control command which is used to bring new changes into the repository). Anyone can submit a bug to the Bug Database. Before submitting a bug report, the FreeBSD mailing lists, IRC channels, or forums can be used to help verify that an issue is actually a bug.

The FreeBSD core team

The FreeBSD core team would be equivalent to the board of directors if the FreeBSD Project were a company. The primary task of the core team is to make sure the project, as a whole, is in good shape and is heading in the right directions. Inviting dedicated and responsible developers to join our group of committers is one of the functions of the core team, as is the recruitment of new core team members as others move on. The current core team was elected from a pool of committer candidates in May 2022. Elections are held every 2 years.

Like most developers, most members of the core team are also volunteers when it comes to FreeBSD development and do not benefit from the project financially, so "commitment" should also not be misconstrued as meaning "guaranteed support." The "board of directors" analogy above is not very accurate, and it may be more suitable to say that these are the people who gave up their lives in favor of FreeBSD against their better judgement!

The FreeBSD Foundation

The FreeBSD Foundation is a 501(c)(3), US-based, non-profit organization dedicated to supporting and promoting the FreeBSD Project and community worldwide. The Foundation funds software development via project grants and provides staff to immediately respond to urgent problems and implement new features and functionality. The Foundation purchases hardware to improve and maintain FreeBSD infrastructure, and funds staffing to improve test coverage, continuous integration and automation. The Foundation advocates for FreeBSD by promoting FreeBSD at technical conferences and events around the world. The Foundation also provides workshops, educational material, and presentations to recruit more users and contributors to FreeBSD. The Foundation also represents the FreeBSD Project in executing contracts, license agreements, and other legal arrangements that require a recognized legal entity.

Outside contributors

Last, but definitely not least, the largest group of developers are the users themselves who provide feedback and bug fixes to us on an almost constant basis. The primary way of keeping in touch with the development of the FreeBSD base system is to subscribe to the FreeBSD technical discussions mailing list where such things are discussed. For porting third party applications, it would be the FreeBSD ports mailing list. For documentation - FreeBSD documentation project mailing list. See Resources on the Internet for more information about the various FreeBSD mailing lists.

The FreeBSD Contributors List is a long and growing one, so why not join it by contributing something back to FreeBSD today? Providing code is not the only way!

In summary, our development model is organized as a loose set of concentric circles. The centralized model is designed for the convenience of the users of FreeBSD, who are provided with an easy way of tracking one central code base, not to keep potential contributors out! Our desire is to present a stable operating system with a large set of coherent application programs that the users can easily install and use - this model works very well in accomplishing that.

All we ask of those who would join us as FreeBSD developers is some of the same dedication its current people have to its continued success!

1.3.4. Third Party Programs

In addition to the base distributions, FreeBSD offers a ported software collection with thousands of commonly sought-after programs. The list of ports ranges from HTTP servers to games, languages, editors, and almost everything in between. There are about 36000 ports; the entire Ports Collection requires approximately 3 GB. To compile a port, you simply change to the directory of the program you wish to install, type make install, and let the system do the rest. The full original distribution for each port you build is retrieved dynamically so you need only enough disk space to build the ports you want.

Almost every port is also provided as a pre-compiled "package", which can be installed with a simple command (pkg install) by those who do not wish to compile their own ports from source. More information on packages and ports can be found in Installing Applications: Packages and Ports.

1.3.5. Additional Documentation

All supported FreeBSD versions provide an option in the installer to install additional documentation under /usr/local/share/doc/freebsd during the initial system setup. Documentation may also be installed later using packages:

# pkg install en-freebsd-doc

For localized versions replace the "en" with the language prefix of choice. Be aware that some of the localised versions might be out of date and might contain information that is no longer correct or relevant. You may view the locally installed manuals with a web browser using the following URLs:

The FreeBSD Handbook




You can always find up to date documentation at The Documentation Portal.

All trademarks are the property of their respective owners.

Chapter 2. Installing FreeBSD

2.1. Synopsis

FreeBSD supports different architectures including amd64, ARM®, RISC-V®, and PowerPC®. Depending on the architecture and platform, different images can be downloaded to install or directly run FreeBSD.

The image types are:

  • Virtual Machine disk images, such as qcow2, vmdk, vhd, and raw device images. These are not installation images, but images that have FreeBSD preinstalled and ready for post-installation tasks. Virtual machine images are also commonly used in cloud environments.

  • SD card images, for embedded systems such as Raspberry Pi. These files must be uncompressed and written as a raw image to an SD card, from which the board will boot.

  • Installation images to boot from an ISO or USB device to install FreeBSD on a drive for the usual desktop, laptop, or server system.

The rest of this chapter describes the third case, explaining how to install FreeBSD using the text-based installation program named bsdinstall. There may be minor differences between the installer and what is shown here, so use this chapter as a general guide rather than as a set of literal instructions.

After reading this chapter, you will know:

  • How to obtain FreeBSD images and create FreeBSD installation media.

  • How to start bsdinstall.

  • The questions bsdinstall will ask, what they mean, and how to answer them.

  • How to troubleshoot a failed installation.

  • How to access a live version of FreeBSD before committing to an installation.

2.2. Minimum Hardware Requirements

The hardware requirements to install FreeBSD vary by architecture and version. Hardware architectures and devices supported by a FreeBSD release are listed on the FreeBSD Release Information page. The FreeBSD download page also has recommendations for choosing the correct image for different architectures.

2.3. Pre-Installation Tasks

Once it has been determined that the system meets the minimum hardware requirements for installing FreeBSD, the installation file should be downloaded and the installation media prepared. Before doing this, check that the system is ready for an installation by verifying the items in this checklist:

  1. Back Up Important Data

    Before installing any operating system, always backup all important data first. Do not store the backup on the system being installed. Instead, save the data to a removable disk such as a USB drive, another system on the network, or an online backup service. Test the backup before starting the installation to make sure it contains all of the needed files. Once the installer formats the system’s disk, all data stored on that disk will be lost.

  2. Decide Where to Install FreeBSD

    If FreeBSD will be the only operating system installed, this step can be skipped. But if FreeBSD will share the disk with another operating system, decide which disk or partition will be used for FreeBSD.

    In the i386 and amd64 architectures, disks can be divided into multiple partitions using one of two partitioning schemes. A traditional Master Boot Record (MBR) holds a partition table defining up to four primary partitions. For historical reasons, FreeBSD calls these primary partition slices. One of these primary partitions can be made into an extended partition containing multiple logical partitions. The GUID Partition Table (GPT) is a newer and simpler method of partitioning a disk. Common GPT implementations allow up to 128 partitions per disk, eliminating the need for logical partitions.

    The FreeBSD boot loader requires either a primary or GPT partition. If all of the primary or GPT partitions are already in use, one must be freed for FreeBSD. To create a partition without deleting existing data, use a partition resizing tool to shrink an existing partition and create a new partition using the freed space.

    A variety of free and commercial partition resizing tools are listed at List of disk partitioning software wikipedia entry. GParted Live is a free live CD which includes the GParted partition editor.

    When used properly, disk shrinking utilities can safely create space for creating a new partition. Since the possibility of selecting the wrong partition exists, always backup any important data and verify the integrity of the backup before modifying disk partitions.

    Disk partitions containing different operating systems make it possible to install multiple operating systems on one computer. An alternative is to use virtualization which allows multiple operating systems to run at the same time without modifying any disk partitions.

  3. Collect Network Information

    Some FreeBSD installation methods require a network connection in order to download the installation files. After any installation, the installer will offer to setup the system’s network interfaces.

    If the network has a DHCP server, it can be used to provide automatic network configuration. If DHCP is not available, the following network information for the system must be obtained from the local network administrator or Internet service provider:

    Required Network Information

    1. IP address

    2. Subnet mask

    3. IP address of default gateway

    4. Domain name of the network

    5. IP addresses of the network’s DNS servers

  4. Check for FreeBSD Errata

    Although the FreeBSD Project strives to ensure that each release of FreeBSD is as stable as possible, bugs occasionally creep into the process. On very rare occasions those bugs affect the installation process. As these problems are discovered and fixed, they are noted in the FreeBSD Errata page of each version. Check the errata before installing to make sure that there are no problems that might affect the installation.

    Information and errata for all the releases can be found on the FreeBSD Release Information page.

2.3.1. Prepare the Installation Media

The FreeBSD installer is not an application that can be run from within another operating system. Instead, download a FreeBSD installation file, burn it to the media associated with its file type and size (CD, DVD, or USB), and boot the system to install from the inserted media.

FreeBSD installation files are available at the FreeBSD download page. Each installation file’s name includes the release version of FreeBSD, the architecture, and the type of file.

Installation files are available in several formats, compressed with xz(1) or uncompressed. The formats vary depending on computer architecture and media type.

Installation file types:

  • -bootonly.iso: This is the smallest installation file as it only contains the installer. A working Internet connection is required during installation as the installer will download the files it needs to complete the FreeBSD installation. This file should be burned to optical media.

  • -disc1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. This file should be burned to optical media.

  • -dvd1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It also contains a set of popular binary packages for installing a window manager and some applications so that a complete system can be installed from media without requiring a connection to the Internet. This file should be burned to optical media.

  • -memstick.img: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. Write this file to a USB stick as shown in Writing an Image File to USB.

  • -mini-memstick.img: Like -bootonly.iso, does not include installation files, but downloads them as needed. A working internet connection is required during installation. It should be written to a USB stick as shown in Writing an Image File to USB.

After downloading the image file, download at least one checksum file from the same directory. There are two checksum files available, named after the release number and the architecture name. For example: CHECKSUM.SHA256-FreeBSD-13.1-RELEASE-amd64 and CHECKSUM.SHA512-FreeBSD-13.1-RELEASE-amd64.

After downloading one of the files (or both), calculate the checksum for the image file and compare it with the one shown in the checksum file. Note that you need to compare the calculated checksum against the correct file, as they correspond to two different algorithms: SHA256 and SHA512. FreeBSD provides sha256(1) and sha512(1) that can be used for calculating the checksum. Other operating systems have similar programs.

Verifying the checksum in FreeBSD can be done automatically using sha256sum(1) (and sha512sum(1)) by executing:

% sha256sum -c CHECKSUM.SHA256-FreeBSD-13.1-RELEASE-amd64 FreeBSD-13.1-RELEASE-amd64-dvd1.iso
FreeBSD-13.1-RELEASE-amd64-dvd1.iso: OK

The checksums must match exactly. If the checksums do not match, the image file is corrupt and must be downloaded again. Writing an Image File to USB

The *memstick.img file is an image of the complete contents of a memory stick. It cannot be copied to the target device as a file. Several applications are available for writing the *.img to a USB stick. This section describes two of these utilities.

Before proceeding, back up any important data on the USB stick. This procedure will erase the existing data on the stick.

Procedure. Using dd to write the image

This example uses /dev/da0 as the target device where the image will be written. Be very careful that the correct device is used as this command will destroy the existing data on the specified target device.

  1. The command-line utility is available on BSD, Linux®, and Mac OS® systems. To burn the image using dd, insert the USB stick and determine its device name. Then, specify the name of the downloaded installation file and the device name for the USB stick. This example burns the amd64 installation image to the first USB device on an existing FreeBSD system.

    # dd if=FreeBSD-13.1-RELEASE-amd64-memstick.img of=/dev/da0 bs=1M conv=sync

    If this command fails, verify that the USB stick is not mounted and that the device name is for the disk, not a partition.

    Some operating systems might require this command to be run with sudo(8). The dd(1) syntax varies slightly across different platforms; for example, Mac OS® requires a lower-case bs=1m. Systems like Linux® might buffer writes. To force all writes to complete, use sync(8).

Procedure. Using Windows® to Write the Image

Be sure to give the correct drive letter as the existing data on the specified drive will be overwritten and destroyed.

  1. Obtaining Image Writer for Windows®

    Image Writer for Windows® is a free application that can correctly write an image file to a memory stick. Download it from win32diskimager home page and extract it into a folder.

  2. Writing the Image with Image Writer

    Double-click the Win32DiskImager icon to start the program. Verify that the drive letter shown under Device is the drive with the memory stick. Click the folder icon and select the image to be written to the memory stick. Click Save to accept the image file name. Verify that everything is correct, and that no folders on the memory stick are open in other windows. When everything is ready, click Write to write the image file to the memory stick.

2.4. Starting the Installation

By default, the installation will not make any changes to the disk(s) before the following message:

Your changes will now be written to disk. If you
have chosen to overwrite existing data, it will
be PERMANENTLY ERASED. Are you sure you want to
commit your changes?

The install can be exited at any time prior to this warning. If there is a concern that something is incorrectly configured, just turn the computer off before this point and no changes will be made to the system’s disks.

This section describes how to boot the system from the installation media which was prepared using the instructions in Prepare the Installation Media. When using a bootable USB stick, plug in the USB stick before turning on the computer. When booting from CD or DVD, turn on the computer and insert the media at the first opportunity. How to configure the system to boot from the inserted media depends upon the architecture.

2.4.1. FreeBSD Boot Menu

Once the system boots from the installation media, a menu similar to the following will be displayed:

FreeBSD boot loader menu
Figure 1. FreeBSD Boot Loader Menu

By default, the menu will wait ten seconds for user input before booting into the FreeBSD installer or, if FreeBSD is already installed, before booting into FreeBSD. To pause the boot timer in order to review the selections, press Space. To select an option, press its highlighted number, character, or key. The following options are available.

  • Boot Multi User: This will continue the FreeBSD boot process. If the boot timer has been paused, press 1, upper- or lower-case B, or Enter.

  • Boot Single User: This mode can be used to fix an existing FreeBSD installation as described in “Single-User Mode”. Press 2 or the upper- or lower-case S to enter this mode.

  • Escape to loader prompt: This will boot the system into a repair prompt that contains a limited number of low-level commands. This prompt is described in “Stage Three”. Press 3 or Esc to boot into this prompt.

  • Reboot: Reboots the system.

  • Cons: Allow to continue the installation by video, serial, Dual (serial primary) or Dual (Video primary)

  • Kernel: Loads a different kernel.

  • Boot Options: Opens the menu shown in, and described under, FreeBSD Boot Options Menu.

Menu showing the different boot options supported
Figure 2. FreeBSD Boot Options Menu

The boot options menu is divided into two sections. The first section can be used to either return to the main boot menu or to reset any toggled options back to their defaults.

The next section is used to toggle the available options to On or Off by pressing the option’s highlighted number or character. The system will always boot using the settings for these options until they are modified. Several options can be toggled using this menu:

  • ACPI Support: If the system hangs during boot, try toggling this option to Off.

  • Safe Mode: If the system still hangs during boot even with ACPI Support set to Off, try setting this option to On.

  • Single User: Toggle this option to On to fix an existing FreeBSD installation as described in “Single-User Mode”. Once the problem is fixed, set it back to Off.

  • Verbose: Toggle this option to On to see more detailed messages during the boot process. This can be useful when troubleshooting a piece of hardware.

After making the needed selections, press 1 or Backspace to return to the main boot menu, then press Enter to continue booting into FreeBSD. A series of boot messages will appear as FreeBSD carries out its hardware device probes and loads the installation program. Once the boot is complete, the welcome menu shown in Welcome Menu will be displayed.

FreeBSD installation welcome menu
Figure 3. Welcome Menu

Press Enter to select the default of Install to enter the installer. The rest of this chapter describes how to use this installer. Otherwise, use the right or left arrows or the colorized letter to select the desired menu item. The Shell can be used to access a FreeBSD shell in order to use command line utilities to prepare the disks before installation. The Live CD option can be used to try out FreeBSD before installing it. The live version is described in Using the Live CD.

To review the boot messages, including the hardware device probe, press the upper- or lower-case S and then Enter to access a shell. At the shell prompt, type more /var/run/dmesg.boot and use the space bar to scroll through the messages. When finished, type exit to return to the welcome menu.

2.5. Using bsdinstall

This section shows the order of the bsdinstall menus and the type of information that will be asked before the system is installed. Use the arrow keys to highlight a menu option, then Space to select or deselect that menu item. When finished, press Enter to save the selection and move onto the next screen.

2.5.1. Selecting the Keymap Menu

Before starting the process, bsdinstall will load the keymap files as shown in Keymap Loading.

Keymap loading
Figure 4. Keymap Loading

After the keymaps have been loaded, bsdinstall displays the menu shown in Keymap Selection Menu. Use the up and down arrows to select the keymap that most closely represents the mapping of the keyboard attached to the system. Press Enter to save the selection.

Keymap selection menu showing all supported keyboards
Figure 5. Keymap Selection Menu

Pressing Esc will exit this menu and use the default keymap. If the choice of keymap is not clear, United States of America ISO-8859-1 is also a safe option.

In addition, when selecting a different keymap, the user can try the keymap and ensure it is correct before proceeding, as shown in Keymap Testing Menu.

Keymap testing menu
Figure 6. Keymap Testing Menu

2.5.2. Setting the Hostname

The next bsdinstall menu is used to set the hostname for the newly installed system.

Setting the hostname
Figure 7. Setting the Hostname

Type in a hostname that is unique for the network. It should be a fully-qualified hostname, such as

2.5.3. Selecting Components to Install

Next, bsdinstall will prompt to select optional components to install.

Different components that can be installed. Example: base-dbg
Figure 8. Selecting Components to Install

Deciding which components to install will depend largely on the intended use of the system and the amount of disk space available. The FreeBSD kernel and userland, collectively known as the base system, are always installed. Depending on the architecture, some of these components may not appear:

  • base-dbg - Base tools like cat and ls, among many others, with debug symbols activated.

  • kernel-dbg - Kernel and modules with debug symbols activated.

  • lib32-dbg - Compatibility libraries for running 32-bit applications on a 64-bit version of FreeBSD with debug symbols activated.

  • lib32 - Compatibility libraries for running 32-bit applications on a 64-bit version of FreeBSD.

  • ports - The FreeBSD Ports Collection is a collection of files which automates the downloading, compiling and installation of third-party software packages. Installing Applications: Packages and Ports discusses how to use the Ports Collection.

    The installation program does not check for adequate disk space. Select this option only if sufficient hard disk space is available. The FreeBSD Ports Collection takes up about 3 GB of disk space.

  • src - The complete FreeBSD source code for both the kernel and the userland. Although not required for the majority of applications, it may be required to build device drivers, kernel modules, or some applications from the Ports Collection. It is also used for developing FreeBSD itself. The full source tree requires 1 GB of disk space and recompiling the entire FreeBSD system requires an additional 5 GB of space.

  • tests - FreeBSD Test Suite.

2.5.4. Installing from the Network

The menu shown in Installing from the Network only appears when installing from a -bootonly.iso or -mini-memstick.img, as this installation media does not hold copies of the installation files. Since the installation files must be retrieved over a network connection, this menu indicates that the network interface must be configured first. If this menu is shown in any step of the process, remember to follow the instructions in Configuring Network Interfaces.

Indicates that certain components have not been found and will be downloaded using the network.
Figure 9. Installing from the Network

2.6. Allocating Disk Space

The next menu is used to determine the method for allocating disk space.

Shows the different partition options. Example: Manual
Figure 10. Partitioning Choices

bsdinstall gives the user four methods for allocating disk space:

  • Auto (ZFS) partitioning creates a root-on-ZFS system with optional GELI encryption support for boot environments.

  • Auto (UFS) partitioning automatically sets up the disk partitions using the UFS file system.

  • Manual partitioning allows advanced users to create customized partitions from menu options.

  • Shell opens a shell prompt where advanced users can create customized partitions using command-line utilities like gpart(8), fdisk(8), and bsdlabel(8).

This section describes what to consider when laying out the disk partitions. It then demonstrates how to use the different partitioning methods.

2.6.1. Designing the Partition Layout

The default partition layout for file systems includes one file system for the entire system. When using UFS it may be worth considering the use of multiple file systems if you have sufficient disk space or multiple disks. When laying out file systems, remember that hard drives transfer data faster from the outer tracks to the inner. Thus, smaller and heavier-accessed file systems should be closer to the outside of the drive, while larger partitions like /usr should be placed toward the inner parts of the disk. It is a good idea to create partitions in an order similar to: /, swap, /var, and /usr.

The size of the /var partition reflects the intended machine’s usage. This partition is used to hold mailboxes, log files, and printer spools. Mailboxes and log files can grow to unexpected sizes depending on the number of users and how long log files are kept. On average, most users rarely need more than about a gigabyte of free disk space in /var.

Sometimes, a lot of disk space is required in /var/tmp. When new software is installed, the packaging tools extract a temporary copy of the packages under /var/tmp. Large software packages, like Firefox or LibreOffice may be tricky to install if there is not enough disk space under /var/tmp.

The /usr partition holds many of the files which support the system, including the FreeBSD Ports Collection and system source code. At least 2 gigabytes of space is recommended for this partition. Also, note that home directories for users are placed in /usr/home by default, but can be placed on another partition. By default, /home is a symbolic link to /usr/home.

When selecting partition sizes, keep the space requirements in mind. Running out of space in one partition while barely using another can be a hassle.

As a rule of thumb, the swap partition should be about double the size of physical memory (RAM). Systems with minimal RAM (less for larger-memory configurations) may perform better with more swap. Configuring too little swap can lead to inefficiencies in the VM page scanning code and might create issues later if more memory is added.

On larger systems with multiple SCSI disks or multiple IDE disks operating on different controllers, it is recommended that swap be configured on each drive, up to four drives. The swap partitions should be approximately the same size. The kernel can handle arbitrary sizes, but internal data structures scale to 4 times the largest swap partition. Keeping the swap partitions near the same size will allow the kernel to optimally stripe swap space across disks. Large swap sizes may elicit a kernel warning message about the total configured swap. The limit is raised by increasing the amount of memory allowed for keeping track of swap allocations, as instructed by the warning message. It might be easier to recover from a runaway program before being forced to reboot.

By properly partitioning a system, fragmentation introduced in the smaller write-heavy partitions will not bleed over into the mostly read partitions. Keeping the write-loaded partitions closer to the disk’s edge will increase I/O performance in the partitions where it occurs the most. While I/O performance in the larger partitions may be needed, shifting them more toward the edge of the disk will not lead to a significant performance improvement over moving /var to the edge.

2.6.2. Guided Partitioning Using UFS

When this method is selected, a menu will display the available disk(s). If multiple disks are connected, choose the one where FreeBSD is to be installed.

Shows the list of disks on which FreeBSD can be installed
Figure 11. Selecting from Multiple Disks

Once the disk is selected, the next menu prompts to install to either the entire disk or to create a partition using free space. If Entire Disk is chosen, a general partition layout filling the whole disk is automatically created. Selecting Partition creates a partition layout from the unused space on the disk.

Menu asking the user if he wants to use all the available space on the disk or wants to make a partition
Figure 12. Selecting Entire Disk or Partition

After the Entire Disk option is chosen, bsdinstall displays a dialog indicating that the disk will be erased.

Menu indicating the user that all data on the disk will be deleted and asking for confirmation
Figure 13. Confirmation

The next menu shows a list with the available partition scheme types. GPT is usually the most appropriate choice for amd64 computers. Older computers that are not compatible with GPT should use MBR. The other partition schemes are generally used for uncommon or older computers. More information is available in Partitioning Schemes.

Menu showing the user the different the different types of partition that exist and requesting one of them
Figure 14. Select Partition Scheme

After the partition layout has been created, review it to ensure it meets the needs of the installation. Selecting Revert will reset the partitions to their original values. Pressing Auto will recreate the automatic FreeBSD partitions. Partitions can also be manually created, modified, or deleted. When the partitioning is correct, select Finish to continue with the installation.

Menu showing created partitions
Figure 15. Review Created Partitions

Once the disks are configured, the next menu provides the last chance to make changes before the selected drives are formatted. If changes need to be made, select Back to return to the main partitioning menu. Revert & Exit exits the installer without making any changes to the drive. Otherwise, select Commit to start the installation process.

Menu indicating to the user that all changes will be written to disk and informing that if he decides to continue the existing data will be permanently deleted.
Figure 16. Final Confirmation

To continue with the installation process, go to Fetching Distribution Files.

2.6.3. Manual Partitioning

Selecting this method opens the partition editor:

Menu showing the Partition Editor.
Figure 17. Manually Create Partitions

Highlight the installation drive (ada0 in this example) and select Create to display a menu of available partition schemes:

Menu showing the different kind of partition schemes
Figure 18. Manually Create Partitions

GPT is usually the most appropriate choice for amd64 computers. Older computers that are not compatible with GPT should use MBR. The other partition schemes are generally used for uncommon or older computers.

Table 1. Partitioning Schemes


Apple Partition Map, used by PowerPC®.


BSD label without an MBR, sometimes called dangerously dedicated mode as non-BSD disk utilities may not recognize it.


GUID Partition Table.


Master Boot Record.

After the partitioning scheme has been selected and created, select Create again to create the partitions. The Tab key is used to give focus to the fields (after cycling through <OK>, <Options>, and <Cancel>).

Menu requesting type
Figure 19. Manually Create Partitions

A standard FreeBSD GPT installation uses at least three partitions, including either UFS or ZFS:

  • freebsd-boot or efi - Holds the FreeBSD boot code.

  • freebsd-ufs - A FreeBSD UFS file system.

  • freebsd-zfs - A FreeBSD ZFS file system. More information about ZFS is available in The Z File System (ZFS).

  • freebsd-swap - FreeBSD swap space.

Refer to gpart(8) for descriptions of the available GPT partition types.

Multiple file system partitions can be created. Some people prefer a traditional layout with separate partitions for /, /var, /tmp, and /usr.

Note that /tmp can be added later as a memory-based file system (tmpfs(5)) on systems with sufficient memory.

The Size may be entered with common abbreviations: K for kilobytes, M for megabytes, or G for gigabytes.

Proper sector alignment provides the best performance, and making partition sizes even multiples of 4K bytes helps to ensure alignment on drives with either 512-byte or 4K-byte sectors. Generally, using partition sizes that are even multiples of 1M or 1G is the easiest way to make sure every partition starts at an even multiple of 4K. There is one exception: the freebsd-boot partition should be no larger than 512K due to current boot code limitations.

A Mountpoint is needed if the partition will contain a file system. If only a single UFS partition will be created, the mountpoint should be /.

The Label is a name by which the partition will be known. Drive names or numbers can change if the drive is connected to a different controller or port, but the partition label does not change. Referring to labels instead of drive names and partition numbers in files like /etc/fstab makes the system more tolerant to hardware changes. GPT labels appear in /dev/gpt/ when a disk is attached. Other partitioning schemes have different label capabilities and their labels appear in different directories in /dev/.

Use a unique label on every partition to avoid conflicts from identical labels. A few letters from the computer’s name, use, or location can be added to the label. For instance, use labroot or rootfslab for the UFS root partition on the computer named lab.

Example 1. Creating Traditional Split File System Partitions

For a traditional partition layout where the /, /var, /tmp, and /usr directories are separate file systems on their own partitions, create a GPT partitioning scheme, then create the partitions as shown. Partition sizes shown are typical for a 20G target disk. If more space is available on the target disk, larger swap or /var partitions may be useful. Labels shown here are prefixed with ex for "example", but readers should use other unique label values as described above.

By default, FreeBSD’s gptboot expects the first UFS partition to be the / partition.

Partition TypeSizeMountpointLabel



















accept the default (remainder of the disk)



After the custom partitions have been created, select Finish to continue with the installation and go to Fetching Distribution Files.

2.6.4. Guided Partitioning Using Root-on-ZFS

This partitioning mode only works with whole disks and will erase the contents of the entire disk. The main ZFS configuration menu offers a number of options to control the creation of the pool.

Menu showing the different options to configure the ZFS pool
Figure 20. ZFS Partitioning Menu

Here is a summary of the options in this menu:

  • Install - Proceed with the installation with the selected options.

  • Pool Type/Disks - Configure the Pool Type and the disk(s) that will constitute the pool. The automatic ZFS installer currently only supports the creation of a single top level vdev, except in stripe mode. To create more complex pools, use the instructions in Shell Mode Partitioning to create the pool.

  • Rescan Devices - Repopulate the list of available disks.

  • Disk Info - This menu can be used to inspect each disk, including its partition table and various other information such as the device model number and serial number, if available.

  • Pool Name - Establish the name of the pool. The default name is zroot.

  • Force 4K Sectors? - Force the use of 4K sectors. By default, the installer will automatically create partitions aligned to 4K boundaries and force ZFS to use 4K sectors. This is safe even with 512 byte sector disks, and has the added benefit of ensuring that pools created on 512 byte disks will be able to have 4K sector disks added in the future, either as additional storage space or as replacements for failed disks. Press the Enter key to chose to activate it or not.

  • Encrypt Disks? - Encrypting the disks allows the user to encrypt the disks using GELI. More information about disk encryption is available in “Disk Encryption with geli”. Press the Enter key to choose whether to activate it or not.

  • Partition Scheme - Choose the partition scheme. GPT is the recommended option in most cases. Press the Enter key to chose between the different options.

  • Swap Size - Establish the amount of swap space.

  • Mirror Swap? - Whether to mirror the swap between the disks. Be aware that enabling mirror swap will break crash dumps. Press the Enter key to activate it or not.

  • Encrypt Swap? - Whether to encrypt the swap. This will encrypt the swap with a temporary key each time the system boots, and discards it on reboot. Press the Enter key to choose to activate it or not. More information about swap encryption in “Encrypting Swap”.

Select T to configure the Pool Type and the disk(s) that will constitute the pool.

Menu requesting the Virtual Device type. Ex: stripe
Figure 21. ZFS Pool Type

Here is a summary of the Pool Type that can be selected in this menu:

  • stripe - Striping provides maximum storage of all connected devices, but no redundancy. If just one disk fails the data on the pool is lost irrevocably.

  • mirror - Mirroring stores a complete copy of all data on every disk. Mirroring provides good read performance because data is read from all disks in parallel. Write performance is slower as the data must be written to all disks in the pool. Allows all but one disk to fail. This option requires at least two disks.

  • raid10 - Striped mirrors. Provides the best performance, but the least storage. This option needs at least an even number of disks and a minimum of four disks.

  • raidz1 - Single Redundant RAID. Allow one disk to fail concurrently. This option needs at least three disks.

  • raidz2 - Double Redundant RAID. Allows two disks to fail concurrently. This option needs at least four disks.

  • raidz3 - Triple Redundant RAID. Allows three disks to fail concurrently. This option needs at least five disks.

Once a Pool Type has been selected, a list of available disks is displayed, and the user is prompted to select one or more disks to make up the pool. The configuration is then validated to ensure that enough disks are selected. If validation fails, select <Change Selection> to return to the list of disks or <Back> to change the Pool Type.

Menu requesting how many disks will be added to the pool
Figure 22. Disk Selection
Menu indicating that not enough disks have been selected.
Figure 23. Invalid Selection

If one or more disks are missing from the list, or if disks were attached after the installer was started, select - Rescan Devices to repopulate the list of available disks.

Device rescan
Figure 24. Rescan Devices

To avoid accidentally erasing the wrong disk, the - Disk Info menu can be used to inspect each disk, including its partition table and various other information such as the device model number and serial number, if available.

Menu showing the information of the partitions.
Figure 25. Analyzing a Disk

Select N to configure the Pool Name. Enter the desired name, then select <OK> to establish it or <Cancel> to return to the main menu and leave the default name.

Menu requesting the name of the pool.
Figure 26. Pool Name

Select S to set the amount of swap. Enter the desired amount of swap, then select <OK> to establish it or <Cancel> to return to the main menu and let the default amount.

Menu requesting the amount of swap memory
Figure 27. Swap Amount

Once all options have been set to the desired values, select the >>> Install option at the top of the menu. The installer then offers a last chance to cancel before the contents of the selected drives are destroyed to create the ZFS pool.

Menu indicating to the user that the data will be lost
Figure 28. Last Chance

If GELI disk encryption was enabled, the installer will prompt twice for the passphrase to be used to encrypt the disks. Initialization of the encryption then begins.

Menu requesting the password to encrypt the devices.
Figure 29. Disk Encryption Password
Menu showing that the encryption is initializing.
Figure 30. Initializing Encryption

The installation then proceeds normally. To continue with the installation, go to Fetching Distribution Files.

2.6.5. Shell Mode Partitioning

When creating advanced installations, the bsdinstall partitioning menus may not provide the level of flexibility required. Advanced users can select the Shell option from the partitioning menu in order to manually partition the drives, create the file system(s), populate /tmp/bsdinstall_etc/fstab, and mount the file systems under /mnt. Once this is done, type exit to return to bsdinstall and continue the installation.

2.7. Fetching Distribution Files

Installation time will vary depending on the distributions chosen, installation media, and speed of the computer. A series of messages will indicate the progress.

First, the installer formats the selected disk(s) and initializes the partitions. Next, in the case of a bootonly media or mini memstick, it downloads the selected components:

Menu showing the download of the different components.
Figure 31. Fetching Distribution Files

Next, the integrity of the distribution files is verified to ensure they have not been corrupted during download or misread from the installation media:

Menu showing the verification of the different components.
Figure 32. Verifying Distribution Files

Finally, the verified distribution files are extracted to the disk:

Menu showing the extraction of the different components.
Figure 33. Extracting Distribution Files

Once all requested distribution files have been extracted, bsdinstall displays the first post-installation configuration screen. The available post-configuration options are described in the next section.

2.8. Network Interfaces, Accounts, Time Zone, Services and Hardening

2.8.1. Setting the root Password

First, the root password must be set. While entering the password, the characters being typed are not displayed on the screen. The password must be entered twice to prevent typing errors.

Menu showing requesting the password for the root user.
Figure 34. Setting the root Password

2.8.2. Configuring Network Interfaces

Next, a list of the network interfaces found on the computer is shown. Select the interface to configure.

Menu showing the different network interfaces to configure.
Figure 35. Choose a Network Interface

If an Ethernet interface is selected, the installer will skip ahead to the menu shown in Choose IPv4 Networking. If a wireless network interface is chosen, the system will instead scan for wireless access points:

Menu showing wireless network scanning.
Figure 36. Scanning for Wireless Access Points

Wireless networks are identified by a Service Set Identifier (SSID); a short, unique name given to each network. SSIDs found during the scan are listed, followed by a description of the encryption types available for that network. If the desired SSID does not appear in the list, select Rescan to scan again. If the desired network still does not appear, check for problems with antenna connections or try moving the computer closer to the access point. Rescan after each change is made.

Menu showing the different wireless networks to connect to.
Figure 37. Choosing a Wireless Network

Next, enter the encryption information for connecting to the selected wireless network. WPA2 encryption is strongly recommended over older encryption types such as WEP, which offer little security. If the network uses WPA2, input the password, also known as the Pre-Shared Key (PSK). For security reasons, the characters typed into the input box are displayed as asterisks.

Menu requesting the wireless network password.
Figure 38. WPA2 Setup

Next, choose whether or not an IPv4 address should be configured on the Ethernet or wireless interface:

Menu indicating if IPv4 wants to be configured for the selected interface.
Figure 39. Choose IPv4 Networking

There are two methods of IPv4 configuration. DHCP will automatically configure the network interface correctly and should be used if the network provides a DHCP server. Otherwise, the addressing information needs to be input manually as a static configuration.

Do not enter random network information as it will not work. If a DHCP server is not available, obtain the information listed in Required Network Information from the network administrator or Internet service provider.

If a DHCP server is available, select Yes in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the DHCP server and obtains the addressing information for the system.

Menu indicating if DHCP wants to be configured for the selected interface.
Figure 40. Choose IPv4 DHCP Configuration

If a DHCP server is not available, select No and input the following addressing information in this menu:

Menu requesting data to configure IPv4 network.
Figure 41. IPv4 Static Configuration
  • IP Address - The IPv4 address assigned to this computer. The address must be unique and not already in use by another device on the local network.

  • Subnet Mask - The subnet mask for the network.

  • Default Router - The IP address of the network’s default gateway.

The next screen will ask if the interface should be configured for IPv6. If IPv6 is available and desired, choose Yes to select it.

Menu indicating if IPv6 wants to be configured for the selected interface.
Figure 42. Choose IPv6 Networking

IPv6 also has two methods of configuration. StateLess Address AutoConfiguration (SLAAC) will automatically request the correct configuration information from a local router. Refer to rfc4862 for more information. Static configuration requires manual entry of network information.

If an IPv6 router is available, select Yes in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the router and obtains the addressing information for the system.

Menu indicating if SLAAC wants to be configured for the selected interface.
Figure 43. Choose IPv6 SLAAC Configuration

If an IPv6 router is not available, select No and input the following addressing information in this menu:

Menu requesting data to configure IPv6 network.
Figure 44. IPv6 Static Configuration
  • IPv6 Address - The IPv6 address assigned to this computer. The address must be unique and not already in use by another device on the local network.

  • Default Router - The IPv6 address of the network’s default gateway.

The last network configuration menu is used to configure the Domain Name System (DNS) resolver, which converts hostnames to and from network addresses. If DHCP or SLAAC was used to autoconfigure the network interface, the Resolver Configuration values may already be filled in. Otherwise, enter the local network’s domain name in the Search field. DNS #1 and DNS #2 are the IPv4 and/or IPv6 addresses of the DNS servers. At least one DNS server is required.

Menu requesting data to configure DNS for the network.
Figure 45. DNS Configuration

Once the interface is configured, select a mirror site that is located in the same region of the world as the computer on which FreeBSD is being installed. Files can be retrieved more quickly when the mirror is close to the target computer, reducing installation time.

Selecting (Main Site) will automatically route you to the nearest mirror.

Menu requesting a network mirror.
Figure 46. Choosing a Mirror

2.8.3. Setting the Time Zone

The next series of menus are used to determine the correct local time by selecting the geographic region, country, and time zone. Setting the time zone allows the system to automatically correct for regional time changes, such as daylight savings time, and perform other time zone related functions properly.

The example shown here is for a machine located in the mainland time zone of Spain, Europe. The selections will vary according to the geographical location.

Menu requesting the timezone region.
Figure 47. Select a Region

The appropriate region is selected using the arrow keys and then pressing Enter.

Menu requesting the timezone country.
Figure 48. Select a Country

Select the appropriate country using the arrow keys and press Enter.

Menu requesting the timezone zone.
Figure 49. Select a Time Zone

The appropriate time zone is selected using the arrow keys and pressing Enter.

Menu requesting confirmation of the selected timezone.
Figure 50. Confirm Time Zone

Confirm the abbreviation for the time zone is correct.

Menu requesting the system date.
Figure 51. Select Date

The appropriate date is selected using the arrow keys and then pressing Set Date. Otherwise, the date selection can be skipped by pressing Skip.

Menu requesting the system time.
Figure 52. Select Time

The appropriate time is selected using the arrow keys and then pressing Set Time. Otherwise, the time selection can be skipped by pressing Skip.

2.8.4. Enabling Services

The next menu is used to configure which system services will be started whenever the system boots. All of these services are optional. Only start the services that are needed for the system to function.

Menu showing the different services available.
Figure 53. Selecting Additional Services to Enable

Here is a summary of the services that can be enabled in this menu:

  • local_unbound - Enable the DNS local unbound. It is necessary to keep in mind that this is a configuration only meant for use as a local caching forwarding resolver. If the objective is to set up a resolver for the entire network, install dns/unbound.

  • sshd - The Secure Shell (SSH) daemon is used to remotely access a system over an encrypted connection. Only enable this service if the system should be available for remote logins.

  • moused - Enable this service if the mouse will be used from the command-line system console.

  • ntpdate - Enable automatic clock synchronization at boot time. Note that the functionality of this program is now available in the ntpd(8) daemon and the ntpdate(8) utility will soon be retired.

  • ntpd - The Network Time Protocol (NTP) daemon for automatic clock synchronization. Enable this service if you wish to synchronise your system clock with a remote time server or pool.

  • powerd - System power control utility for power control and energy saving.

  • dumpdev - Crash dumps are useful when debugging issues with the system, so users are encouraged to enable them.

2.8.5. Enabling Hardening Security Options

The next menu is used to configure which security options will be enabled. All of these options are optional. But their use is encouraged.

Menu shoring the different hardening security options.
Figure 54. Selecting Hardening Security Options

Here is a summary of the options that can be enabled in this menu:

  • hide_uids - Hide processes running as other users (UID). This prevents unprivileged users from seeing running processes from other users.

  • hide_gids - Hide processes running as other groups (GID). This prevents unprivileged users from seeing running processes from other groups.

  • hide_jail - Hide processes running in jails. This prevents unprivileged users from seeing processes running inside jails.

  • read_msgbuf - Disable reading kernel message buffer for unprivileged users. Prevent unprivileged users from using dmesg(8) to view messages from the kernel’s log buffer.

  • proc_debug - Disable process debugging facilities for unprivileged users. Disables a variety of unprivileged inter-process debugging services, including some procfs functionality, ptrace(), and ktrace(). Please note that this will also prevent debugging tools such as lldb(1), truss(1) and procstat(1), as well as some built-in debugging facilities in certain scripting languages like PHP.

  • random_pid - Randomize the PID of processes.

  • clear_tmp - Clean /tmp when the system starts up.

  • disable_syslogd - Disable opening the syslogd network socket. By default, FreeBSD runs syslogd in a secure way with -s. This prevents the daemon from listening for incoming UDP requests on port 514. With this option enabled, syslogd will instead run with -ss, which prevents syslogd from opening any port. For more information, see syslogd(8).

  • disable_sendmail - Disable the sendmail mail transport agent.

  • secure_console - Make the command prompt request the root password when entering single-user mode.

  • disable_ddtrace - DTrace can run in a mode that affects the running kernel. Destructive actions may not be used unless explicitly enabled. Use -w to enable this option when using DTrace. For more information, see dtrace(1).

  • enable_aslr - Enable address layout randomization. For more information about address layout randomization the Wikipedia article can be consulted.

2.8.6. Add Users

The next menu prompts to create at least one user account. It is recommended to log into the system using a user account rather than as root. When logged in as root, there are essentially no limits or protection on what can be done. Logging in as a normal user is safer and more secure.

Select Yes to add new users.

Menu requesting if a user want to be added to the system.
Figure 55. Add User Accounts

Follow the prompts and input the requested information for the user account. The example shown in Enter User Information creates the asample user account.

Menu requesting different information for the new user.
Figure 56. Enter User Information

Here is a summary of the information to input:

  • Username - The name the user will enter to log in. A common convention is to use the first letter of the first name combined with the last name, as long as each username is unique for the system. The username is case sensitive and should not contain any spaces.

  • Full name - The user’s full name. This can contain spaces and is used as a description for the user account.

  • Uid - User ID. This is typically left blank so the system automatically assigns a value.

  • Login group - The user’s group. This is typically left blank to accept the default.

  • Invite user into other groups? - Additional groups to which the user will be added as a member. If the user needs administrative access, type wheel here.

  • Login class - Typically left blank for the default.

  • Shell - Type in one of the listed values to set the interactive shell for the user. Refer to Shells for more information about shells.

  • Home directory - The user’s home directory. The default is usually correct.

  • Home directory permissions - Permissions on the user’s home directory. The default is usually correct.

  • Use password-based authentication? - Typically yes so that the user is prompted to input their password at login.

  • Use an empty password? - Typically no as empty or blank passwords are insecure.

  • Use a random password? - Typically no so that the user can set their own password in the next prompt.

  • Enter password - The password for this user. Typed-in characters will not be shown on the screen.

  • Enter password again - The password must be typed again for verification.

  • Lock out the account after creation? - Typically no so that the user can log in.

After entering all the details, a summary is shown for review. If a mistake was made, enter no to correct it. Once everything is correct, enter yes to create the new user.

Menu showing the information of the new user and requesting if everything is correct.
Figure 57. Exit User and Group Management

If there are more users to add, answer the Add another user? question with yes. Enter no to finish adding users and continue the installation.

For more information on adding users and user management, see Users and Basic Account Management.

2.8.7. Final Configuration

After everything has been installed and configured, a final chance is provided to modify settings.

Menu showing different options to perform before finishing the installation. Ex: Add user
Figure 58. Final Configuration

Use this menu to make any changes or to do any additional configuration before completing the installation.

Once configuration is complete, select Exit.

Menu showing that the installation has finished. And asking if you want to open a shell to make manual changes.
Figure 59. Manual Configuration

bsdinstall will prompt for any additional configuration that needs to be done before rebooting into the new system. Select Yes to exit to a shell within the new system or No to proceed to the last step of the installation.

Menu showing that the installation has finished and asking whether to reboot the system or access the Live CD.
Figure 60. Complete the Installation

If further configuration or special setup is needed, select Live CD to boot the install media into Live CD mode.

If the installation is complete, select Reboot to reboot the computer and start the new FreeBSD system. Do not forget to remove the FreeBSD install media or the computer might boot from it again.

As FreeBSD boots, informational messages are displayed. After the system finishes booting, a login prompt is displayed. At the login: prompt, enter the username added during the installation. Avoid logging in as root. Refer to The Superuser Account for instructions on how to become the superuser when administrative access is needed.

The messages that appear during boot can be reviewed by pressing Scroll-Lock to turn on the scroll-back buffer. The PgUp, PgDn, and arrow keys can be used to scroll back through the messages. When finished, press Scroll-Lock again to unlock the display and return to the console. To review these messages once the system has been up for some time, type less /var/run/dmesg.boot from a command prompt. Press q to return to the command line after viewing.

If sshd was enabled in Selecting Additional Services to Enable, the first boot might be a bit slower as the system generates SSH host keys. Subsequent boots will be faster. The fingerprints of the keys are then displayed as in the following example:

Generating public/private rsa1 key pair.
Your identification has been saved in /etc/ssh/ssh_host_key.
Your public key has been saved in /etc/ssh/
The key fingerprint is:
The key's randomart image is:
+--[RSA1 1024]----+
|    o..          |
|   o . .         |
|  .   o          |
|       o         |
|    o   S        |
|   + + o         |
|o . + *          |
|o+ ..+ .         |
|==o..o+E         |
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/
The key fingerprint is:
The key's randomart image is:
+--[ DSA 1024]----+
|       ..     . .|
|      o  .   . + |
|     . ..   . E .|
|    . .  o o . . |
|     +  S = .    |
|    +  . = o     |
|     +  . * .    |
|    . .  o .     |
|      .o. .      |
Starting sshd.

Refer to OpenSSH for more information about fingerprints and SSH.

FreeBSD does not install a graphical environment by default. Refer to The X Window System for more information about installing and configuring a graphical window manager.

Proper shutdown of a FreeBSD computer helps protect data and hardware from damage. Do not turn off the power before the system has been properly shut down! If the user is a member of the wheel group, become the superuser by typing su at the command line and entering the root password. Then, type shutdown -p now and the system will shut down cleanly, and, if the hardware supports it, turn itself off.

2.9. Troubleshooting

This section covers basic installation troubleshooting, such as common problems people have reported.

Check the Hardware Notes listed on the FreeBSD Release Information page for the version of FreeBSD to make sure the hardware is supported.

Some installation problems can be avoided or alleviated by updating the firmware on various hardware components, most notably the motherboard. Motherboard firmware is usually referred to as the BIOS. Most motherboard and computer manufacturers have a website for upgrades and upgrade information.

Manufacturers generally advise against upgrading the motherboard BIOS unless there is a good reason for doing so, like a critical update. The upgrade process can go wrong, leaving the BIOS incomplete and the computer inoperative.

If the system hangs while probing hardware during boot or behaves strangely during the installation process, ACPI may be the culprit. FreeBSD makes extensive use of the system ACPI service on the i386 and amd64 platforms to aid in system configuration if it is detected during boot. Unfortunately, some bugs still exist in both the ACPI driver and within system motherboards and BIOS firmware. ACPI can be disabled by setting the hint.acpi.0.disabled hint in the third stage boot loader:

set hint.acpi.0.disabled="1"

This is reset each time the system is booted, so it is necessary to add hint.acpi.0.disabled="1" to the file /boot/loader.conf. More information about the boot loader can be found in “Synopsis”.

2.10. Using the Live CD

The welcome menu of bsdinstall, shown in Welcome Menu, provides a Live CD option. This is useful for those who are still wondering whether FreeBSD is the right operating system for them and want to test some of the features before installing.

The following points should be noted before using the Live CD:

  • To gain access to the system, authentication is required. The username is root and the password is blank.

  • As the system runs directly from the installation media, performance will be significantly slower than that of a system installed on a hard disk.

  • This option only provides a command prompt and not a graphical interface.

Chapter 3. FreeBSD Basics

3.1. Synopsis

This chapter covers the basic commands and functionality of the FreeBSD operating system. Much of this material is relevant for any UNIX®-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® 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.

3.2. 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:

FreeBSD/amd64 ( (ttyv0)


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, and ttyv0 indicates that this is the "system console". The second line is the login prompt.

Since FreeBSD is a multiuser system, it needs some way to distinguish between different users. This is accomplished by requiring every user to log into the system before gaining access to the programs on the system. Every user has a unique "username" and a personal "password".

To log into the system console, type the username that was configured during system installation, as described in Add Users, and press Enter. Then enter the password associated with the username and press Enter. The password is not echoed for security reasons.

Once the correct password is input, the message of the day (MOTD) will be displayed followed by a command prompt. Depending upon the shell that was selected when the user was created, this prompt will be a #, $, or % character. The prompt indicates that the user is now logged into the FreeBSD system console and ready to try the available commands.

3.2.1. 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 Alt+F1 through Alt+F8 have been reserved by FreeBSD for switching between virtual consoles. Use Alt+F1 to switch to the system console (ttyv0), Alt+F2 to access the first virtual console (ttyv1), Alt+F3 to access the second virtual console (ttyv2), and so on. When using Xorg as a graphical console, the combination becomes 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 kbdcontrol(1), vidcontrol(1), atkbd(4), syscons(4), and vt(4) for a more technical description of the FreeBSD console and its keyboard drivers.

In FreeBSD, the number of available virtual consoles is configured in this section of /etc/ttys:

# name    getty                         type  status comments
ttyv0   "/usr/libexec/getty Pc"         xterm   on  secure
# Virtual terminals
ttyv1   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv2   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv3   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv4   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv5   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv6   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv7   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv8   "/usr/X11R6/bin/xdm -nodaemon"  xterm   off secure

To disable a virtual console, put a comment symbol (#) at the beginning of the line representing that virtual console. For example, to reduce the number of available virtual consoles from eight to four, put a # in front of the last four lines representing virtual consoles ttyv5 through ttyv8. Do not comment out the line for the system console ttyv0. Note that the last virtual console (ttyv8) is used to access the graphical environment if Xorg has been installed and configured as described in The X Window System.

For a detailed description of every column in this file and the available options for the virtual consoles, refer to ttys(5).

3.2.2. Single User Mode

The FreeBSD boot menu provides an option labelled as "Boot Single User". If this option is selected, the system will boot into a special mode known as "single user mode". This mode is typically used to repair a system that will not boot or to reset the root password when it is not known. While in single user mode, networking and other virtual consoles are not available. However, full root access to the system is available, and by default, the root password is not needed. For these reasons, physical access to the keyboard is needed to boot into this mode and determining who has physical access to the keyboard is something to consider when securing a FreeBSD system.

The settings which control single user mode are found in this section of /etc/ttys:

# 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.

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.

3.2.3. 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:

# kldload vesa

To determine which video modes are supported by the hardware, use vidcontrol(1). To get a list of supported video modes issue the following:

# 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 vidcontrol(1) as the root user:

# vidcontrol MODE_279

If the new video mode is acceptable, it can be permanently set on boot by adding it to /etc/rc.conf:


3.3. 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.

3.3.1. 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. System Accounts

System accounts are used to run services such as DNS, mail, and web servers. The reason for this is security; if all services ran as the superuser, they could act without restriction.

Examples of system accounts are daemon, operator, bind, news, and www.

nobody is the generic unprivileged system account. However, the more services that use nobody, the more files and processes that user will become associated with, and hence the more privileged that user becomes. 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 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.


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 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 pw(8). After the expiry time has elapsed, the account cannot be used to log in to the system, although the account’s directories and files will remain.

User’s full name

The user name uniquely identifies the account to FreeBSD, but does not necessarily reflect the user’s real name. Similar to a comment, this information can contain spaces, uppercase characters, and be more than 8 characters long.

Home directory

The home directory is the full path to a directory on the system. This is the user’s starting directory when the user logs in. A common convention is to put all user home directories under /home/username or /usr/home/username. Each user stores their personal files and subdirectories in their own home directory.

User shell

The shell provides the user’s default environment for interacting with the system. There are many different kinds of shells and experienced users will have their own preferences, which can be reflected in their account settings. 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 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.

Example 2. Install a Program As the Superuser
% configure
% make
% su -
# make install
# exit

The built-in su(1) framework works well for single systems or small networks with just one system administrator. An alternative is to install the security/sudo package or port. This software provides activity logging and allows the administrator to configure which users can run which commands as the superuser.

3.3.2. Managing Accounts

FreeBSD provides a variety of different commands to manage user accounts. The most common commands are summarized in Utilities for Managing User Accounts, followed by some examples of their usage. See the manual page for each utility for more details and usage examples.

Table 2. Utilities for Managing User Accounts




The recommended command-line application for adding new users.


The recommended command-line application for removing users.


A flexible tool for changing user database information.


The command-line tool to change user passwords.


A powerful and flexible tool for modifying all aspects of user accounts.


A system configuration utility with account management support. Adding a user

The recommended program for adding new users is adduser(8). When a new user is added, this program automatically updates /etc/passwd and /etc/group. It also creates a home directory for the new user, copies in the default configuration files from /usr/share/skel, and can optionally mail the new user a welcome message. This utility must be run as the superuser.

The adduser(8) utility is interactive and walks through the steps for creating a new user account. As seen in Adding a User on FreeBSD, either input the required information or press Return to accept the default value shown in square brackets. In this example, the user has been invited into the wheel group, allowing them to become the superuser with su(1). When finished, the utility will prompt to either create another user or to exit.

Example 3. Adding a User on FreeBSD
# adduser

The output should be similar to the following:

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

Since the password is not echoed when typed, be careful to not mistype the password when creating the user account. Removing a user

To completely remove a user from the system, run rmuser(8) as the superuser. This command performs the following steps:

  1. Removes the user’s crontab(1) entry, if one exists.

  2. Removes any at(1) jobs belonging to the user.

  3. Sends a SIGKILL signal to all processes owned by the user.

  4. Removes the user from the system’s local password file.

  5. Removes the user’s home directory (if it is owned by the user), including handling of symbolic links in the path to the actual home directory.

  6. Removes the incoming mail files belonging to the user from /var/mail.

  7. Removes all files owned by the user from /tmp, /var/tmp, and /var/tmp/vi.recover.

  8. Removes the username from all groups to which it belongs in /etc/group. (If a group becomes empty and the group name is the same as the username, the group is removed; this complements adduser(8)'s per-user unique groups.)

  9. Removes all message queues, shared memory segments and semaphores owned by the user.

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.

Example 4. rmuser Interactive Account Removal
# rmuser jru

The output should be similar to the following:

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. Change user information

Any user can use 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, chpass(1) displays an editor containing user information. When the user exits from the editor, the user database is updated with the new information.

This utility will prompt for the user’s password when exiting the editor, unless the utility is run as the superuser.

In Using chpass as Superuser, the superuser has typed chpass jru and is now viewing the fields that can be changed for this user. If jru runs this command instead, only the last six fields will be displayed and available for editing. This is shown in Using chpass as Regular User.

Example 5. Using chpass as Superuser
# chpass

The output should be similar to the following:

# Changing user database information for jru.
Login: jru
Password: *
Uid [#]: 1001
Gid [# or name]: 1001
Change [month day year]:
Expire [month day year]:
Home directory: /home/jru
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:
Example 6. Using chpass as Regular User
#Changing user database information for jru.
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:

The commands chfn(1) and chsh(1) are links to chpass(1), as are ypchpass(1), ypchfn(1), and ypchsh(1). Since NIS support is automatic, specifying the yp before the command is not necessary. How to configure NIS is covered in Network Servers. Change user password

Any user can easily change their password using 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:

Example 7. Changing Your Password
% passwd

The output should be similar to the following:

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 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.

Example 8. Changing Another User’s Password as the Superuser
# passwd jru

The output should be similar to the following:

Changing local password for jru.
New password:
Retype new password:
passwd: updating the database...
passwd: done

As with chpass(1), yppasswd(1) is a link to passwd(1), so NIS works with either command. Create, remove, modify and display system users and groups

The 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. 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.

3.3.3. Managing Groups

A group is a list of users. A group is identified by its group name and GID. In FreeBSD, the kernel uses the UID of a process, and the list of groups it belongs to, to determine what the process is allowed to do. Most of the time, the GID of a user or process usually means the first group in the list.

The group name to GID mapping is listed in /etc/group. This is a plain text file with four colon-delimited fields. The first field is the group name, the second is the encrypted password, the third the GID, and the fourth the comma-delimited list of members. For a more complete description of the syntax, refer to group(5).

The superuser can modify /etc/group using a text editor, although editing the group file using vigr(8) is preferred because it can catch some common mistakes. Alternatively, pw(8) can be used to add and edit groups. For example, to add a group called teamtwo and then confirm that it exists:

Care must be taken when using the operator group, as unintended superuser-like access privileges may be granted, including but not limited to shutdown, reboot, and access to all items in /dev in the group.

Example 9. Adding a Group Using pw(8)
# pw groupadd teamtwo
# pw groupshow teamtwo

The output should be similar to the following:


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.

Example 10. Adding User Accounts to a New Group Using pw(8)
# pw groupmod teamtwo -M jru
# pw groupshow teamtwo

The output should be similar to the following:


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 pw(8), but will show up when the information is queried via id(1) or a similar tool. When pw(8) is used to add a user to a group, it only manipulates /etc/group and does not attempt to read additional data from /etc/passwd.

Example 11. Adding a New Member to a Group Using pw(8)
# pw groupmod teamtwo -m db
# pw groupshow teamtwo

The output should be similar to the following:


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.

Example 12. Using id(1) to Determine Group Membership
% id jru

The output should be similar to the following:

uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo)

In this example, jru is a member of the groups jru and teamtwo.

For more information about this command and the format of /etc/group, refer to pw(8) and group(5).

3.4. 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® permissions used in FreeBSD. For finer-grained file system access control, refer to Access Control Lists.

In UNIX®, basic permissions are assigned using three types of access: read, write, and execute. These access types are used to determine file access to the file’s owner, group, and others (everyone else). The read, write, and execute permissions can be represented as the letters r, w, and x. They can also be represented as binary numbers as each permission is either on or off (0). When represented as a number, the order is always read as rwx, where r has an on value of 4, w has an on value of 2 and x has an on value of 1.

Table 4.1 summarizes the possible numeric and alphabetic possibilities. When reading the "Directory Listing" column, a - is used to represent a permission that is set to off.

Table 3. UNIX® Permissions
ValuePermissionDirectory Listing


No read, no write, no execute



No read, no write, execute



No read, write, no execute



No read, write, execute



Read, no write, no execute



Read, no write, execute



Read, write, no execute



Read, write, execute


Use the -l argument with ls(1) to view a long directory listing that includes a column of information about a file’s permissions for the owner, group, and everyone else. For example, ls -l in an arbitrary directory may show:

% ls -l

The output should be similar to the following:

total 530
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 myfile
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 otherfile
-rw-r--r--  1 root  wheel    7680 Sep  5 12:31 email.txt

Focusing on the line for myfile, the first (leftmost) character indicates whether this file is a regular file, a directory, a special character device, a socket, or any other special pseudo-file device. In this example, the - indicates a regular file. The next three characters, rw- in this example, give the permissions for the owner of the file. The next three characters, r--, give the permissions for the group that the file belongs to. The final three characters, r--, give the permissions for the rest of the world. A dash means that the permission is turned off. In this example, the permissions are set so the owner can read and write to the file, the group can read the file, and the rest of the world can only read the file. According to the table above, the permissions for this file would be 644, where each digit represents the three parts of the file’s permission.

How does the system control permissions on devices? FreeBSD treats most hardware devices as a file that programs can open, read, and write data to. These special device files are stored in /dev/.

Directories are also treated as files. They have read, write, and execute permissions. The executable bit for a directory has a slightly different meaning than that of files. When a directory is marked executable, it means it is possible to change into that directory using 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 chmod(1).

3.4.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:







Group owner






All ("world")



Adding permissions



Removing permissions



Explicitly set permissions












Sticky bit



Set UID or GID

These values are used with chmod(1), but with letters instead of numbers. For example, the following command would block both members of the group associated with FILE and all other users from accessing FILE:

% 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:

% chmod go-w,a+x FILE

3.4.2. 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 chflags(1). For example, to enable the system undeletable flag on the file file1, issue the following command:

# chflags sunlink file1

To disable the system undeletable flag, put a "no" in front of the sunlink:

# chflags nosunlink file1

To view the flags of a file, use -lo with ls(1):

# ls -lo file1
-rw-r--r--  1 trhodes  trhodes  sunlnk 0 Mar  1 05:54 file1

Several file flags may only be added or removed by the root user. In other cases, the file owner may set its file flags. Refer to chflags(1) and chflags(2) for more information.

3.4.3. 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® 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, passwd(1) runs with the real user ID when a user changes their password. However, in order to update the password database, the command runs as the effective ID of the root user. This allows users to change their passwords without seeing a Permission Denied error.

The setuid permission may be added symbolically by adding the s permission for the user as in the following example:

# chmod u+s

The setuid permission may also be set by prefixing a permission set with the number four (4) as shown in the following example:

# chmod 4755

The permissions on now look like the following:

-rwsr-xr-x   1 trhodes  trhodes    63 Aug 29 06:36

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 passwd(1).

The nosuid 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 passwd(1):

In terminal A:

Changing local password for trhodes
Old Password:

In terminal B:

# ps aux | grep passwd
trhodes  5232  0.0  0.2  3420  1608   0  R+    2:10AM   0:00.00 grep passwd
root     5211  0.0  0.2  3620  1724   2  I+    2:09AM   0:00.01 passwd

Although passwd(1) is run as a normal user, it is using the effective UID of root.

The setgid permission performs the same function as the setuid permission; except that it alters the group settings. When an application or utility executes with this setting, it will be granted the permissions based on the group that owns the file, not the user who started the process.

To set the setgid permission on a file symbolically, add the s permission for the group with chmod(1):

# chmod g+s

Alternatively, provide chmod(1) with a leading two (2):

# chmod 2755

In the following listing, notice that the s is now in the field designated for the group permission settings:

-rwxr-sr-x   1 trhodes  trhodes    44 Aug 31 01:49

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 setuid(2) system calls.

The setuid and setgid permission bits may lower system security, by allowing for elevated permissions. The third special permission, the sticky bit, can strengthen the security of a system.

When the sticky bit is set on a directory, it allows file deletion only by the file owner. This is useful to prevent file deletion in public directories, such as /tmp, by users who do not own the file. To utilize this permission, add the t mode to the file:

# chmod +t /tmp

Alternatively, prefix the permission set with a one (1):

# chmod 1777 /tmp

The sticky bit permission will display as a t at the very end of the permission set:

# ls -al / | grep tmp
drwxrwxrwt  10 root  wheel         512 Aug 31 01:49 tmp

3.5. 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 Disk Organization. Standard mount points include /usr/, /var/, /tmp/, /mnt/, and /cdrom/. These directories are usually referenced to entries in /etc/fstab. This file is a table of various file systems and mount points and is read by the system. Most of the file systems in /etc/fstab are mounted automatically at boot time from the script rc(8) unless their entry includes noauto. Details can be found in The fstab File.

A complete description of the file system hierarchy is available in hier(7). The following table provides a brief overview of the most common directories.




Root directory of the file system.


User utilities fundamental to both single-user and multi-user environments.


Programs and configuration files used during operating system bootstrap.


Default boot configuration files. Refer to loader.conf(5) for details.


Device special files managed by devfs(5)


System configuration files and scripts.


Default system configuration files. Refer to rc(8) for details.


Scripts that run daily, weekly, and monthly, via cron(8). Refer to periodic(8) for details.


Critical system libraries needed for binaries in /bin and /sbin


Critical system files


Contains subdirectories to be used as mount points for removable media such as CDs, USB drives, and floppy disks


Empty directory commonly used by system administrators as a temporary mount point.


Automounted NFS shares; see auto_master(5)


Process file system. Refer to procfs(5), mount_procfs(8) for details.


Statically linked programs for emergency recovery as described in rescue(8).


Home directory for the root account.


System programs and administration utilities fundamental to both single-user and multi-user environments.


Temporary files which are usually not preserved across a system reboot. A memory-based file system is often mounted at /tmp. This can be automated using the tmpmfs-related variables of rc.conf(5) or with an entry in /etc/fstab; refer to mdmfs(8) for details.


The majority of user utilities and applications.


Common utilities, programming tools, and applications.


Standard C include files.


Archive libraries.


Miscellaneous utility data files.


System daemons and system utilities executed by other programs.


Local executables and libraries. Also used as the default destination for the FreeBSD ports framework. Within /usr/local, the general layout sketched out by hier(7) for /usr should be used. Exceptions are the man directory, which is directly under /usr/local rather than under /usr/local/share, and the ports documentation is in share/doc/port.


The FreeBSD Ports Collection (optional).


System daemons and system utilities executed by users.


Architecture-independent files.


BSD and/or local source files.


Multi-purpose log, temporary, transient, and spool files.


Miscellaneous system log files.


Temporary files which are usually preserved across a system reboot.

3.6. Disk Organization

The smallest unit of organization that FreeBSD uses to find files is the filename. Filenames are case-sensitive, which means that readme.txt and README.TXT are two separate files. FreeBSD does not use the extension of a file to determine whether the file is a program, document, or some other form of data.

Files are stored in directories. A directory may contain no files, or it may contain many hundreds of files. A directory can also contain other directories, allowing a hierarchy of directories within one another in order to organize data.

Files and directories are referenced by giving the file or directory name, followed by a forward slash, /, followed by any other directory names that are necessary. For example, if the directory foo contains a directory bar which contains the file readme.txt, the full name, or path, to the file is foo/bar/readme.txt. Note that this is different from Windows® which uses \ to separate file and directory names. FreeBSD does not use drive letters, or other drive names in the path. For example, one would not type c:\foo\bar\readme.txt on FreeBSD.

3.6.1. File systems

Directories and files are stored in a file system. Each file system contains exactly one directory at the very top level, called the root directory for that file system. This root directory can contain other directories. One file system is designated the root file system or /. Every other file system is mounted under the root file system. No matter how many disks are on the FreeBSD system, every directory appears to be part of the same disk.

Consider three file systems, called A, B, and C. Each file system has one root directory, which contains two other directories, called A1, A2 (and likewise B1, B2 and C1, C2).

Call A the root file system. If 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:

Directory tree with the root directory and two subdirectories

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:

Directory tree with the root directory and two subdirectories

Any files that are in the B1 or B2 directories can be reached with the path /A1/B1 or /A1/B2 as necessary. Any files that were in /A1 have been temporarily hidden. They will reappear if B is unmounted from A.

If B had been mounted on A2 then the diagram would look like this:

Directory tree with the root directory and two subdirectories

and the paths would be /A2/B1 and /A2/B2 respectively.

File systems can be mounted on top of one another. Continuing the last example, the C file system could be mounted on top of the B1 directory in the B file system, leading to this arrangement:

A complex directory tree. With different subdirectories hanging from root.

Or C could be mounted directly on to the A file system, under the A1 directory:

A complex directory tree. With different subdirectories hanging from root.

It is entirely possible to have one large root file system, and not need to create any others. There are some drawbacks to this approach, and one advantage.

Benefits of Multiple File Systems
  • Different file systems can have different mount options. For example, the root file system can be mounted read-only, making it impossible for users to inadvertently delete or edit a critical file. Separating user-writable file systems, such as /home, from other file systems allows them to be mounted nosuid. This option prevents the suid/guid bits on executables stored on the file system from taking effect, possibly improving security.

  • FreeBSD automatically optimizes the layout of files on a file system, depending on how the file system is being used. So a file system that contains many small files that are written frequently will have a different optimization to one that contains fewer, larger files. By having one big file system this optimization breaks down.

  • FreeBSD’s file systems are robust if power is lost. However, a power loss at a critical point could still damage the structure of the file system. By splitting data over multiple file systems it is more likely that the system will still come up, making it easier to restore from backup as necessary.

Benefit of a Single File System
  • File systems are a fixed size. If you create a file system when you install FreeBSD and give it a specific size, you may later discover that you need to make the partition bigger. This is not easily accomplished without backing up, recreating the file system with the new size, and then restoring the backed up data.

    FreeBSD features the growfs(8) command, which makes it possible to increase the size of file system on the fly, removing this limitation. A file system can only be expanded into free space in the partition in which it resides. If there is space after the partition, the partition can be expanded with gpart(8). If the partition is the last one on a virtual disk, and the disk is expanded, the partition can then be expanded.

3.6.2. Disk partitions

File systems are contained in partitions. Disks are divided into partitions using one of several partitioning schemes; see Manual Partitioning. The newer scheme is GPT; older BIOS-based computers use MBR. GPT supports division of a disk into partitions with a size, offset, and type. It supports a large number of partitions and partition types, and is recommended whenever its use is possible. GPT partitions use the disk name with a suffix, where the suffix is p1 for the first partition, p2 for the second, and so on. MBR, however, supports only a small number of partitions. The MBR partitions are known in FreeBSD as slices. Slices may be used for different operating systems. FreeBSD slices are subdivided into partitions using BSD labels (see bsdlabel(8)).

Slice numbers follow the device name, prefixed with an s, starting at 1. So "da0s1" is the first slice on the first SCSI drive. There can only be four physical slices on a disk, but there can be logical slices inside physical slices of the appropriate type. These extended slices are numbered starting at 5, so "ada0s5" is the first extended slice on the first SATA disk. These devices are used by file systems that expect to occupy a slice.

Each GPT or BSD partition can contain only one file system, which means that file systems are often described by either their typical mount point in the file system hierarchy, or the name of the partition they are contained in.

FreeBSD also uses disk space for swap space to provide virtual memory. This allows your computer to behave as though it has much more memory than it actually does. When FreeBSD runs out of memory, it moves some of the data that is not currently being used to the swap space, and moves it back in (moving something else out) when it needs it. This is called paging.

Some BSD partitions have certain conventions associated with them.




Normally contains the root file system.


Normally contains swap space.


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.


Partition d used to have a special meaning associated with it, although that is now gone and d may work as any normal partition.

Slices and "dangerously dedicated" physical drives contain BSD partitions, which are represented as letters from a to h. This letter is appended to the device name, so "da0a" is the a partition on the first da drive, which is "dangerously dedicated". "ada1s3e" is the fifth partition in the third slice of the second SATA disk drive.

Finally, each disk on the system is identified. A disk name starts with a code that indicates the type of disk, and then a number, indicating which disk it is. Unlike partitions and slices, disk numbering starts at 0. Common codes are listed in Disk Device Names.

When referring to a partition in a slice, include the disk name, s, the slice number, and then the partition letter. Examples are shown in Sample Disk, Slice, and Partition Names. GPT partitions include the disk name, p, and then the partition number.

Conceptual Model of a Disk shows a conceptual model of a disk layout using MBR slices.

When installing FreeBSD, configure the disk slices if using MBR, and create partitions within the slice to be used for FreeBSD. If using GPT, configure partitions for each file system. In either case, create a file system or swap space in each partition, and decide where each file system will be mounted. See gpart(8) for information on manipulating partitions.

Table 4. Disk Device Names
Drive TypeDrive Device Name

SATA and IDE hard drives


SCSI hard drives and USB storage devices


NVMe storage

nvd or nda

SATA and IDE CD-ROM drives


SCSI CD-ROM drives


Floppy drives


SCSI tape drives


RAID drives

Examples include aacd for Adaptec® AdvancedRAID, mlxd and mlyd for Mylex®, amrd for AMI MegaRAID®, idad for Compaq Smart RAID, twed for 3ware® RAID.

Table 5. Sample Disk, Slice, and Partition Names


The first partition (a) on the first slice (s1) on the first SATA disk (ada0).


The fifth partition (e) on the second slice (s2) on the second SCSI disk (da1).

Example 13. Conceptual Model of a Disk

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® partitions). The first slice contains a Windows® NTFS file system, C:, and the second slice contains a FreeBSD installation. This example FreeBSD installation has four data partitions and a swap partition.

The four partitions each hold a file system. Partition a is used for the root file system, d for /var/, e for /tmp/, and f for /usr/. Partition letter c refers to the entire slice, and so is not used for ordinary partitions.

Layout of a shared drive between Windows and FreeBSD

3.7. Mounting and Unmounting File Systems

The file system is best visualized as a tree, rooted, as it were, at /. /dev, /usr, and the other directories in the root directory are branches, which may have their own branches, such as /usr/local, and so on.

There are various reasons to house some of these directories on separate file systems. /var contains the directories log/, spool/, and various types of temporary files, and as such, may get filled up. Filling up the root file system is not a good idea, so splitting /var from / is often favorable.

Another common reason to contain certain directory trees on other file systems is if they are to be housed on separate physical disks, or are separate virtual disks, such as Network File System mounts, described in “Network File System (NFS)”, or CDROM drives.

3.7.1. The fstab File

During the boot process (The FreeBSD Booting Process), file systems listed in /etc/fstab are automatically mounted except for the entries containing noauto. This file contains entries in the following format:

device       /mount-point fstype     options      dumpfreq     passno

An existing device name as explained in Disk Device Names.


An existing directory on which to mount the file system.


The file system type to pass to mount(8). The default FreeBSD file system is ufs.


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 mount(8).


Used by dump(8) to determine which file systems require dumping. If the field is missing, a value of zero is assumed.


Determines the order in which UFS file systems should be checked by fsck(8) after a reboot. File systems that should be skipped should have their passno set to zero. The root file system needs to be checked before everything else and should have its passno set to one. The other file systems should be set to values greater than one. If more than one file system has the same passno, fsck(8) will attempt to check file systems in parallel if possible.

Refer to fstab(5) for more information on the format of /etc/fstab and its options.

3.7.2. Using mount(8)

File systems are mounted using mount(8). The most basic syntax is as follows:

# mount device mountpoint

A file system listed in /etc/fstab can also be mounted by providing just the mountpoint.

This command provides many options which are described in mount(8). The most commonly used options include:

Mount Options

Mount all the file systems listed in /etc/fstab, except those marked as "noauto", excluded by the -t flag, or those that are already mounted.


Do everything except for the actual mount system call. This option is useful in conjunction with the -v flag to determine what mount(8) is actually trying to do.


Force the mount of an unclean file system (dangerous), or the revocation of write access when downgrading a file system’s mount status from read-write to read-only.


Mount the file system read-only. This is identical to using -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.


Update mount options on the file system.


Be verbose.


Mount the file system read-write.

The following options can be passed to -o as a comma-separated list:


Do not interpret setuid or setgid flags on the file system. This is also a useful security option.

3.7.3. Using umount(8)

To unmount a file system use 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.

3.8. 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 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.

3.8.1. Viewing Processes

To see the processes running on the system, use ps(1) or 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 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 top(1).

By default, ps(1) only shows the commands that are running and owned by the user. For example:

% ps

The output should be similar to the following:

8203  0  Ss   0:00.59 /bin/csh
8895  0  R+   0:00.00 ps

The output from 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 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 top(1) is similar:

% top

The output should be similar to the following:

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

  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 ps(1), such as the PID, username, amount of CPU time, and the command that started the process. By default, 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.

top(1) automatically updates the display every two seconds. A different interval can be specified with -s.

3.8.2. Killing Processes

One way to communicate with any running process or daemon is to send a signal using 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 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. [1].

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.

Killing a random process on the system is a bad idea. In particular, 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 kill(1) before pressing Return.

3.9. 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 (sh(1)) and the extended C shell (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 tcsh(1). A Linux® user might prefer bash. Each shell has unique properties that may or may not work with a user’s preferred working environment, which is why there is a choice of which shell to use.

One common shell feature is filename completion. After a user types the first few letters of a command or filename and presses Tab, the shell completes the rest of the command or filename. Consider two files called foobar and football. To delete foobar, the user might type rm foo and press Tab to complete the filename.

But the shell only shows rm foo. It was unable to complete the filename because both foobar and football start with foo. Some shells sound a beep or show all the choices if more than one name matches. The user must then type more characters to identify the desired filename. Typing a t and pressing Tab again is enough to let the shell determine which filename is desired and fill in the rest.

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. Common Environment Variables provides a list of common environment variables and their meanings. Note that the names of environment variables are always in uppercase.

Table 6. Common Environment Variables




Current logged in user’s name.


Colon-separated list of directories to search for binaries.


Network name of the Xorg display to connect to, if available.


The current shell.


The name of the user’s type of terminal. Used to determine the capabilities of the terminal.


Database entry of the terminal escape codes to perform various terminal functions.


Type of operating system.


The system’s CPU architecture.


The user’s preferred text editor.


The user’s preferred utility for viewing text one page at a time.


Colon-separated list of directories to search for manual pages.

How to set an environment variable differs between shells. In tcsh(1) and csh(1), use setenv to set environment variables. In sh(1) and bash, use export to set the current environment variables. This example sets the default EDITOR to /usr/local/bin/emacs for the tcsh(1) shell:

% setenv EDITOR /usr/local/bin/emacs

The equivalent command for bash would be:

% 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.

3.9.1. 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 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:

% chsh -s /usr/local/bin/bash

Enter your password at the prompt and press Return to change your shell. Log off and log in again to start using the new shell.

The new shell must be present in /etc/shells. If the shell was installed from the FreeBSD Ports Collection as described in 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:

# echo /usr/local/bin/bash >> /etc/shells

Then, rerun chsh(1).

3.9.2. Advanced Shell Techniques

The UNIX® shell is not just a command interpreter, it acts as a powerful tool which allows users to execute commands, redirect their output, redirect their input and chain commands together to improve the final command output. When this functionality is mixed with built in commands, the user is provided with an environment that can maximize efficiency.

Shell redirection is the action of sending the output or the input of a command into another command or into a file. To capture the output of the ls(1) command, for example, into a file, redirect the output:

% ls > directory_listing.txt

The directory contents will now be listed in directory_listing.txt. Some commands can be used to read input, such as sort(1). To sort this listing, redirect the input:

% 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 sort(1) by mixing the direction:

% sort < directory_listing.txt > sorted.txt

In all of the previous examples, the commands are performing redirection using file descriptors. Every UNIX® system has file descriptors, 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® 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:

% cat directory_listing.txt | sort | less

In that example, the contents of directory_listing.txt will be sorted and the output passed to less(1). This allows the user to scroll through the output at their own pace and prevent it from scrolling off the screen.

3.10. 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 ee(1), which stands for easy editor. To start this editor, type ee filename where filename is the name of the file to be edited. Once inside the editor, all of the commands for manipulating the editor’s functions are listed at the top of the display. The caret (^) represents Ctrl, so ^e expands to Ctrl+e. To leave ee(1), press Esc, then choose the "leave editor" option from the main menu. The editor will prompt to save any changes if the file has been modified.

FreeBSD also comes with more powerful text editors, such as vi(1), as part of the base system. Other editors, like editors/emacs and 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 Shells.

3.11. Devices and Device Nodes

A device is a term used mostly for hardware-related activities in a system, including disks, printers, graphics cards, and keyboards. When FreeBSD boots, the majority of the boot messages refer to devices being detected. A copy of the boot messages is saved to /var/run/dmesg.boot.

Each device has a device name and number. For example, ada0 is the first SATA hard drive, while kbd0 represents the keyboard.

Most devices in FreeBSD must be accessed through special files called device nodes, which are located in /dev.

3.12. 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:

% man command

where command is the name of the command to learn about. For example, to learn more about ls(1), type:

% man ls

Manual pages are divided into sections which represent the type of topic. In FreeBSD, the following sections are available:

  1. User commands.

  2. System calls and error numbers.

  3. Functions in the C libraries.

  4. Device drivers.

  5. File formats.

  6. Games and other diversions.

  7. Miscellaneous information.

  8. System maintenance and operation commands.

  9. 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(1) which section to display, specify the section number:

% man 1 chmod

This will display the manual page for the user command chmod(1). References to a particular section of the online manual are traditionally placed in parenthesis in written documentation, so chmod(1) refers to the user command and 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:

% man -k mail

This command displays a list of commands that have the keyword "mail" in their descriptions. This is equivalent to using apropos(1).

To read the descriptions for all of the commands in /usr/sbin, type:

% cd /usr/sbin
% man -f * | more


% cd /usr/sbin
% whatis * |more

3.12.1. 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 info(1) or, if editors/emacs is installed, the info mode of emacs.

To use info(1), type:

% info

For a brief introduction, type h. For a quick command reference, type ?.

Chapter 4. Installing Applications: Packages and Ports

4.1. 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.

4.2. Overview of Software Installation

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 36000 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 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 Firefox, KDE Plasma, 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, NGINX® 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, NGINX® is available as a nginx package and a nginx-lite 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 mailing list and the FreeBSD ports bugs mailing list.

Before installing an application, check for related security issues.

To audit installed packages against known vulnerabilities, run pkg audit -F.

The remainder of this chapter explains how to use packages and ports to install and manage third-party software on FreeBSD.

4.3. 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 Ports Portal. The ports can be searched by application name or by software category.

  • Dan Langille maintains FreshPorts 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 SourceForge or GitHub then check back at the Ports Portal to see if the application has been ported.

  • Search the binary package repository for an application using the pkg(8) command

4.4. Using pkg for Binary Package Management

pkg(8) provides an interface for manipulating packages: registering, adding, removing and upgrading packages.

For sites wishing to only use prebuilt binary packages from the FreeBSD mirrors, managing packages with pkg(8) can be sufficient.

However, for those sites building from source a separate port management tool will be needed.

Since pkg(8) 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(8) installs only binary packages.

4.4.1. Getting Started with pkg

All supported versions of FreeBSD now contain /usr/sbin/pkg a.k.a pkg(7). This is a small placeholder that has just the minimum functionality required to install the real pkg(8).

An Internet working connection is required for the bootstrap process to succeed.

Run pkg(8) command line:

# pkg

The output should be similar to the following:

The package management tool is not yet installed on your system.
Do you want to fetch and install it now? [y/N]

pkg(7) will intercept the command, and if you confirm that is your intention, download the pkg(8) tarball, install pkg(8) from it, bootstrap the local package database and then proceed to run the command you originally requested.

More recent versions of pkg(7) understand pkg -N as a test to see if pkg(8) is installed without triggering the installation, and conversely, pkg bootstrap[-f] to install pkg(8) (or force it to be reinstalled) without performing any other actions.

Usage information for pkg is available in the pkg(8) manual page or by running pkg without additional arguments. Additional pkg configuration options are described in pkg.conf(5).

Each pkg command argument is documented in a command-specific manual page.

To read the manual page for pkg install, for example, run this command:

# pkg help install

The rest of this section demonstrates common binary package management tasks which can be performed using pkg(8). Each demonstrated command provides many switches to customize its use. Refer to a command’s help or man page for details and more examples.

4.4.2. 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 2023, is named 2023Q1. And the Latest branch provides the latest versions of the packages to the users.

To switch pkg(8) from Quarterly to Latest run the following commands:

# mkdir -p /usr/local/etc/pkg/repos
# echo 'FreeBSD: { url: "pkg+${ABI}/latest" }' > /usr/local/etc/pkg/repos/FreeBSD.conf

Then run this command to update the local package repositories catalogues for the Latest branch:

# pkg update -f

4.4.3. Configure pkg

pkg.conf(5) is the system-wide configuration file used by the pkg(8) tools. The default location of this file is /usr/local/etc/pkg.conf.

FreeBSD does not need to have a pkg.conf file. Many installations will work well with no pkg.conf at all or with an empty pkg.conf (other than comment lines).

Lines in the file beginning with a "#" are comments and are ignored.

The file is in UCL format. For more information on the syntax of libucl(3), please visit the official UCL website.

The following types of options are recognized - boolean, string and list options.

A boolean option is marked as enabled if one of the following values is specified in the configuration file - YES, TRUE and ON.

To search a package pkg-search(8) can be used:

# pkg search nginx

The output should be similar to the following:

modsecurity3-nginx-1.0.3       Instruction detection and prevention engine / nginx Wrapper
nginx-1.22.1_2,3               Robust and small WWW server
nginx-devel-1.23.2_4           Robust and small WWW server
nginx-full-1.22.1_1,3          Robust and small WWW server (full package)
nginx-lite-1.22.1,3            Robust and small WWW server (lite package)
nginx-naxsi-1.22.1,3           Robust and small WWW server (plus NAXSI)
nginx-prometheus-exporter-0.10.0_7 Prometheus exporter for NGINX and NGINX Plus stats
nginx-ultimate-bad-bot-blocker-4.2020.03.2005_1 Nginx bad bot and other things blocker
nginx-vts-exporter-0.10.7_7    Server that scraps NGINX vts stats and export them via HTTP
p5-Nginx-ReadBody-0.07_1       Nginx embeded perl module to read and evaluate a request body
p5-Nginx-Simple-0.07_1         Perl 5 module for easy to use interface for Nginx Perl Module
p5-Test-Nginx-0.30             Testing modules for Nginx C module development
py39-certbot-nginx-2.0.0       NGINX plugin for Certbot
rubygem-passenger-nginx-6.0.15 Modules for running Ruby on Rails and Rack applications

4.4.5. Installing and Fetching Packages

To install a binary package pkg-install(8) can be used. 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:

# pkg install curl

The output should be similar to the following:

Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
The following 9 package(s) will be affected (of 0 checked):

New packages to be INSTALLED:
        ca_root_nss: 3.83
        curl: 7.86.0
        gettext-runtime: 0.21
        indexinfo: 0.3.1
        libidn2: 2.3.3
        libnghttp2: 1.48.0
        libpsl: 0.21.1_4
        libunistring: 1.0

Number of packages to be installed: 9

The process will require 11 MiB more space.
3 MiB to be downloaded

Proceed with this action? [y/N]

The new package and any additional packages that were installed as dependencies can be seen in the installed packages list:

# pkg info

The output should be similar to the following:

ca_root_nss-3.83               Root certificate bundle from the Mozilla Project
curl-7.86.0                    Command line tool and library for transferring data with URLs
gettext-runtime-0.21.1         GNU gettext runtime libraries and programs
indexinfo-0.3.1                Utility to regenerate the GNU info page index
libidn2-2.3.3                  Implementation of IDNA2008 internationalized domain names
libnghttp2-1.48.0              HTTP/2.0 C Library
libpsl-0.21.1_6                C library to handle the Public Suffix List
libssh2-               Library implementing the SSH2 protocol
libunistring-1.0               Unicode string library
pkg-1.18.4                     Package manager

To fetch a package and install it later or in another place use pkg-fetch(8). For example, to download nginx-lite:

# pkg fetch -d -o /usr/home/user/packages/ nginx-lite
  • -d: used to fetch all the dependencies

  • -o: used to specify the download directory

The output should be similar to the following:

Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
The following packages will be fetched:

New packages to be FETCHED:
        nginx-lite: 1.22.1,3 (342 KiB: 22.20% of the 2 MiB to download)
        pcre: 8.45_3 (1 MiB: 77.80% of the 2 MiB to download)

Number of packages to be fetched: 2

The process will require 2 MiB more space.
2 MiB to be downloaded.

Proceed with fetching packages? [y/N]:

To install the downloaded packages pkg-install(8) can be used as follows:

# cd /usr/home/user/packages/
# pkg install nginx-lite-1.22.1,3.pkg

4.4.6. Obtaining Information About Installed Packages

Information about the packages installed on a system can be viewed by running pkg-info(8) 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:

# pkg info pkg

The output should be similar to the following:

Name           : pkg
Version        : 1.19.0
Installed on   : Sat Dec 17 11:05:28 2022 CET
Origin         : ports-mgmt/pkg
Architecture   : FreeBSD:13:amd64
Prefix         : /usr/local
Categories     : ports-mgmt
Licenses       : BSD2CLAUSE
Maintainer     :
WWW            :
Comment        : Package manager
Options        :
        DOCS           : on
Shared Libs provided:
Annotations    :
        FreeBSD_version: 1301000
        repo_type      : binary
        repository     : FreeBSD
Flat size      : 33.2MiB
Description    :
Package management tool


4.4.7. Upgrading Installed Packages

Installed packages can be upgraded to their latest versions using pkg-upgrade(8):

# pkg upgrade

This command will compare the installed versions with those available in the repository catalogue and upgrade them from the repository.

4.4.8. 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, use pkg-audit(8):

# pkg audit -F

The output should be similar to the following:

Fetching vuln.xml.xz: 100%  976 KiB 499.5kB/s    00:02
chromium-108.0.5359.98 is vulnerable:
  chromium -- multiple vulnerabilities
  CVE: CVE-2022-4440
  CVE: CVE-2022-4439
  CVE: CVE-2022-4438
  CVE: CVE-2022-4437
  CVE: CVE-2022-4436

4.4.9. Removing Packages

Packages that are no longer needed can be removed with pkg-delete(8).

For example:

# pkg delete curl

The output should be similar to the following:

Checking integrity... done (0 conflicting)
Deinstallation has been requested for the following 1 packages (of 0 packages in the universe):

Installed packages to be REMOVED:
        curl :7.86.0

Number of packages to be removed: 1

The operation will free 4 MiB.

Proceed with deinstallation packages? [y/N]: y
[1/1] Deinstalling curl-7.86.0...
[1/1] Deleting files for curl-7.86.0: 100%

4.4.10. 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 pkg-autoremove(8):

# pkg autoremove

The output should be similar to the following:

Checking integrity... done (0 conflicting)
Deinstallation has been requested for the following 1 packages:

Installed packages to be REMOVED:

Number of packages to be removed: 1

The operation will free 723 KiB.

Proceed with deinstalling packages? [y/N]:

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:

# pkg prime-list

The output should be similar to the following:


pkg prime-list is an alias command declared in /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:

# pkg prime-origins

The output should be similar to the following:


This list can be used to rebuild all packages installed on a system using build tools such as ports-mgmt/poudriere or ports-mgmt/synth.

Marking an installed package as automatic can be done using:

# 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:

# pkg set -A 0 devel/cmake

4.4.11. Removing Stale Packages

By default, pkg stores binary packages in a cache directory defined by PKG_CACHEDIR in 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:

# pkg clean

The entire cache may be cleared by running:

# pkg clean -a

4.4.12. Locking and Unlocking Packages

pkg-lock(8) is used to lock packages against reinstallation, modification or deletion. pkg-unlock(8) unlocks the named packages. Either variant only has an effect on currently installed packages. Consequently it is impossible to block installation of a new package by using this mechanism, unless such an installation implies updating a locked package.

For example, to lock nginx-lite:

# pkg lock nginx-lite

And to unlock nginx-lite:

# pkg unlock nginx-lite

4.4.13. 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 lang/python3 is renamed to lang/python311 so that lang/python3 can now represent version 3.11.

To change the package origin for the above example, run:

# pkg set -o lang/python3:lang/python311

As another example, to update lang/ruby31 to lang/ruby32, run:

# pkg set -o lang/ruby31:lang/ruby32

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:

# pkg install -Rf lang/ruby32

4.5. Using the Ports Collection

The Ports Collection is a set of 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 /usr/ports.

Before installing and using the Ports Collection, please be aware that it is generally ill-advised to use the Ports Collection in conjunction with the binary packages provided via pkg to install software. pkg, by default, tracks quarterly branch-releases of the ports tree and not HEAD. Dependencies could be different for a port in HEAD compared to its counterpart in a quarterly branch release and this could result in conflicts between dependencies installed by pkg and those from the Ports Collection. If the Ports Collection and pkg must be used in conjunction, then be sure that your Ports Collection and pkg are on the same branch release of the ports tree.

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:

  • Makefile: contains statements that specify how the application should be compiled and where its components should be installed.

  • distinfo: contains the names and checksums of the files that must be downloaded to build the port.

  • 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.

  • pkg-descr: provides a more detailed description of the program.

  • 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 pkg-message or other files to handle special situations. For more details on these files, and on ports in general, refer to the FreeBSD Porter’s Handbook.

The port does not include the actual source code, also known as a distfile. The extract portion of building a port will automatically save the downloaded source to /usr/ports/distfiles.

4.5.1. Installing the Ports Collection

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:

Procedure: Git Method

If more control over the ports tree is needed or if local changes need to be maintained, or if running FreeBSD-CURRENT, Git can be used to obtain the Ports Collection. Refer to the Git Primer for a detailed description of Git.

  1. Git 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 Git like this:

    # cd /usr/ports/devel/git
    # make install clean

    If the ports tree is not available, or pkg is being used to manage packages, Git can be installed as a package:

    # pkg install git
  2. Check out a copy of the HEAD branch of the ports tree:

    # git clone /usr/ports
  3. Or, check out a copy of a quarterly branch:

    # git clone -b 2023Q1 /usr/ports
  4. As needed, update /usr/ports after the initial Git checkout:

    # git -C /usr/ports pull
  5. As needed, switch /usr/ports to a different quarterly branch:

    # git -C /usr/ports switch 2023Q1

4.5.2. 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 ports(7).

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 for known security issues related to the port. Alternatively, 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 pkg-audit(8) and 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:

# 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
===>  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
      This port has installed the following binaries which execute with
      increased privileges.

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:

# make clean
===>  Cleaning for lsof-88.d,8

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 www/firefox and security/gpgme. 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.

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 ports(7).

The ports system uses 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 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 /usr/ports, to fetch all distfiles, or within a category, such as /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 Makefile. When using, specify the alternate location:

# cd /usr/ports/directory
# make MASTER_SITE_OVERRIDE= \ fetch

The WRKDIRPREFIX and PREFIX variables can override the default working and target directories. For example:

# make WRKDIRPREFIX=/usr/home/example/ports install

will compile the port in /usr/home/example/ports and install everything under /usr/local.

# make PREFIX=/usr/home/example/local install

will compile the port in /usr/ports and install it in /usr/home/example/local. And:

# 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.

4.5.3. Removing Installed Ports

Installed ports can be uninstalled using pkg delete. Examples for using this command can be found in the pkg-delete(8) manual page.

Alternately, make deinstall can be run in the port's directory:

# cd /usr/ports/sysutils/lsof
# make deinstall
===>  Deinstalling for sysutils/lsof
===>   Deinstalling
Deinstallation has been requested for the following 1 packages:


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.

4.5.4. 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 "Git Method". The following command will list the installed ports which are out of date:

# pkg version -l "<"

Before attempting an upgrade, read /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. 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.

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. Upgrading Ports Using Portmaster

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:

# 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:

# 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:

# portmaster -a

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 portmaster(8) for details regarding their usage.

If errors are encountered during the upgrade process, add -f to upgrade and rebuild all ports:

# 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:

# portmaster shells/bash

More information about ports-mgmt/portmaster may be found in its pkg-descr. Upgrading Ports Using Portupgrade

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:

# 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:

# 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:

# 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:

# 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 ports-mgmt/portupgrade may be found in its pkg-descr.

4.5.5. 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 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 work directories found within the local copy of the Ports Collection:

# portsclean -C

In addition, outdated source distribution files accumulate in /usr/ports/distfiles over time. To use Portupgrade to delete all the distfiles that are no longer referenced by any ports:

# portsclean -D

Portupgrade can remove all distfiles not referenced by any port currently installed on the system:

# portsclean -DD

If Portmaster is installed, use:

# 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, ports-mgmt/pkg_cutleaves automates the task of removing installed ports that are no longer needed.

4.6. 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 pkg(8) and other package management tools.

poudriere is installed using the ports-mgmt/poudriere package or port. The installation includes a sample configuration file /usr/local/etc/poudriere.conf.sample. Copy this file to /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 /usr/local/etc/poudriere.conf and FREEBSD_HOST should be set to a nearby mirror. Defining CCACHE_DIR enables the use of 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 /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.

4.6.1. 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.

# poudriere jail -c -j 13amd64 -v 13.1-RELEASE
[00:00:00] Creating 13amd64 fs at /poudriere/jails/13amd64... done
[00:00:00] Using pre-distributed MANIFEST for FreeBSD 13.1-RELEASE amd64
[00:00:00] Fetching base for FreeBSD 13.1-RELEASE amd64
/poudriere/jails/13amd64/fromftp/base.txz              125 MB 4110 kBps    31s
[00:00:33] Extracting base... done
[00:00:54] Fetching src for FreeBSD 13.1-RELEASE amd64
/poudriere/jails/13amd64/fromftp/src.txz               154 MB 4178 kBps    38s
[00:01:33] Extracting src... done
[00:02:31] Fetching lib32 for FreeBSD 13.1-RELEASE amd64
/poudriere/jails/13amd64/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/13amd64/etc/resolv.conf
Looking up mirrors... 3 mirrors found.
Fetching public key from done.
Fetching metadata signature for 13.1-RELEASE from 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
The following files will be updated as part of updating to
Installing updates...Scanning //usr/share/certs/blacklisted for certificates...
Scanning //usr/share/certs/trusted for certificates...
[00:04:06] Recording filesystem state for clean... done
[00:04:07] Jail 13amd64 13.1-RELEASE-p1 amd64 is ready to be used
# poudriere ports -c -p local -m git+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 poudriere(8) for details after ports-mgmt/poudriere or ports-mgmt/poudriere-devel is installed.

The basic configuration shown here puts a single jail-, port-, and set-specific make.conf in /usr/local/etc/poudriere.d. The filename in this example is created by combining the jail name, port name, and set name: 13amd64-local-workstation-make.conf. The system make.conf and this new file are combined at build time to create the make.conf used by the build jail.

Packages to be built are entered in 13amd64-local-workstation-pkglist (ports with FLAVORS can be defined with @FLAVOR):


Options and dependencies for the specified ports are configured:

# poudriere options -j 13amd64 -p local -z workstation -f 13amd64-local-workstation-pkglist

Finally, packages are built and a package repository is created:

# poudriere bulk -j 13amd64 -p local -z workstation -f 13amd64-local-workstation-pkglist

While running, pressing Ctrl+t displays the current state of the build. poudriere also builds files in /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 poudriere(8) and the main web site,

4.6.2. 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 /usr/local/etc/pkg/repos/FreeBSD.conf that contains the following:

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: /usr/local/poudriere/data/packages/13amd64, where 13amd64 is the name of the build.

If the URL to the package repository is:, then the repository configuration file in /usr/local/etc/pkg/repos/custom.conf would look like:

custom: {
	url: "",
	enabled: yes,

If exposing the package repository to the internet is not desired, the file:// protocol can be used to point to the repository directly:

custom: {
	url: "file:///usr/local/poudriere/data/packages/11amd64",
	enabled: yes,

4.7. 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 /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 .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 .sample extension.

  • Applications which provide documentation will install it into /usr/local/share/doc and many applications also install manual pages. This documentation should be consulted before continuing.

  • Some applications run services which must be added to /etc/rc.conf before starting the application. These applications usually install a startup script in /usr/local/etc/rc.d. See Starting Services for more information.

    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 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.

4.8. Dealing with Broken Ports

When a port does not build or install, try the following:

  1. Search to see if there is a fix pending for the port in the Problem Report database. If so, implementing the proposed fix may fix the issue.

  2. Ask the maintainer of the port for help. Type make maintainer in the ports skeleton or read the port’s Makefile to find the maintainer’s email address. Remember to include the output leading up to the error in the email to the maintainer.

    Some ports are not maintained by an individual but instead by a group maintainer represented by a mailing list. Many, but not all, of these addresses look like Please take this into account when sending an email.

    In particular, ports maintained by 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 Writing FreeBSD Problem Reports.

  3. Fix it! The Porter’s Handbook includes detailed information on the ports infrastructure so that you can fix the occasional broken port or even submit your own!

  4. Install the package instead of the port using the instructions in Using pkg for Binary Package Management.

Chapter 5. The X Window System

5.1. Synopsis

An installation of FreeBSD using bsdinstall does not automatically install a graphical user interface. This chapter describes how to install and configure Xorg, which provides the open source X Window System used to provide a graphical environment. It then describes how to find and install a desktop environment or window manager.

Before reading this chapter, you should:

After reading this chapter, you will know:

  • The various components of the X Window System, and how they interoperate.

  • How to install and configure Xorg.

  • How to use TrueType® fonts in Xorg.

  • How to set up your system for graphical logins (XDM).

5.2. Installing Xorg

On FreeBSD, Xorg can be installed as a package or port.

The binary meta package can be installed quickly but with fewer options for customization:

# pkg install xorg

Either of these installations results in the complete Xorg system being installed.

The current user must be a member of the video group. To add a user to video group, execute the following command:

# pw groupmod video -m username

A smaller version of the X system suitable for experienced users is available in x11/xorg-minimal. Most of the documents, libraries, and applications will not be installed. Some applications require these additional components to function.

Video cards, monitors, and input devices are automatically detected and do not require any manual configuration. Do not create xorg.conf or run a -configure step unless automatic configuration fails.

5.3. Graphic card drivers

The following table shows the different graphics cards supported by FreeBSD, which package should be installed and its corresponding module.

Table 7. Graphic card packages


Open Source




Open Source


amdgpu and radeonkms




nvidia or nvidia-modeset


Open Source




Open Source




Open Source


VirtualBox® OSE additions include the vboxvideo driver.


Open Source



The following command can be used to identify which graphics card is installed in the system:

% pciconf -lv|grep -B4 VGA

The output should be similar to the following:

vgapci0@pci0:0:2:0:     class=0x030000 rev=0x07 hdr=0x00 vendor=0x8086 device=0x2a42 subvendor=0x17aa subdevice=0x20e4
    vendor     = 'Intel Corporation'
    device     = 'Mobile 4 Series Chipset Integrated Graphics Controller'
    class      = display
    subclass   = VGA

If the graphics card is not supported by Intel®, AMD® or NVIDIA® drivers, then VESA or SCFB modules should be used. VESA module must be used when booting in BIOS mode and SCFB module must be used when booting in UEFI mode.

This command can be used to check the booting mode:

% sysctl machdep.bootmethod

The output should be similar to the following:

machdep.bootmethod: BIOS

5.3.1. Intel®

Intel® Graphics refers to the class of graphics chips that are integrated on the same die as an Intel® CPU. Wikipedia offers a good overview of the variations and names used for generations of Intel HD Graphics.

The graphics/drm-kmod package indirectly provides a range of kernel modules for use with Intel® Graphics cards. The Intel® driver can be installed by executing the following command:

# pkg install drm-kmod

Then add the module to /etc/rc.conf file, executing the following command:

# sysrc kld_list+=i915kms

If a high CPU usage is noticed or excessive tearing with HD video, the installation of multimedia/libva-intel-driver may help. To install the package execute the following command:

# pkg install libva-intel-driver mesa-libs mesa-dri

5.3.2. AMD®

The graphics/drm-kmod package indirectly provides a range of kernel modules for use with AMD® Graphics cards. The modules amdgpu and radeonkms can be used depending the generation of the hardware. The FreeBSD project maintains an AMD graphics support matrix to determine which driver must be used.

AMD® driver can be installed by executing the following command:

# pkg install drm-kmod

For post-HD7000 or Tahiti graphic cards add the module to /etc/rc.conf file, executing the following command:

# sysrc kld_list+=amdgpu

For older graphic cards (pre-HD7000 or pre-Tahiti) add the module to /etc/rc.conf file, executing the following command:

# sysrc kld_list+=radeonkms

5.3.3. NVIDIA®

FreeBSD supports different versions of the proprietary NVIDIA® driver. Users of newer graphics cards should install the x11/nvidia-driver package. Those with older cards will have to check below which version supports them.

Table 8. Supported versions of NVIDIA® drivers
PackageSupported hardware


supported hardware


supported hardware


supported hardware


supported hardware


supported hardware

Version 304 of the NVIDIA® graphics driver (nvidia-driver-304) does not support xorg-server 1.20 or later.

The latest NVIDIA® driver can be installed by running the following command:

# pkg install nvidia-driver

Then add the module to /etc/rc.conf file, executing the following command:

# sysrc kld_list+=nvidia-modeset

The nvidia driver must be used if the packages x11/nvidia-driver-304 or x11/nvidia-driver-340 have been installed.

# sysrc kld_list+=nvidia

5.4. Xorg Configuration

Xorg supports most common video cards, keyboards, and pointing devices.

Video cards, monitors, and input devices are automatically detected and do not require any manual configuration. Do not create xorg.conf or run a Xorg -configure step unless automatic configuration fails.

5.4.1. Configuration Files

Xorg looks in several directories for configuration files. /usr/local/etc/X11/ is the recommended directory for these files on FreeBSD. Using this directory helps keep application files separate from operating system files.

5.4.2. Single or Multiple Files

It is easier to use multiple files that each configure a specific setting than the traditional single xorg.conf. These files are stored in the /usr/local/etc/X11/xorg.conf.d/ subdirectory.

The traditional single xorg.conf still works, but is neither as clear nor as flexible as multiple files in the /usr/local/etc/X11/xorg.conf.d/ subdirectory.

5.4.3. Video Cards

The driver for the graphics card can be specified in the /usr/local/etc/X11/xorg.conf.d/ directory.

To configure the Intel® driver in a configuration file:

Example 14. Select Intel® Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "intel"

To configure the AMD® driver in a configuration file:

Example 15. Select AMD® Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "radeon"

To configure the NVIDIA® driver in a configuration file:

Example 16. Select NVIDIA® Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "nvidia"

To configure the VESA driver in a configuration file:

Example 17. Select VESA Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "vesa"

To configure the SCFB driver in a configuration file:

Example 18. Select SCFB Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "scfb"

To configure multiple video cards, the BusID can be added. A list of video card bus IDs can be displayed by executing:

% pciconf -lv | grep -B3 display

The output should be similar to the following:

vgapci0@pci0:0:2:0:     class=0x030000 rev=0x07 hdr=0x00 vendor=0x8086 device=0x2a42 subvendor=0x17aa subdevice=0x20e4
    vendor     = 'Intel Corporation'
    device     = 'Mobile 4 Series Chipset Integrated Graphics Controller'
    class      = display
vgapci1@pci0:0:2:1:     class=0x038000 rev=0x07 hdr=0x00 vendor=0x8086 device=0x2a43 subvendor=0x17aa subdevice=0x20e4
    vendor     = 'Intel Corporation'
    device     = 'Mobile 4 Series Chipset Integrated Graphics Controller'
    class      = display
Example 19. Select Intel® Video Driver and NVIDIA® Video Driver in a File


Section "Device"
	Identifier "Card0"
	Driver     "intel"
	BusID     "pci0:0:2:0"

Section "Device"
	Identifier "Card0"
	Driver     "nvidia"
	BusID     "pci0:0:2:1"

5.4.4. Monitors

Almost all monitors support the Extended Display Identification Data standard (EDID). Xorg uses EDID to communicate with the monitor and detect the supported resolutions and refresh rates. Then it selects the most appropriate combination of settings to use with that monitor.

Other resolutions supported by the monitor can be chosen by setting the desired resolution in configuration files, or after the X server has been started with xrandr(1). Using RandR (Resize and Rotate)

Run xrandr(1) without any parameters to see a list of video outputs and detected monitor modes:

% xrandr

The output should be similar to the following:

Screen 0: minimum 320 x 200, current 2560 x 960, maximum 8192 x 8192
LVDS-1 connected 1280x800+0+0 (normal left inverted right x axis y axis) 261mm x 163mm
   1280x800      59.99*+  59.81    59.91    50.00
   1280x720      59.86    59.74
   1024x768      60.00
   1024x576      59.90    59.82
   960x540       59.63    59.82
   800x600       60.32    56.25
   864x486       59.92    59.57
   640x480       59.94
   720x405       59.51    58.99
   640x360       59.84    59.32
VGA-1 connected primary 1280x960+1280+0 (normal left inverted right x axis y axis) 410mm x 257mm
   1280x1024     75.02    60.02
   1440x900      74.98    60.07
   1280x960      60.00*
   1280x800      74.93    59.81
   1152x864      75.00
   1024x768      75.03    70.07    60.00
   832x624       74.55
   800x600       72.19    75.00    60.32    56.25
   640x480       75.00    72.81    66.67    59.94
   720x400       70.08
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
HDMI-2 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
DP-3 disconnected (normal left inverted right x axis y axis)

This shows that the VGA-1 output is being used to display a screen resolution of 1280x960 pixels at a refresh rate of about 60 Hz. The LVDS-1 is being used as a secondary monitor to display a screen resolution of 1280x800 pixels at a refresh rate of about 60 Hz. Monitors are not attached to the HDMI-1, HDMI-2, DP-1, DP-2 and DP-3 connectors.

Any of the other display modes can be selected with xrandr(1). For example, to switch to 1280x1024 at 60 Hz:

% xrandr --output LVDS-1 --mode 1280x720 --rate 60 Using the Xorg configuration file

The monitor configuration can also be set in a configuration file.

To set a screen resolution of 1024x768 in a configuration file:

Example 20. Set Screen Resolution in a File


Section "Screen"
	Identifier "Screen0"
	Device     "Card0"
	SubSection "Display"
	Modes      "1024x768"

5.4.5. Input Devices

Xorg supports the vast majority of input devices via x11/libinput.

Some desktop environments (such as KDE Plasma) provide a graphical UI for setting these parameters. Check if this is the case before resorting to manual configuration editing.

For example, to configure the keyboard layout:

Example 21. Setting a Keyboard Layout


Section "InputClass"
        Identifier "Keyboard1"
        MatchIsKeyboard "on"
        Option "XkbLayout" "es, fr"
        Option "XkbModel" "pc104"
        Option "XkbVariant" ",qwerty"
        Option "XkbOptions" "grp:win_space_toggle"

5.5. Using Fonts in Xorg

The default fonts that ship with Xorg are less than ideal for typical desktop publishing applications. Large presentation fonts show up jagged and unprofessional looking, and small fonts are almost completely unintelligible. However, there are several free, high quality Type1 (PostScript®) fonts available which can be readily used with Xorg.

5.5.1. Type1 Fonts

The URW font collection (x11-fonts/urwfonts) includes high quality versions of standard type1 fonts (Times Roman™, Helvetica™, Palatino™ and others). The Freefonts collection (x11-fonts/freefonts) includes many more fonts, but most of them are intended for use in graphics software such as the Gimp, and are not complete enough to serve as screen fonts. In addition, Xorg can be configured to use TrueType® fonts with a minimum of effort. For more details on this, see the X(7) manual page or TrueType® Fonts.

To install the above Type1 font collections from binary packages, run the following commands:

# pkg install urwfonts

And likewise with the freefont or other collections. To have the X server detect these fonts, add an appropriate line to the X server configuration file (/usr/local/etc/X11/xorg.conf.d/90-fonts.conf), which reads:

Section "Files"
  FontPath "/usr/local/share/fonts/urwfonts/"

Alternatively, at the command line in the X session run:

% xset fp+ /usr/local/share/fonts/urwfonts
% xset fp rehash

This will work but will be lost when the X session is closed, unless it is added to the startup file (~/.xinitrc for a normal startx session, or ~/.xsession when logging in through a graphical login manager like XDM). A third way is to use the new /usr/local/etc/fonts/local.conf as demonstrated in Anti-Aliased Fonts.

5.5.2. TrueType® Fonts

Xorg has built in support for rendering TrueType® fonts. There are two different modules that can enable this functionality. The freetype module is used in this example because it is more consistent with the other font rendering back-ends. To enable the freetype module just add the following line to the "Module" section of /usr/local/etc/X11/xorg.conf.d/90-fonts.conf.

Load  "freetype"

Now make a directory for the TrueType® fonts (for example, /usr/local/share/fonts/TrueType) and copy all of the TrueType® fonts into this directory. Keep in mind that TrueType® fonts cannot be directly taken from an Apple® Mac®; they must be in UNIX®/MS-DOS®/Windows® format for use by Xorg. Once the files have been copied into this directory, use mkfontscale to create a fonts.dir, so that the X font renderer knows that these new files have been installed. mkfontscale can be installed as a package:

# pkg install mkfontscale

Then create an index of X font files in a directory:

# cd /usr/local/share/fonts/TrueType
# mkfontscale

Now add the TrueType® directory to the font path. This is just the same as described in Type1 Fonts:

% xset fp+ /usr/local/share/fonts/TrueType
% xset fp rehash

or add a FontPath line to xorg.conf.

Now Gimp, LibreOffice, and all of the other X applications should now recognize the installed TrueType® fonts. Extremely small fonts (as with text in a high resolution display on a web page) and extremely large fonts (within LibreOffice) will look much better now.

5.5.3. Anti-Aliased Fonts

All fonts in Xorg that are found in /usr/local/share/fonts/ and ~/.fonts/ are automatically made available for anti-aliasing to Xft-aware applications. Most recent applications are Xft-aware, including KDE, GNOME, and Firefox.

To control which fonts are anti-aliased, or to configure anti-aliasing properties, create (or edit, if it already exists) the file /usr/local/etc/fonts/local.conf. Several advanced features of the Xft font system can be tuned using this file; this section describes only some simple possibilities. For more details, please see fonts-conf(5).

This file must be in XML format. Pay careful attention to case, and make sure all tags are properly closed. The file begins with the usual XML header followed by a DOCTYPE definition, and then the <fontconfig> tag:

<?xml version="1.0"?>
      <!DOCTYPE fontconfig SYSTEM "fonts.dtd">

As previously stated, all fonts in /usr/local/share/fonts/ as well as ~/.fonts/ are already made available to Xft-aware applications. To add another directory outside of these two directory trees, add a line like this to /usr/local/etc/fonts/local.conf:


After adding new fonts, and especially new font directories, rebuild the font caches:

# fc-cache -f

Anti-aliasing makes borders slightly fuzzy, which makes very small text more readable and removes "staircases" from large text, but can cause eyestrain if applied to normal text. To exclude font sizes smaller than 14 point from anti-aliasing, include these lines:

	<match target="font">
	    <test name="size" compare="less">
	    <edit name="antialias" mode="assign">
	<match target="font">
	    <test name="pixelsize" compare="less" qual="any">
	    <edit mode="assign" name="antialias">

Spacing for some monospaced fonts might also be inappropriate with anti-aliasing. This seems to be an issue with KDE, in particular. One possible fix is to force the spacing for such fonts to be 100. Add these lines:

	<match target="pattern" name="family">
	   <test qual="any" name="family">
	   <edit name="family" mode="assign">
	<match target="pattern" name="family">
	    <test qual="any" name="family">
	    <edit name="family" mode="assign">

(this aliases the other common names for fixed fonts as "mono"), and then add:

	<match target="pattern" name="family">
	     <test qual="any" name="family">
	     <edit name="spacing" mode="assign">

Certain fonts, such as Helvetica, may have a problem when anti-aliased. Usually this manifests itself as a font that seems cut in half vertically. At worst, it may cause applications to crash. To avoid this, consider adding the following to local.conf:

	<match target="pattern" name="family">
	     <test qual="any" name="family">
	     <edit name="family" mode="assign">

After editing local.conf, make certain to end the file with the </fontconfig> tag. Not doing this will cause changes to be ignored.

Users can add personalized settings by creating their own ~/.config/fontconfig/fonts.conf. This file uses the same XML format described above.

One last point: with an LCD screen, sub-pixel sampling may be desired. This basically treats the (horizontally separated) red, green and blue components separately to improve the horizontal resolution; the results can be dramatic. To enable this, add the line somewhere in local.conf:

	 <match target="font">
	     <test qual="all" name="rgba">
	     <edit name="rgba" mode="assign">

Depending on the sort of display, rgb may need to be changed to bgr, vrgb or vbgr: experiment and see which works best.

For more information about how to install and configure fonts on FreeBSD, please read the article Fonts and FreeBSD.

Chapter 6. Wayland on FreeBSD

6.1. Wayland Synopsis

Wayland is a new display server, but it differs from Xorg in several important ways. First, Wayland is only a protocol that acts as an intermediary between clients using a different mechanism which removes the dependency on an X server. Xorg includes both the X11 protocol, used to run remote displays and the X server will accept connections and display windows. Under Wayland, the compositor or window manager provides the display server instead of a traditional X server.

Since Wayland is not an X server, traditional X screen connections will need to utilize other methods such as VNC or RDP for remote desktop management. Second, Wayland can manage composite communications between clients and a compositor as a separate entity which does not need to support the X protocols.

Wayland is relatively new, and not all software has been updated to run natively without Xwayland support. Because Wayland does not provide the X server, and expects compositors to provide that support, X11 window managers that do not yet support Wayland will require that Xwayland is not started with the -rootless parameter. The -rootless parameter, when removed, will restore X11 window manager support.

The current NVIDIA® driver should work with most wlroots compositors, but it may be a little unstable and not support all features at this time. Volunteers to help work on the NVIDIA® DRM are requested.

Currently, a lot of software will function with minimal issues on Wayland, including Firefox. And a few desktops are also available, such as the Compiz Fusion replacement, known as Wayfire, and the i3 window manager replacement, Sway.

As of May, 2021, plasma5-kwin does support Wayland on FreeBSD. To use Plasma under Wayland, use the startplasma-wayland parameter to ck-launch-session and tie in dbus with: ck-launch-session dbus-run-session startplasma-wayland to get it working.

For compositors, a kernel supporting the evdev(4) driver must exist to utilize the keybinding functionality. This is built into the GENERIC kernel by default; however, if it has been customized and evdev(4) support was stripped out, the evdev(4) module will need to be loaded. In addition, users of Wayland will need to be members of the video group. To quickly make this change, use the pw command:

pw groupmod video -m user

Installing Wayland is simple; there is not a great deal of configuration for the protocol itself. Most of the composition will depend on the chosen compositor. By installing seatd now, a step is skipped as part of the compositor installation and configuration as seatd is needed to provide non-root access to certain devices.

All of the compositors described here should work with graphics/drm-kmod open source drivers; however, the NVIDIA® graphics cards may have issues when using the proprietary drivers. Begin by installing the following packages:

# pkg install wayland seatd

Once the protocol and supporting packages have been installed, a compositor must create the user interface. Several compositors will be covered in the following sections. All compositors using Wayland will need a runtime directory defined in the environment, which can be achieved with the following command in the bourne shell:

% export XDG_RUNTIME_DIR=/var/run/user/`id -u`

It is important to note that most compositors will search the XDG_RUNTIME_DIR directory for the configuration files. In the examples included here, a parameter will be used to specify a configuration file in ~/.config to keep temporary files and configuration files separate. It is recommended that an alias be configured for each compositor to load the designated configuration file.

It has been reported that ZFS users may experience issues with some Wayland clients because they need access to posix_fallocate() in the runtime directory. While the author could not reproduce this issue on their ZFS system, a recommended workaround is not to use ZFS for the runtime directory and instead use tmpfs for the /var/run directory. In this case, the tmpfs file system is used for /var/run and mounted through the command mount -t tmpfs tmpfs /var/run command and then make this change persist across reboots through /etc/fstab. The XDG_RUNTIME_DIR environment variable could be configured to use /var/run/user/$UID and avoid potential pitfalls with ZFS. Consider that scenario when reviewing the configuration examples in the following sections.

The seatd daemon helps manage access to shared system devices for non-root users in compositors; this includes graphics cards. For traditional X11 managers, seatd is not needed, such as both Plasma and GNOME, but for the Wayland compositors discussed here, it will need enabled on the system and be running before starting a compositor environment. To enable and start the seatd daemon now, and on system initialization:

# sysrc seatd_enable=”YES”
# service seatd start

Afterward, a compositor, which is similar to an X11 desktop, will need to be installed for the GUI environment. Three are discussed here, including basic configuration options, setting up a screen lock, and recommendations for more information.

6.2. The Wayfire Compositor

Wayfire is a compositor that aims to be lightweight and customizable. Several features are available, and it brings back several elements from the previously released Compiz Fusion desktop. All of the parts look beautiful on modern hardware. To get Wayfire up and running, begin by installing the required packages:

# pkg install wayfire wf-shell alacritty swaylock-effects swayidle wlogout kanshi mako wlsunset

The alacritty package provides a terminal emulator. Still, it is not completely required as other terminal emulators such as kitty, and XFCE-4 Terminal have been tested and verified to work under the Wayfire compositor. Wayfire configuration is relatively simple; it uses a file that should be reviewed for any customizations. To begin, copy the example file over to the runtime environment configuration directory and then edit the file:

% mkdir ~/.config/wayfire
% cp /usr/local/share/examples/wayfire/wayfire.ini ~/.config/wayfire

The defaults for most users should be fine. Within the configuration file, items like the famous cube are pre-configured, and there are instructions to help with the available settings. A few primary settings of note include:

mode = 1920x1080@60000
position = 0,0
transform = normal
scale = 1.000000

In this example, from the configuration file, the screen’s output should be the listed mode at the listed hertz. For example, the mode should be set to widthxheight@refresh_rate. The position places the output at a specific pixel location specified. The default should be fine for most users. Finally, transform sets a background transform, and scale will scale the output to the specified scale factor. The defaults for these options are generally acceptable; for more information, see the documentation.

As mentioned, Wayland is new, and not all applications work with the protocol yet. At this time, sddm does not appear to support starting and managing compositors in Wayland. The swaylock utility has been used instead in these examples. The configuration file contains options to run swayidle and swaylock for idle and locking of the screen.

This option to define the action to take when the system is idle is listed as:

idle = swaylock

And the lock timeout is configured using the following lines:

toggle = <super> KEY_Z
screensaver_timeout = 300
dpms_timeout = 600

The first option will lock the screen after 300 seconds, and after another 300, the screen will shut off through the dpms_timeout option.

One final thing to note is the <super> key. Most of the configuration mentions this key, and it is the traditional Windows key on the keyboard. Most keyboards have this super key available; however, it should be remapped within this configuration file if it is not available. For example, to lock the screen, press and hold the super key, the shift key, and press the escape key. nless the mappings have changed, this will execute the swaylock application. The default configuration for swaylock will show a grey screen; however, the application is highly customizable and well documented. In addition, since the swaylock-effects is the version that was installed, there are several options available such as the blur effect, which can be seen using the following command:

% swaylock --effect-blur 7x5

There is also the --clock parameter which will display a clock with the date and time on the lock screen. When x11/swaylock-effects was installed, a default pam.d configuration was included. It provides the default options that should be fine for most users. More advanced options are available; see the PAM documentation for more information.

At this point, it is time to test Wayfire and see if it can start up on the system. Just type the following command:

% wayfire -c ~/.config/wayfire/wayfire.ini

The compositor should now start and display a background image along with a menu bar at the top of the screen. Wayfire will attempt to list installed compatible applications for the desktop and present them in this drop-down menu; for example, if the XFCE-4 file manager is installed, it will show up in this drop-down menu. If a specific application is compatible and valuable enough for a keyboard shortcut, it may be mapped to a keyboard sequence using the wayfire.ini configuration file. Wayfire also has a configuration tool named Wayfire Config Manager. It is located in the drop-down menu bar but may also be started through a terminal by issuing the following command:

% wcm

Various Wayfire configuration options, including the composite special effects, maybe enabled, disabled, or configured through this application. In addition, for a more user-friendly experience, a background manager, panel, and docking application may be enabled in the configuration file:

panel = wf-panel
dock = wf-dock
background = wf-background

Changes made through wcm will overwrite custom changes in the wayfire.ini configuration file. The wayfire.ini file is highly recommended to be backed up so any essential changes may be restored.

Finally, the default launcher listed in the wayfire.ini is x11/wf-shell which may be replaced with other panels if desired by the user.

6.3. The Hikari Compositor

The Hikari compositor uses several concepts centered around productivity, such as sheets, workspaces, and more. In that way, it resembles a tiling window manager. Breaking this down, the compositor starts with a single workspace, which is similar to virtual desktops. Hikari uses a single workspace or virtual desktop for user interaction. The workspace is made up of several views, which are the working windows in the compositor grouped as either sheets or groups. Both sheets and groups are made up of a collection of views; again, the windows that are grouped together. When switching between sheets or groups, the active sheet or group will become known collectively as the workspace. The manual page will break this down into more information on the functions of each but for this document, just consider a single workspace utilizing a single sheet. Hikari installation will comprise of a single package, x11-wm/hikari, and a terminal emulator alacritty:

# pkg install hikari alacritty

Other shells, such as kitty or the Plasma Terminal, will function under Wayland. Users should experiment with their favorite terminal editor to validate compatibility.

Hikari uses a configuration file, hikari.conf, which could either be placed in the XDG_RUNTIME_DIR or specified on startup using the -c parameter. An autostart configuration file is not required but may make the migration to this compositor a little easier. Beginning the configuration is to create the Hikari configuration directory and copy over the configuration file for editing:

% mkdir ~/.config/hikari
% cp /usr/local/etc/hikari/hikari.conf ~/.config/hikari

The configuration is broken out into various stanzas such as ui, outputs, layouts, and more. For most users, the defaults will function fine; however, some important changes should be made. For example, the $TERMINAL variable is normally not set within the user’s environment. Changing this variable or altering the hikari.conf file to read:

terminal = "/usr/local/bin/alacritty"

Will launch the alacritty terminal using the bound key press. While going through the configuration file, it should be noted that the capital letters are used to map keys out for the user. For example, the L key for starting the terminal L+Return is actually the previously discussed super key or Windows logo key. Therefore, holding the L/super/Windows key and pressing Enter will open the specified terminal emulator with the default configuration. Mapping other keys to applications require an action definition to be created. For this, the action item should be listed in the actions stanza, for example:

actions {
  terminal = "/usr/local/bin/alacritty"
  browser = "/usr/local/bin/firefox"

Then an action may be mapped under the keyboard stanza, which is defined within the bindings stanza:

bindings {
  keyboard {
    "L+Return" = action-terminal
    "L+b" = action-browser

After Hikari is restarted, holding the Windows logo button and pressing the b key on the keyboard will start the web browser. The compositor does not have a menu bar, and it is recommended the user set up, at minimal, a terminal emulator before migration. The manual page contains a great deal of documentation it should be read before performing a full migration. Another positive aspect about Hikari is that, while migrating to the compositor, Hikari can be started in the Plasma and GNOME desktop environments, allowing for a test-drive before completely migrating.

Locking the screen in Hikari is easy because a default pam.d configuration file and unlock utility are bundled with the package. The key binding for locking the screen is L (Windows logo key)+ Shift + Backspace. It should be noted that all views not marked public will be hidden. These views will never accept input when locked but beware of sensitive information being visible. For some users, it may be easier to migrate to a different screen locking utility such as swaylock-effects, discussed in this section. To start Hikari, use the following command:

% hikari -c ~/.config/hikari/hikari.conf

6.4. The Sway Compositor

The Sway compositor is a tiling compositor that attempts to replace the i3 windows manager. It should work with the user’s current i3 configuration; however, new features may require some additional setup. In the forthcoming examples, a fresh installation without migrating any i3 configuration will be assumed. To install Sway and valuable components, issue the following command as the root user:

# pkg install sway swayidle swaylock-effects alacritty dmenu-wayland dmenu

For a basic configuration file, issue the following commands and then edit the configuration file after it is copied:

% mkdir ~/.config/sway
% cp /usr/local/etc/sway/config ~/.config/sway

The base configuration file has many defaults, which will be fine for most users. Several important changes should be made like the following:

# Logo key. Use Mod1 for Alt.
input * xkb_rules evdev
set $mod Mod4
# Your preferred terminal emulator
set $term alacritty
set $lock swaylock -f -c 000000
output "My Workstation" mode 1366x786@60Hz position 1366 0
output * bg ~/wallpapers/mywallpaper.png stretch
### Idle configuration
exec swayidle -w \
          timeout 300 'swaylock -f -c 000000' \
          timeout 600 'swaymsg "output * dpms off"' resume 'swaymsg "output * dpms on"' \
          before-sleep 'swaylock -f -c 000000'

In the previous example, the xkb rules for evdev(4) events are loaded, and the $mod key is set to the Windows logo key for the key bindings. Next, the terminal emulator was set to be alacritty, and a screen lock command was defined; more on this later. The output keyword, the mode, the position, a background wallpaper, and Sway is also told to stretch this wallpaper to fill out the screen. Finally, swaylock is set to daemonize and lock the screen after a timeout of 300 seconds, placing the screen or monitor into sleep mode after 600 seconds. The locked background color of 000000, which is black, is also defined here. Using swaylock-effects, a clock may also be displayed with the --clock parameter. See the manual page for more options. The sway-output(5) manual page should also be reviewed; it includes a great deal of information on customing the output options available.

While in Sway, to bring up a menu of applications, hold the Windows logo key (mod) and press the d key. The menu may be navigated using the arrow keys on the keyboard. There is also a method to manipulate the layout of the bar and add a tray; read the sway-bar(5) manual page for more information. The default configuration adds a date and time to the upper right-hand corner. See the Bar stanza in the configuration file for an example. By default, the configuration does not include locking the screen outside of the example above, enabling a lockout timer. Creating a lock key binding requires the following line to the Key bindings section:

# Lock the screen manually
bindsym $mod+Shift+Return exec $lock

Now the screen may be locked using the combination of holding the Windows logo key, pressing and holding shift, and finally pressing return. When Sway is installed, whether from a package or the FreeBSD Ports Collection, a default file for pam.d was installed. The default configuration should be acceptable for most users, but more advanced options are available. Read through the PAM documentation for more information.

Finally, to exit Sway and return to the shell, hold the Windows logo key, the shift key, and press the e key. A prompt will be displayed with an option to exit Sway. During migration, Sway can be started through a terminal emulator on an X11 desktop such as Plasma. This makes testing different changes and key bindings a little easier prior to fully migrating to this compositor. To start Sway, issue the following command:

% sway -c ~/.config/sway/config

6.5. Using Xwayland

When installing Wayland, the Xwayland binary should have been installed unless Wayland was built without X11 support. If the /usr/local/bin/Xwayland file does not exist, install it using the following command:

# pkg install xwayland-devel

The development version of Xwayland is recommended and was most likely installed with the Wayland package. Each compositor has a method of enabling or disabling this feature.

Once Xwayland has been installed, configure it within the chosen compositor. For Wayfire, the following line is required in the wayfire.ini file:

xwayland = true

For the Sway compositor, Xwayland should be enabled by default. Even so, it is recommened to manually add a configuration line in the ~/.config/sway/config like the following:

xwayland enable

Finally, for Hikari, no changes are needed. Support for Xwayland is build in by default. To disable that support, rebuild the package from the ports collection and disable Xwayland support at that time.

After these changes are made, start the compositor at the command line and execute a terminal from the key bindings. Within this terminal, issue the env command and search for the DISPLAY variables. If the compositor was able to properly start the Xwayland X server, these environment variables should look similar to the following:

% env | grep DISPLAY

In this output, there is a default Wayland display and a display set for the Xwayland server. Another method to verify that Xwayland is functioning properly is to use install and test the small package:[x11/eyes] and check the output. If the xeyes application starts and the eyes follow the mouse pointer, Xwayland is functioning properly. If an error such as the following is displayed, something happened during the Xwayland intitialization and it may need reinstalled:

Error: Cannot open display wayland-0

A security feature of Wayland is that, without running an X server, there is not another network listener. Once Xwayland is enabled, this security feature is no longer applicable to the system.

For some compositors, such as Wayfire, Xwayland may not start properly. As such, env will show the following information for the DISPLAY environment variables:

% env | grep DISPLAY

Even though Xwayfire was installed and configured, X11 applications will not start giving a display issue. To work around this, verify that there is already an instance of Xwayland using a UNIX socket through these two methods. First, check the output from sockstat and search for X11-unix:

% sockstat | grep x11

There should be something similar to the following information:

trhodes  Xwayland   2734  8  stream /tmp/.X11-unix/X0
trhodes  Xwayland   2734  9  stream /tmp/.X11-unix/X0
trhodes  Xwayland   2734  10 stream /tmp/.X11-unix/X0
trhodes  Xwayland   2734  27 stream /tmp/.X11-unix/X0_
trhodes  Xwayland   2734  28 stream /tmp/.X11-unix/X0

This suggests the existence of an X11 socket. This can be further verified by attempting to execute Xwayland manually within a terminal emulator running under the compositor:

% Xwayland

If an X11 socket is already available, the following error should be presented to the user:

Fatal server error:
(EE) Server is already active for display 0
	If this server is no longer running, remove /tmp/.X0-lock
	and start again.

Since there is an active X display available using display zero, the environment variable was just set improperly, to fix this, change the DISPLAY environment variable to :0 and attempt to execute the application again. The following example uses mail/claws-mail as the application which needs the Xwayland service:

export DISPLAY=:0

After this change, the mail/claws-mail application should now start using Xwayland and function as expected.

6.6. Remote Desktop Using VNC

Earlier in this document it was noted that Wayland does not provide the same X server style access as Xorg provides. Instead, users are free to pick and choose a remote desktop protocol such as RDP or VNC. The FreeBSD Ports collection includes the wayvnc, which will support wlroots based compositors such as the ones discussed here. This application may be installed using:

# pkg install wayvnc

Unlike some other packages, wayvnc does not come with a configuration file. Thankfully, the manual page documents the important options and they may be extrapolated into a simple configuration file:


The key files will need to be generated, and it is highly recommended they be used for increased security of the connection. When invoked, wayvnc will search for the configuration file in ~/.config/wayvnc/config. This could be overwritten using the -C configuration_file option when starting the server. Thus, to start the wayvnc server, issue the following command:

% wayvnc -C ~/.config/wayvnc/config

At the time of this writing, there is no rc.d script to start wayvnc on system initialization. If that functionality is desired, a local startup file will need to be created. This is probably a feature request for the port maintainer.

6.7. Wayland Login Manager

While several login managers exist and are slowly migrating to Wayland, one option is the x11/ly text user interface (TUI) manager. Needing minimal configuration, ly will start Sway, Wayfire, and others by presenting a login window on system initialization. To install ly, issue the following command:

# pkg install ly

There will be some configuration hints presented, the import steps are to add the following lines to /etc/gettytab:


And then modify the ttyv1 line in /etc/ttys to match the following line:

ttyv1 "/usr/libexec/getty Ly" xterm onifexists secure

After a system reboot, a login should appear. To configure specific settings, such as language and edit /usr/local/etc/ly/config.ini. At minimal, this file should have the designated tty that was previously specified in /etc/ttys.

If setting ttyv0 up as the login terminal, it may be required to press the alt and F1 keys to properly see the login window.

When the login window appears, using the left and right arrows will swap through different, supported, window managers.

6.8. Useful Utilities

One useful Wayland utility which all compositors can make use of is the waybar. While Wayfire does come with a launch menu, an easy-to-use and fast taskbar is a good accessory for any compositor or desktop manager. A Wayland compatible taskbar that is fast and easy to configure is waybar. To install the package and a supporting audio control utility, issue the following command:

# pkg install pavucontrol waybar

To create the configuration directory and copy over a default configuration file, execute the following commands:

% mkdir ~/.config/waybar
% cp /usr/local/etc/xdg/waybar/config ~/.config/waybar

The lavalauncher utility provides a launch bar for various applications. There is no example configuration file provided with the package, so the following actions must be taken:

mkdir ~/.config/lavalauncher

An example configuration file that only includes Firefox, and is placed on the right, is below:

global-settings {
	watch-config-file = true;

bar {
	output            = eDP-1;
	position          = bottom;
	background-colour = "#202020";

	# Condition for the default configuration set.
	condition-resolution = wider-than-high;

	config {
		position = right;

	button {
		image-path          =     /usr/local/lib/firefox/browser/chrome/icons/default/default48.png;
		command[mouse-left] =     /usr/local/bin/firefox;
	button {
	  image-path           =   /usr/local/share/pixmaps/thunderbird.png;
	  command[mouse-left]  =   /usr/local/bin/thunderbird;

Chapter 7. Network

7.1. Synopsis

This chapter delves into the topic of network configuration and performance, showcasing the robust networking capabilities of the FreeBSD operating system. Whether working with wired or wireless networks, this chapter provides a comprehensive guide to configuring and optimizing network connectivity in FreeBSD.

Before diving into the details, it is beneficial for readers to have a basic understanding of networking concepts such as protocols, network interfaces, and addressing.

This chapter covers:

  • The ability to configure wired networks in FreeBSD, including network interface setup, addressing, and customization options.

  • The skills to configure wireless networks in FreeBSD, encompassing wireless network interface setup, security protocols, and troubleshooting techniques.

  • FreeBSD’s networking capabilities and its reputation for excellent network performance.

  • An understanding of various network services and protocols supported by FreeBSD, with configuration instructions for DNS, DHCP and more.

More information about how to make advanced network configurations in Advanced Networking.

7.2. Setting up the Network

Setting up a wired or wireless connection is a common task for a FreeBSD user. This section will show how to identify the wired and wireless network adapters and how to configure them.

Before starting with the configuration it is necessary to know the following network data:

  • If the network has DHCP

  • If the network does not have DHCP, the static IP to be used

  • The netmask

  • The IP address of the default gateway

The network connection may have been configured at installation time by bsdinstall(8).

7.2.1. Identify Network Adapters

FreeBSD supports a wide variety of network adapters for both wired and wireless networks. Check the Hardware Compatibility List for the used FreeBSD release to see if the network adapter is supported.

To get the network adapters used by our system execute the following command:

% pciconf -lv | grep -A1 -B3 network

The output should be similar to the following:

em0@pci0:0:25:0:        class=0x020000 rev=0x03 hdr=0x00 vendor=0x8086 device=0x10f5 subvendor=0x17aa subdevice=0x20ee
    vendor     = 'Intel Corporation' (1)
    device     = '82567LM Gigabit Network Connection' (2)
    class      = network
    subclass   = ethernet
iwn0@pci0:3:0:0:        class=0x028000 rev=0x00 hdr=0x00 vendor=0x8086 device=0x4237 subvendor=0x8086 subdevice=0x1211
    vendor     = 'Intel Corporation' (1)
    device     = 'PRO/Wireless 5100 AGN [Shiloh] Network Connection' (2)
    class      = networ

The text before the '@' symbol is the name of the driver controlling the device. In this case these are em(4) and iwn(4).

1Shows the name of the vendor
2Shows the name of the device

It is only necessary to load the network interface card module if FreeBSD has not detected it correctly.

For example, to load the alc(4) module, execute the following command:

# kldload if_alc

Alternatively, to load the driver as a module at boot time, place the following line in /boot/loader.conf:


7.3. Wired Networks

Once the right driver is loaded the network adapter needs to be configured. FreeBSD uses the driver name followed by a unit number to name the network interface adapter. The unit number represents the order in which the adapter is detected at boot time, or is later discovered.

For example, em0 is the first network interface card (NIC) on the system using the em(4) driver.

To display the network interface configuration, enter the following command:

% ifconfig

The output should be similar to the following:

em0: flags=8863<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        ether 00:1f:16:0f:27:5a
        inet6 fe80::21f:16ff:fe0f:275a%em0 prefixlen 64 scopeid 0x1
        inet netmask 0xffffff00 broadcast
        media: Ethernet autoselect (1000baseT <full-duplex>)
        status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
        inet6 ::1 prefixlen 128
        inet6 fe80::1%lo0 prefixlen 64 scopeid 0x2
        inet netmask 0xff000000
        groups: lo
        nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>

In this example, the following devices were displayed:

  • em0: The Ethernet interface.

  • lo0: The loop interface is a software loopback mechanism which may be used for performance analysis, software testing, and/or local communication. More information in lo(4).

The example shows that em0 is up and running.

The key indicators are:

  1. UP means that the interface is configured and ready.

  2. The interface has an IPv4 Internet (inet) address,

  3. The interface has an IPv6 Internet (inet6) address, fe80::21f:16ff:fe0f:275a%em0.

  4. It has a valid subnet mask (netmask), where 0xffffff00 is the same as

  5. It has a valid broadcast address,

  6. The MAC address of the interface (ether) is 00:1f:16:0f:27:5a.

  7. The physical media selection is on autoselection mode (media: Ethernet autoselect (1000baseT <full-duplex>)).

  8. The status of the link (status) is active, indicating that the carrier signal is detected. For em0, the status: no carrier status is normal when an Ethernet cable is not plugged into the interface.

If the ifconfig(8) output had shown something similar to the next output it would indicate the interface has not been configured:

em0: flags=8822<BROADCAST,SIMPLEX,MULTICAST> metric 0 mtu 1500
        ether 00:1f:16:0f:27:5a
        media: Ethernet autoselect
        status: no carrier

7.3.1. Configuring Static IPv4 Address

This section provides a guide to configuring a static IPv4 address on a FreeBSD system.

The network interface card configuration can be performed from the command line with ifconfig(8) but will not persist after a reboot unless the configuration is also added to /etc/rc.conf.

If the network was configured during installation by bsdinstall(8), some entries for the network interface card (NICs) may be already present. Double check /etc/rc.conf before executing sysrc(8).

The IP address can be set executing the following command:

# ifconfig em0 inet

To make the change persist across reboots execute the following command:

# sysrc ifconfig_em0="inet netmask"

Add the default router executing the following command:

# sysrc defaultrouter=""

Add the DNS records to /etc/resolv.conf:


Then restart netif and routing executing the following command:

# service netif restart && service routing restart

The connection can be tested using ping(8):

% ping -c2

The output should be similar to the following:

PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=51 time=55.173 ms
64 bytes from icmp_seq=1 ttl=51 time=53.093 ms

--- ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 53.093/54.133/55.173/1.040 ms

7.3.2. Configuring Dynamic IPv4 Address

If the network has a DHCP server, it is very easy to configure the network interface to use DHCP. FreeBSD uses dhclient(8) as the DHCP client. dhclient(8) will automatically provide the IP, the netmask and the default router.

To make the interface work with DHCP execute the following command:

# sysrc ifconfig_em0="DHCP"

dhclient(8) can be used manually by running the following command:

# dhclient em0

The output should be similar to the following:

DHCPREQUEST on em0 to port 67
unknown dhcp option value 0x7d
bound to -- renewal in 43200 seconds.

In this way it can be verified that the address assignment using DHCP works correctly.

dhclient(8) client can be started in background. This can cause trouble with applications depending on a working network, but it will provide a faster startup in many cases.

To execute dhclient(8) in background execute the following command:

# sysrc background_dhclient="YES"

Then restart netif executing the following command:

# service netif restart

The connection can be tested using ping(8):

% ping -c2

The output should be similar to the following:

PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=51 time=55.173 ms
64 bytes from icmp_seq=1 ttl=51 time=53.093 ms

--- ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 53.093/54.133/55.173/1.040 ms

7.3.3. 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 (RFC2462).

  • Mandatory multicast addresses.

  • Built-in IPsec (IP security).

  • Simplified header structure.

  • Support for mobile IP.

  • IPv6-to-IPv4 transition mechanisms.

FreeBSD includes the KAME project IPv6 reference implementation and comes with everything needed to use IPv6.

This section focuses on getting IPv6 configured and running.

There are three different types of IPv6 addresses:


A packet sent to a unicast address arrives at the interface belonging to the address.


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.


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, 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 0s 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:: 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 execute the following command:

# ifconfig

The output should be similar to the following:

em0: flags=8863<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        ether 00:1f:16:0f:27:5a
        inet netmask 0xffffff00 broadcast
        inet6 fe80::21f:16ff:fe0f:275a%em0 prefixlen 64 scopeid 0x1
        media: Ethernet autoselect (1000baseT <full-duplex>)
        status: active

In this example, the em0 interface is using fe80::21f:16ff:fe0f:275a%em0, an auto-configured link-local address which was automatically generated from the MAC address.

Some IPv6 addresses are reserved. A list of reserved addresses can be checked in the following table:

Table 9. Example IPv6 Reserved Addresses
IPv6 addressPrefixlength (Bits)DescriptionNotes


128 bits


Equivalent to in IPv4.


128 bits

loopback address

Equivalent to in IPv4.


96 bits

embedded IPv4

The lower 32 bits are the compatible IPv4 address.


96 bits

IPv4 mapped IPv6 address

The lower 32 bits are the IPv4 address for hosts which do not support IPv6.


10 bits


Equivalent to in IPv4.


7 bits


Unique local addresses are intended for local communication and are only routable within a set of cooperating sites.


8 bits



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 RFC3513.

7.3.4. Configuring Static IPv6 Address

To configure a FreeBSD system as an IPv6 client with a static IPv6 address it is necessary to set the IPv6 address.

Execute the following commands to meet the requirements:

# sysrc ifconfig_em0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64"

To assign a default router, specify its address executing the following command:

# sysrc ipv6_defaultrouter="2001:db8:4672:6565::1"

7.3.5. Configuring Dynamic IPv6 Address

If the network has a DHCP server, it is very easy to configure the network interface to use DHCP. dhclient(8) will provide automatically the IP, the netmask and the default router.

To make the interface works with DHCP execute the following command:

# sysrc ifconfig_em0_ipv6="inet6 accept_rtadv"
# sysrc rtsold_enable="YES"

7.3.6. Router Advertisement and Host Auto Configuration

This section demonstrates how to setup rtadvd(8) on an IPv6 router to advertise the IPv6 network prefix and default route.

To enable rtadvd(8), execute the following command:

# sysrc rtadvd_enable="YES"

It is important to specify the interface on which to do IPv6 router advertisement. For example, to tell rtadvd(8) to use em0:

# sysrc rtadvd_interfaces="em0"

Next, create the configuration file, /etc/rtadvd.conf as seen in this example:


Replace em0 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.

7.3.7. IPv6 and IPv4 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 execute the following command:

# sysrc ipv6_ipv4mapping="YES"

7.4. Wireless Networks

Most wireless networks are based on the IEEE® 802.11 standards.

FreeBSD supports networks that operate using 802.11a, 802.11b, 802.11g and 802.11n.

802.11ac support on FreeBSD is currently under development.

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.

There are three basic steps to configure a wireless network:

  1. Scan and select an access point

  2. Authenticate the station

  3. Configure an IP address or use DHCP.

The following sections discuss each step.

7.4.1. Quick Start to Connect to a Wireless Network

Connecting FreeBSD to an existing wireless network is a very common situation.

This procedure shows the steps required:

  • The first step will be to obtain the SSID (Service Set Identifier) and PSK (Pre-Shared Key) for the wireless network from the network administrator.

  • The second step will be to add an entry for this network to /etc/wpa_supplicant.conf. If the file does not exist, create it:

 ssid="myssid" (1)
 psk="mypsk" (2)
1Is the SSID of the wireless network. Replace it with the name of the wireless network.
2Is the PSK of the wireless network. Replace it with the password of the wireless network.
  • The third step will be to add the network entry to configure the network on startup:

# sysrc wlans_iwn0="wlan0"
# sysrc ifconfig_wlan0="WPA DHCP"
  • And the last step will be the restart netif service executing the following command:

# service netif restart

7.4.2. Basic Wireless Configuration

The first step will be to configure the wireless network card to an interface. To find out what wireless network cards are in the system check the section Identify Network Adapters.

# ifconfig wlan0 create wlandevice iwm0

To make the change persist across reboots execute the following command:

# sysrc wlans_iwn0="wlan0"

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 /etc/regdomain.xml. To set the data at runtime, use ifconfig:

# ifconfig wlan0 regdomain etsi2 country AT

To persist the settings, add it to /etc/rc.conf:

# sysrc create_args_wlan0="country AT regdomain etsi2"

7.4.3. Scan Wireless Networks

Available wireless networks can be scanned using ifconfig(8).

To list the wireless networks execute the following command:

# ifconfig wlan0 up list scan

The output should be similar to the following:

SSID/MESH ID                      BSSID              CHAN RATE    S:N     INT CAPS
FreeBSD                           e8:d1:1b:1b:58:ae    1   54M  -47:-96   100 EP   RSN BSSLOAD HTCAP WPS WME
NetBSD                            d4:b9:2f:35:fe:08    1   54M  -80:-96   100 EP   RSN BSSLOAD HTCAP WPS WME
OpenBSD                           fc:40:09:c6:31:bd   36   54M  -94:-96   100 EPS  VHTPWRENV APCHANREP RSN WPS BSSLOAD HTCAP VHTCAP VHTOPMODE WME
GNU-Linux                         dc:f8:b9:a0:a8:e0   44   54M  -95:-96   100 EP   WPA RSN WPS HTCAP VHTCAP VHTOPMODE WME VHTPWRENV
Windows                           44:48:b9:b3:c3:ff   44   54M  -84:-96   100 EP   BSSLOAD VHTPWRENV HTCAP WME RSN VHTCAP VHTOPMODE WPS
MacOS                             46:48:b9:b3:c3:ff   44   54M  -84:-96   100 EP   BSSLOAD VHTPWRENV HTCAP WME RSN VHTCAP VHTOPMODE WPS
  1. SSID/MESH ID identifies the name of the network.

  2. BSSID identifies the MAC address of the access point.

  3. CAPS field identifies the type of each network and the capabilities of the stations operating there (see the definition of list scan in ifconfig(8) for more details).

7.4.4. Connection and Authentication to a Wireless Network

Once a wireless network has been selected from the list of scanned networks, it is necessary to perform the connection and the authentication. In the vast majority of wireless networks, authentication is done with a password configured in the router. 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. Authenticate with WPA2/WPA/Personal

The authentication process in a wireless network is managed by wpa_supplicant(8).

The wpa_supplicant(8) configuration will be made in the /etc/wpa_supplicant.conf file. For more information, see wpa_supplicant.conf(5).

Once the scanning of the wireless networks has been carried out, a network has been chosen and have the password (PSK), that information will be added to the file /etc/wpa_supplicant.conf as in the following example:

        scan_ssid=1 (1)
        ssid="FreeBSD" (2)
        psk="12345678" (3)
1SSID scan technique. Only need to use this option if the network is hidden.
2Network name.
3Passwork of the wireless network.

The next step will be to configure the wireless connection in the file /etc/rc.conf.

To use a static address it will be necessary to execute the following command:

# sysrc ifconfig_wlan0="inet netmask"

To use a dynamic address it will be necessary to execute the following command:

# ifconfig_wlan0="WPA DHCP"

Then restart the network executing the following command:

# service netif restart

More information on how to perform more advanced methods of authentication can be obtained at Wireless Advanced Authentication. Authenticate with Open Networks

It is important that the user is very careful when connecting to open networks without any kind of authentication.

Once the wireless network scan is done and the SSID of the wireless network is selected, execute the following command:

# ifconfig wlan0 ssid SSID

And then execute dhclient(8) to get the address configured:

# dhclient wlan0

7.4.5. 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 Link Aggregation and Failover and an example for using both wired and wireless connections is provided at Failover Mode Between Ethernet and Wireless Interfaces.

7.5. Hostname

The hostname represents the fully qualified domain name (FQDN) of the host on the network.

If no hostname has been set for the host FreeBSD will assign the value Amnesiac.

7.5.1. Check The Current Hostname

hostname(1) can be used to check the current hostname:

$ hostname

The output should be similar to the following:

7.5.2. Change Hostname

To change the hostname of the host and persist it across reboots execute the following command:

# sysrc hostname=""

7.6. DNS

The DNS could be understanded as a telephone directory in which an IP is identified to a hostname and vice versa.

There are three files that handle how a FreeBSD system interact with the DNS. These three files are hosts(5), resolv.conf(5) and nsswitch.conf(5)

Unless otherwise stated in the /etc/nsswitch.conf file, FreeBSD will look at the addresses in the /etc/hosts file and then the DNS information in the /etc/resolv.conf file.

The nsswitch.conf(5) file specifies how the nsdispatch (name-service switch dispatcher) should operate.

By default, the hosts section of the /etc/nsswitch.conf file will be as follows:

hosts: files dns

For example, in case of using the nscd(8) service. The order of preference could be changed by leaving the line as follows:

hosts: files cache dns

7.6.1. Local addresses

The /etc/hosts file is a simple text database who 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 DNS server. Additionally, /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.

For example, in the case of having a local instance of www/gitlab-ce in a local environment, it could be added as follows to the file /etc/hosts: git

7.6.2. Configuring the Nameserver

How a FreeBSD system accesses the Internet Domain Name System (DNS) is controlled by resolv.conf(5).

The most common entries to /etc/resolv.conf are:


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 list for hostname lookup. This is normally determined by the domain of the local hostname.


The local domain name.

A typical /etc/resolv.conf looks like this:


Only one of the search and domain options should be used.

When using DHCP, dhclient(8) usually rewrites /etc/resolv.conf with information received from the DHCP server.

If the machine in which the configuration is being made is not a DNS server, local-unbound(8) can be used to improve DNS lookup performance.

To enable it at boot time execute the following command:

# sysrc local_unbound_enable="YES"

To start the local-unbound(8) service execute the following command:

# service local_unbound start

7.7. 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?

  • Is the router working correctly?

Before sending a bug report, always check the Hardware Notes in the FreeBSD release page, update the version of FreeBSD to the latest STABLE version, check the mailing list archives, and search the Internet.

7.7.1. Troubleshooting in Wired Networks

If the card works, yet performance is poor, read through tuning(7). Also, check the network configuration as incorrect network settings can cause slow connections.

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 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 ping(8). Refer to Firewalls for more information.

7.7.2. Troubleshooting in Wireless Networks

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 WPA2 or WPA, configure the access point for open authentication and no security to see if traffic will pass.

  • Once the system can associate with the access point, diagnose the network configuration using tools like ping(8).

  • There are many lower-level debugging tools. Debugging messages can be enabled in the 802.11 protocol support layer using wlandebug(8).

Part II: Common Tasks

Now that the basics have been covered, this part of the book discusses some frequently used features of FreeBSD. These chapters:

  • Introduce popular and useful desktop applications: browsers, productivity tools, document viewers, and more.

  • Introduce a number of multimedia tools available for FreeBSD.

  • Explain the process of building a customized FreeBSD kernel to enable extra functionality.

  • Describe the print system in detail, both for desktop and network-connected printer setups.

  • Show how to run Linux applications on the FreeBSD system.

Some of these chapters recommend prior reading, and this is noted in the synopsis at the beginning of each chapter.

Chapter 8. Desktop Environments

8.1. Synopsis

While FreeBSD is popular as a server for its performance and stability, it is also well suited for day-to-day use as a desktop. With over 36000 applications available in the FreeBSD ports tree, it is straightforward to build a customized desktop that can run a wide variety of desktop applications. This chapter demonstrates how to install popular desktop environments as well as desktop applications such as web browsers, productivity software, document viewers, and financial software.


  • Readers of this chapter should already understand how to install either the X Window System or Wayland on FreeBSD.

  • Readers are instructed throughout this chapter to install official packages. Refer to the section on using the ports collection to build customized packages from ports.

8.2. Desktop Environments

This section describes how to install and configure some popular desktop environments on a FreeBSD system. A desktop environment can range from a simple window manager to a complete suite of desktop applications.

Table 10. Supported desktop environments

KDE Plasma

GPL 2.0 or later



GPL 2.0 or later






GPL 2.0, LGPL 2.0



GPL 2.0 or later





8.2.1. KDE Plasma

KDE Plasma is an easy-to-use desktop environment. This desktop provides a suite of applications with a consistent look and feel, a standardized menu and toolbars, keybindings, color-schemes, internationalization, and a centralized, dialog-driven desktop configuration. More information on KDE can be found at the KDE homepage. For FreeBSD-specific information, consult the FreeBSD homepage at KDE. Install KDE Plasma meta package

To install the KDE Plasma meta package with KDE Frameworks, Plasma Desktop and Applications execute:

# pkg install kde5 Minimal KDE Plasma installation

To install a minimal KDE Plasma execute:

# pkg install plasma5-plasma

This installation is really minimal. Konsole must be installed separately executing:

# pkg install konsole Configure KDE Plasma

KDE Plasma uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of KDE Plasma.

Enable D-BUS service in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES"

To increase messages size execute:

sysctl Start KDE Plasma

The preferred KDE Plasma display manager is x11/sddm. To install x11/sddm, execute:

# pkg install sddm

Enable SDDM service in /etc/rc.conf to start at system boot:

# sysrc sddm_enable="YES"

The keyboard language can be set in SDDM by running the following command (for Spanish, for example):

# sysrc sddm_lang="es_ES"

A second method to start KDE Plasma is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo "exec ck-launch-session startplasma-x11" > ~/.xinitrc

8.2.2. GNOME

GNOME is a user-friendly desktop environment. It includes a panel for starting applications and displaying status, a desktop, a set of tools and applications, and a set of conventions that make it easy for applications to cooperate and be consistent with each other. Install GNOME meta package

To install the GNOME meta package with GNOME Desktop and Applications, execute:

# pkg install gnome Minimal GNOME installation

To install the GNOME-lite meta package with a GNOME desktop slimmed down for only the basics, execute:

# pkg install gnome-lite Configure GNOME

GNOME requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

# Device                Mountpoint      FStype  Options         Dump    Pass#
proc                    /proc           procfs  rw              0       0

GNOME uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of GNOME.

Enable D-BUS service in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES" Start GNOME

GNOME Display Manager is the preferred display manager for GNOME. GDM is installed as part of the GNOME package.

Enable GDM in /etc/rc.conf to start at system boot:

# sysrc gdm_enable="YES"

A second method to start GNOME is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo "exec gnome-session" > ~/.xinitrc

8.2.3. XFCE

XFCE is a desktop environment based on the GTK+, lightweight and provides a simple, efficient, easy-to-use desktop. It is fully configurable, has a main panel with menus, applets, and application launchers, provides a file manager and sound manager, and is themeable. Since it is fast, light, and efficient, it is ideal for older or slower machines with memory limitations. Install XFCE

To install the XFCE meta package, execute:

# pkg install xfce Configure XFCE

XFCE requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

# Device                Mountpoint      FStype  Options         Dump    Pass#
proc                    /proc           procfs  rw              0       0

XFCE uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of XFCE.

Enable D-BUS in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES" Start XFCE

x11/lightdm is a display manager that supports different display technologies and is a good choice as it is very lightweight, requires little memory usage, and has fast performance.

To install it, execute:

# pkg install lightdm lightdm-gtk-greeter

Enable lightdm in /etc/rc.conf to start at system boot:

# sysrc lightdm_enable="YES"

A second method to start XFCE is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo '. /usr/local/etc/xdg/xfce4/xinitrc' > ~/.xinitrc

8.2.4. MATE

The MATE Desktop Environment is the continuation of GNOME 2. It provides an intuitive and attractive desktop environment using traditional metaphors. Install MATE meta package

To install the MATE meta package that includes the MATE Desktop with some extra applications such as text editor, archiver manager, etc., execute:

# pkg install mate Minimal MATE installation

To install the MATE lite meta package with MATE desktop slimmed down for only the basics, execute:

# pkg install mate-base Configure MATE

MATE requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

# Device                Mountpoint      FStype  Options         Dump    Pass#
proc                    /proc           procfs  rw              0       0

MATE uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of MATE. Enable D-BUS in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES" Start MATE

x11/lightdm is a display manager that supports different display technologies and is a good choice as it is very lightweight, requires little memory usage, and has fast performance.

To install it, execute:

# pkg install lightdm lightdm-gtk-greeter

Enable lightdm in /etc/rc.conf to start at system boot:

# sysrc lightdm_enable="YES"

A second method to start MATE is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo "exec ck-launch-session mate-session" > ~/.xinitrc

8.2.5. Cinnamon

Cinnamon is a UNIX® desktop which provides advanced innovative features and a traditional user experience. The desktop layout is similar to Gnome 2. The underlying technology is forked from Gnome Shell. The emphasis is put on making users feel at home and providing them with an easy to use and comfortable desktop experience. Install Cinnamon

To install the Cinnamon package, execute:

# pkg install cinnamon Configure Cinnamon

Cinnamon requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

# Device                Mountpoint      FStype  Options         Dump    Pass#
proc                    /proc           procfs  rw              0       0

Cinnamon uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of Cinnamon. Enable D-BUS in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES" Start Cinnamon

x11/lightdm is a display manager that supports different display technologies and is a good choice as it is very lightweight, requires little memory usage, and has fast performance.

To install it execute:

# pkg install lightdm lightdm-gtk-greeter

Enable lightdm in /etc/rc.conf to start at system boot:

# sysrc lightdm_enable="YES"

A second method to start Cinnamon is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo "exec ck-launch-session cinnamon-session" > ~/.xinitrc

8.2.6. LXQT

LXQt is an advanced, easy-to-use, and fast desktop environment based on Qt technologies. It has been tailored for users who value simplicity, speed, and an intuitive interface. Unlike most desktop environments, LXQt also works fine with less powerful machines. Install LXQT

To install the LXQT meta package, execute:

# pkg install lxqt Configure LXQT

LXQT requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

# Device                Mountpoint      FStype  Options         Dump    Pass#
proc                    /proc           procfs  rw              0       0

LXQT uses dbus-daemon(1) for a message bus and hardware abstraction. This application is automatically installed as a dependency of LXQT.

Enable D-BUS in /etc/rc.conf to start at system boot:

# sysrc dbus_enable="YES" Start LXQT

The preferred LXQT display manager is x11/sddm. To install x11/sddm, execute:

# pkg install sddm

Enable SDDM service in /etc/rc.conf to start at system boot:

# sysrc sddm_enable="YES"

The keyboard language can be set in SDDM by running the following command (for example, for Spanish):

# sysrc sddm_lang="es_ES"

A second method to start LXQT is by manually invoking startx(1). For this to work, the following line is needed in ~/.xinitrc:

% echo "exec ck-launch-session startlxqt" > ~/.xinitrc

8.3. Browsers

This section describes how to install and configure some popular web browsers on a FreeBSD system, from full web browsers with high resource consumption to command line web browsers with reduced resource usage.

Table 11. Supported browsers
NameLicensePackageResources Needed


MPL 2.0




BSD-3 and others



Iridium browser

BSD-3 and others




MPL 2.0




GPL 2.0 or later



Gnome Web (Epiphany)

GPL 3.0 or later




GPL 3.0 or later




GPL 3.0 or later




GPL 2.0 or later







8.3.1. Firefox

Firefox is an open source browser that features a standards-compliant HTML display engine, tabbed browsing, popup blocking, extensions, improved security, and more. Firefox is based on the Mozilla codebase.

To install the package of the latest release version of Firefox, execute:

# pkg install firefox

To instead install Firefox Extended Support Release (ESR) version, execute:

# pkg install firefox-esr

8.3.2. Chromium

Chromium is an open source browser project that aims to build a safer, faster, and more stable web browsing experience. Chromium features tabbed browsing, popup blocking, extensions, and much more. Chromium is the open source project upon which the Google Chrome web browser is based.

To install Chromium, execute:

# pkg install chromium

The executable for Chromium is /usr/local/bin/chrome, not /usr/local/bin/chromium.

8.3.3. Iridium browser

Iridium is a free, open, and libre browser modification of the Chromium code base, with privacy being enhanced in several key areas. Automatic transmission of partial queries, keywords, metrics to central services is inhibited and only occurs with consent.

To install Iridium, execute:

# pkg install iridium-browser

8.3.4. Falkon

Falkon is a new-ish and very fast QtWebEngine browser. It aims to be a lightweight web browser available on all major platforms. Falkon has all standard functions you expect from a web browser. It includes bookmarks, history (both also in sidebar) and tabs. Beyond that, you block ads with a builtin AdBlock plugin, block Flash content with Click2Flash and edit the local CA Certificates database with an SSL Manager.

To install Falkon, execute:

# pkg install falkon

8.3.5. Konqueror

Konqueror is more than a web browser as it is also a file manager and a multimedia viewer. It supports WebKit, a rendering engine used by many modern browsers including Chromium, as well as its own KHTML engine.

To install Konqueror, execute:

# pkg install konqueror

8.3.6. Gnome Web (Epiphany)

Gnome Web (Epiphany) is a web browser designed to be as lightweight and fast as possible, at the expense of many of the features found in other browsers.

To install Gnome Web (Epiphany), execute:

# pkg install epiphany

8.3.7. qutebrowser

Qutebrowser is a keyboard-focused browser with a minimal GUI. It is based on Python and PyQt5 and free software, licensed under the GPL.

To install qutebrowser, execute:

# pkg install qutebrowser

8.3.8. Dillo

Dillo aims to be a multiplatform alternative browser that is small, stable, developer-friendly, usable, fast, and extensible. This new, experimental version of Dillo is based upon FLTK toolkit, rather than GTK1, and has been substantially rewritten.

To install Dillo, execute:

# pkg install dillo

A lynx-like WWW browser with text and graphics modes with many features like displaying tables, menus, etc.

To install Links, execute:

# pkg install links

8.3.10. w3m

w3m is a pager/text-based web browser. It is a similar application to Lynx, but it has several features Lynx doesn’t have like rendering tables and rendering frames.

To install w3m, execute:

# pkg install w3m

8.4. Development tools

This section describes how to install and configure some popular development tools on a FreeBSD system.

Table 12. Supported development tools
NameLicensePackageResources Needed

Visual Studio Code




Qt Creator





GPL 2.0 or later and LGPL 2.0 or later



Eclipse IDE









Apache 2.0



GNU Emacs

GPL 3.0 or later



8.4.1. Visual Studio Code

Visual Studio Code is a type of tool that combines the simplicity of a code editor with what developers need for their core edit-build-debug cycle. It provides comprehensive editing and debugging support, an extensibility model, and lightweight integration with existing tools.

To install Visual Studio Code, execute:

# pkg install vscode

8.4.2. Qt Creator

Qt Creator is a cross-platform IDE (integrated development environment) tailored to the needs of Qt developers. Functionalities included with Qt Creator are:

  • code editor with C++, QML and ECMAscript support;

  • rapid code navigation tools;

  • static code checking and style hints as you type;

  • context sensitive help;

  • visual debugger;

  • integrated GUI layout and forms designer.

To install Qt Creator, execute:

# pkg install qtcreator

8.4.3. kdevelop

Open source, feature-full, plugin extensible IDE for C/C++ and other programming languages. It is based on KDevPlatform and the KDE and Qt libraries, and it has been under development since 1998.

To install kdevelop, execute:

# pkg install kdevelop

8.4.4. Eclipse IDE

The Eclipse Platform is an open extensible IDE for anything and yet nothing in particular. The Eclipse Platform provides building blocks and a foundation for constructing and running integrated software-development tools. The Eclipse Platform allows tool builders to independently develop tools that integrate with other people’s tools.

To install Eclipse IDE, execute:

# pkg install eclipse

8.4.5. Vim

Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems.

Vim is often called a "programmer’s editor," and so useful for programming that many consider it an entire IDE. It’s not just for programmers, though. Vim is perfect for all kinds of text editing, from composing email to editing configuration files.

To install Vim, execute:

# pkg install vim

8.4.6. Neovim

Neovim is an aggressive refactor of editors/vim. It represents a complete overhaul of the codebase with many sanity improvements, including sensible defaults, a built-in terminal emulator, asynchronous plugin architecture, and powerful APIs designed for speed and extensibility. It retains full compatibility with almost all Vim plugins and scripts.

To install Neovim, execute:

# pkg install neovim

8.4.7. GNU Emacs

GNU Emacs is an extensible, customizable, free/libre text editor. At its core is an interpreter for Emacs Lisp, a dialect of the Lisp programming language with extensions to support text editing.

To install GNU Emacs, execute:

# pkg install emacs

8.5. Desktop office productivity

When it comes to productivity, users often look for an office suite or an easy-to-use word processor. While some desktop environments like KDE Plasma provide an office suite, there is no default productivity package. Several office suites and graphical word processors are available for FreeBSD, regardless of the installed desktop environments.

This section demonstrates how to install the following popular productivity software and indicates if the application is resource-heavy, takes time to compile from ports, or has any major dependencies.

Table 13. Supported Desktop office productivity suites
NameLicensePackageResources Needed


MPL 2.0



Calligra Suite





GPL 2.0 or later



8.5.1. LibreOffice

LibreOffice is a free software office suite developed by The Document Foundation. It is compatible with other major office suites and available on a variety of platforms. It is a rebranded fork of Apache OpenOffice and includes applications found in a complete office productivity suite: a word processor, spreadsheet, presentation manager, drawing program, database management program, and a tool for creating and editing mathematical formulæ. It is available in a number of different languages and internationalization has been extended to interfaces, spell checkers, and dictionaries. More information about LibreOffice can be found at

To install LibreOffice, execute:

# pkg install libreoffice

The LibreOffice package comes by default only in English. To have a localized version of LibreOffice it is necessary to install a language pack. For example, for the version localized in Spanish, it is necessary to install the package editors/libreoffice-es with the command:

# pkg install libreoffice-es

8.5.2. Calligra

The KDE Plasma desktop environment includes an office suite which can be installed separately from KDE Plasma. Calligra includes standard components that can be found in other office suites. Words is the word processor, Sheets is the spreadsheet program, Stage manages slide presentations, and Karbon is used to draw graphical documents.

To install Calligra, execute:

# pkg install calligra

8.5.3. AbiWord

AbiWord is a free word processing program similar in look and feel to Microsoft® Word. It is fast, contains many features, and is user-friendly.

AbiWord can import or export many file formats, including some proprietary ones like Microsoft® .rtf.

To install AbiWord, execute:

# pkg install abiword

8.6. Document Viewers

Some new document formats have gained popularity since the advent of UNIX® and the viewers they require may not be available in the base system. This section demonstrates how to install the following document viewers:

Table 14. Supported Document Viewers
NameLicensePackageResources Needed


GPL 2.0




GPL 2.0




GPL 2.0




GPL 2.0



8.6.1. Okular

Okular is a universal document viewer, part of the KDE Plasma project.

Okular combines excellent functionality with the versatility of supporting different kind of documents, like PDF, Postscript, DjVu, CHM, XPS, ePub and others.

To install Okular, execute:

# pkg install okular

8.6.2. Evince

Evince is a document viewer for multiple document formats including PDF and Postscript. Part of the GNOME project. The goal of evince is to replace document viewers such as ggv and gpdf with a single, simple application.

To install Evince, execute:

# pkg install evince

8.6.3. ePDFView

ePDFView is a lightweight PDF document viewer that only uses the Gtk+ and Poppler libraries. The aim of ePDFView is to make a simple PDF document viewer, similar to Evince but without using the GNOME libraries.

To install ePDFView, execute:

# pkg install epdfview

8.6.4. Xpdf

For users that prefer a small FreeBSD PDF viewer, Xpdf provides a light-weight and efficient viewer which requires few resources. It uses the standard X fonts and does not require any additional toolkits.

To install Xpdf, execute:

# pkg install xpdf

8.7. Finance

For managing personal finances on a FreeBSD desktop, some powerful and easy-to-use applications can be installed. Some are compatible with widespread file formats, such as the formats used by Quicken and Excel.

This section covers these programs:

Table 15. Supported Finance programs
NameLicensePackageResources Needed


GPL 2.0




GPL 2.0 and GPL 3.0



8.7.1. KMyMoney

KMyMoney is a personal finance application created by the KDE community. KMyMoney aims to provide the important features found in commercial personal finance manager applications. It also highlights ease-of-use and proper double-entry accounting among its features. KMyMoney imports from standard Quicken QIF files, tracks investments, handles multiple currencies, and provides a wealth of reports.

To install KMyMoney, execute:

# pkg install kmymoney

8.7.2. GnuCash

GnuCash is part of the GNOME effort to provide user-friendly, yet powerful, applications to end-users. GnuCash can be used to keep track of income and expenses, bank accounts, and stocks. It features an intuitive interface while remaining professional.

GnuCash provides a smart register, a hierarchical system of accounts, and many keyboard accelerators and auto-completion methods. It can split a single transaction into several more detailed pieces. GnuCash can import and merge Quicken QIF files. It also handles most international date and currency formats.

To install GnuCash, execute:

# pkg install gnucash

Chapter 9. Multimedia

9.1. Synopsis

The multimedia chapter provides an overview of multimedia support on FreeBSD. Multimedia applications and technologies have become an integral part of modern computing, and FreeBSD provides robust and reliable support for a wide range of multimedia hardware and software. This chapter covers various multimedia components such as audio, video, and image processing. It also discusses various media formats and codecs, as well as tools and applications for multimedia creation and playback. Additionally, the chapter covers multimedia system configuration, troubleshooting, and optimization. Whether you are a multimedia enthusiast or a professional content creator, FreeBSD offers a robust platform for multimedia work. This chapter aims to help get the most out of FreeBSD’s multimedia capabilities, providing useful information and practical examples to help get started.

9.2. Setting Up the Sound Card

By default, FreeBSD will automatically detect the sound card used by the system. FreeBSD supports a wide variety of sound cards. The list of supported sound cards can be consulted in sound(4).

It is only necessary to load the sound card module if FreeBSD has not detected it correctly.

Where it is not known which sound card the system has, or which module to use, the snd_driver metadriver can be loaded by executing the following command:

# kldload snd_driver

Alternatively, to load the driver as a module at boot time, place the following line in /boot/loader.conf:


9.2.1. Testing Sound

To confirm the sound card is detected the following command can be executed:

% dmesg | grep pcm

The output should be similar to the following:

pcm0: <Conexant CX20561 (Hermosa) (Analog 2.0+HP/2.0)> at nid 26,22 and 24 on hdaa0
pcm1: <Conexant CX20561 (Hermosa) (Internal Analog Mic)> at nid 29 on hdaa0

The status of the sound card may also be checked using this command:

# cat /dev/sndstat

The output should be similar to the following:

Installed devices:
pcm0: <Conexant CX20561 (Hermosa) (Analog 2.0+HP/2.0)> (play/rec) default
pcm1: <Conexant CX20561 (Hermosa) (Internal Analog Mic)> (rec)

If no pcm devices are listed, double-check that the correct device driver was loaded. If all goes well, the sound card should now work in FreeBSD.

beep(1) can be used to produce some noise, confirming that the sound card is working:

% beep

9.2.2. Mixer

FreeBSD has different utilities to set and display sound card mixer values built on the FreeBSD Sound System:

Table 16. Supported mixer packages



Included in base system






KDE Plasma audio widget

GPL 2.0







9.2.3. Graphics Card Sound

Graphics cards often come with their own integrated sound devices, and it may be unclear which is being used as the default device. To confirm, run dmesg and look for the pcm entries to identify how the system is enumerating the outputs. Execute the following command:

% dmesg | grep pcm

The output looks something like this:

pcm0: <HDA NVIDIA (Unknown) PCM #0 DisplayPort> at cad 0 nid 1 on hdac0
pcm1: <HDA NVIDIA (Unknown) PCM #0 DisplayPort> at cad 1 nid 1 on hdac0
pcm2: <HDA NVIDIA (Unknown) PCM #0 DisplayPort> at cad 2 nid 1 on hdac0
pcm3: <HDA NVIDIA (Unknown) PCM #0 DisplayPort> at cad 3 nid 1 on hdac0
hdac1: HDA Codec #2: Realtek ALC889
pcm4: <HDA Realtek ALC889 PCM #0 Analog> at cad 2 nid 1 on hdac1
pcm5: <HDA Realtek ALC889 PCM #1 Analog> at cad 2 nid 1 on hdac1
pcm6: <HDA Realtek ALC889 PCM #2 Digital> at cad 2 nid 1 on hdac1
pcm7: <HDA Realtek ALC889 PCM #3 Digital> at cad 2 nid 1 on hdac1

The graphics card (NVIDIA®) has been enumerated before the sound card (Realtek®), with the sound card appearing as pcm4. The system can be configured to use the sound card as the default device by executing the following command:

# sysctl hw.snd.default_unit=4

To make this change permanent add the next line to /etc/sysctl.conf:


9.2.4. Automatically Switching to Headphones

Some systems may struggle with switching between audio outputs, but fortunately FreeBSD allows automatic switchover to be configured in device.hints.

Identify how the system is enumerating the audio outputs by executing the following command:

% dmesg | grep pcm

The output looks something like this:

pcm0: <Realtek ALC892 Analog> at nid 23 and 26 on hdaa0
pcm1: <Realtek ALC892 Right Analog Headphones> at nid 22 on hdaa0

Add the following lines to /boot/device.hints:

hint.hdac.0.cad0.nid22.config="as=1 seq=15 device=Headphones"
hint.hdac.0.cad0.nid26.config="as=2 seq=0 device=speakers"

Keep in mind that these values are for the example indicated above. They may vary depending on the system.

9.2.5. Troubleshooting Sound

Some common error messages and their solutions:

Table 17. Common Error Messages

xxx: can’t open /dev/dsp!

Type fstat | grep dsp to check if another application is holding the device open. Noteworthy troublemakers are esound and KDE’s sound support.

Programs using audio/pulseaudio might need to restart the audio/pulseaudio daemon for the changes in hw.snd.default_unit to take effect. Alternatively, audio/pulseaudio settings can be changed on the fly. pacmd(1) opens a command line connection to the audio/pulseaudio daemon:

# pacmd
Welcome to PulseAudio 14.2! Use "help" for usage information.

The following command changes the default sink to card number 4 as in the previous example:

set-default-sink 4

Do not use the exit command to exit the command line interface. That will kill the audio/pulseaudio daemon. Use Ctrl+D instead.

9.3. Audio players

This section introduces some of the software available from the FreeBSD Ports Collection which can be used for audio playback.

Table 18. Audio players packages


LGPL 3.0




GPL 2.0







MOC (music on console)

GPL 2.0



9.3.1. Elisa

Elisa is a music player developed by the KDE community that strives to be simple and nice to use.

To install Elisa, execute:

# pkg install elisa

9.3.2. GNOME Music

GNOME Music is the new GNOME music playing application. It aims to combine an elegant and immersive browsing experience with simple and straightforward controls.

To install GNOME Music, execute:

# pkg install gnome-music

9.3.3. Audacious

Audacious is an open source audio player. A descendant of XMMS, it plays your music how you want it, without stealing away your computer’s resources from other tasks.

To install Audacious, execute:

# pkg install audacious-qt6 audacious-plugins-qt6

Audacious supports OSS natively, but must be configured in the settings on the Audio tab.

9.3.4. MOC (music on console)

MOC (music on console) is a console audio player designed to be powerful and easy to use.

MOC plays smoothly, regardless of system or I/O load, because it handles the output buffer in a separate thread. It does not cause gaps between files, because the next file to be played is pre-cached while playing the current file.

To install MOC (music on console), execute:

# pkg install moc

9.4. Video players

This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback.

Table 19. Video players packages


GPL 2.0




GPL 2.0



VLC media player

GPL 2.0



Kodi (XBMC)

GPL 2.0



9.4.1. MPlayer

MPlayer is a multimedia player and encoder suite which runs on many platforms and works on the command line. It plays a terrific number of different file formats and codecs including popular DivX, XviD, H.264 streams as well as DVD and SVCDs along with many popular audio codecs.

To install MPlayer, execute:

# pkg install mplayer

For examples of how MPlayer works see mplayer(1).

9.4.2. SMPlayer

SMPlayer intends to be a complete front-end for MPlayer, from basic features like playing videos, DVDs, and VCDs to more advanced features like support for MPlayer filters and more.

To install SMPlayer, execute:

# pkg install smplayer

9.4.3. VLC media player

VLC media player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, mp3, ogg, and more) as well as DVD’s, VCD’s, and various streaming protocols. It can also be used as a server to stream in unicast or multicast in IPv4 or IPv6 on a high-bandwidth network. VLC also has the ability to transcode media on-the-fly for streaming or saving to disk.

To install VLC, execute:

# pkg install vlc

9.4.4. Kodi (XBMC)

Kodi (formerly known as XBMC) is a free and open source cross-platform media-player and entertainment hub. It allows users to play and view most videos, music, podcasts, and other digital media files from local and network storage media and the internet.

To install Kodi, execute:

# pkg install kodi

9.5. Conferencing and Meetings

A FreeBSD desktop environment can be used to join video conferences. This section will explain how to configure the webcam and which videoconferencing applications are supported on FreeBSD.

9.5.1. Setting Up the Webcam

To allow FreeBSD access to the webcam and perform its configuration it is necessary to install certain utilities:

  • multimedia/webcamd is a daemon that enables the use of hundreds of different USB based webcam and DVB USB devices.

  • multimedia/pwcview is an application that can be used to view the video stream of the webcam.

To install the required utilities, execute:

# pkg install webcamd pwcview

Enable the webcamd(8) service in /etc/rc.conf to start it at system boot:

# sysrc webcamd_enable="YES"

The user must belong to the webcamd group. To add the user to webcamd group execute the following command:

# pw groupmod webcamd -m username

Since multimedia/webcamd needs the cuse(3) module this module must be loaded by executing the following command:

# kldload cuse

To load cuse(3) at system boot, execute the command:

# sysrc kld_list += "cuse"

Once the utilities have been installed the list of available webcams can be shown with webcamd(8):

# webcamd -l

The output should be similar to the following:

webcamd [-d ugen0.2] -N SunplusIT-Inc-HP-TrueVision-HD-Camera -S unknown -M 0 (1)
webcamd [-d ugen1.3] -N Realtek-802-11n-WLAN-Adapter -S 00e04c000001 -M 0
1Available webcam

Configure the available webcam executing the following command:

# sysrc webcamd_0_flags="-d ugen0.2" (1)

Note here that if this is a plug-and-play USB webcam, changing the USB port to which it is connected will change the output from webcamd -l, and the entry in rc.conf might need to be updated. For laptops that use USB integrated webcams, this should not be an issue.

The webcamd(8) service must be started by executing the following command:

# service webcamd start

The output should be similar to the following:

Starting webcamd.
webcamd 1616 - - Attached to ugen0.2[0]

multimedia/pwcview can be used to check the proper functioning of the webcam. The following command can be used to execute multimedia/pwcview:

% pwcview -f 30 -s vga

Then multimedia/pwcview will display the webcam:

pwcview showing Absolute FreeBSD 3rd edition as an example

9.5.2. Meetings software status

FreeBSD currently supports the following tools used to carry out videoconferences.

Table 20. Meeting software
NameFirefox statusChromium statusWebsite

Microsoft Teams

Does not work


Google Meet

Does not work






Does not work



Does not work


9.6. Image Scanners

In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection.

9.6.1. Checking the Scanner

Before attempting any configuration it is important to check the scanner is supported by SANE.

With the scanner connected, run the following command to get all connected USB devices:

# usbconfig list

The output should be similar to the following:

ugen4.2: <LITE-ON Technology USB NetVista Full Width Keyboard.> at usbus4, cfg=0 md=HOST spd=LOW (1.5Mbps) pwr=ON (70mA)
ugen4.3: <Logitech USB Optical Mouse> at usbus4, cfg=0 md=HOST spd=LOW (1.5Mbps) pwr=ON (100mA)
ugen3.2: <HP Deskjet 1050 J410 series> at usbus3, cfg=0 md=HOST spd=HIGH (480Mbps) pwr=ON (2mA)

Run the following command to obtain the idVendor and the idProduct:

# usbconfig -d 3.2 dump_device_desc

Note here that the scanner is a plug-and-play device, and changing the USB port to which it is connected will change the output from usbconfig list.

The output should be similar to the following:

ugen3.2: <HP Deskjet 1050 J410 series> at usbus3, cfg=0 md=HOST spd=HIGH (480Mbps) pwr=ON (2mA)

bLength = 0x0012
bDescriptorType = 0x0001
bcdUSB = 0x0200
bDeviceClass = 0x0000  <Probed by interface class>
bDeviceSubClass = 0x0000
bDeviceProtocol = 0x0000
bMaxPacketSize0 = 0x0040
idVendor = 0x03f0
idProduct = 0x8911
bcdDevice = 0x0100
iManufacturer = 0x0001  <HP>
iProduct = 0x0002  <Deskjet 1050 J410 series>
bNumConfigurations = 0x0001

Once the idVendor and the idProduct have been obtained, it is necessary to check in the list of supported devices of SANE if the scanner is supported by filtering by the idProduct.

9.6.2. SANE Configuration

SANE provides the access to the scanner via backends. To be able to scan with FreeBSD the graphics/sane-backends package must be installed by running the following command:

# pkg install sane-backends

Some USB scanners require firmware to be loaded. Like the HP scanner used in the example above, which needs the package print/hplip installed.

After installing the necessary packages devd(8) must be configured to allow FreeBSD access to the scanner.

Add the saned.conf file to /usr/local/etc/devd/saned.conf with the following content:

notify 100 {
        match "system" "USB";
        match "subsystem" "INTERFACE";
        match "type" "ATTACH";
        match "cdev" "ugen[0-9].[0-9]";
        match "vendor" "0x03f0"; (1)
        match "product" "0x8911"; (2)
        action "chown -L cups:saned /dev/\$cdev && chmod -L 660 /dev/\$cdev";
1vendor: Is the idVendor obtained previously by running the usbconfig -d 3.2 dump_device_desc command.
2product: Is the idProduct obtained previously by running the usbconfig -d 3.2 dump_device_desc command.

After that devd(8) must be restarted by running the following command:

# service devd restart

The SANE backends include scanimage(1) which can be used to list the devices and perform an image acquisition.

Execute scanimage(1) with -L argument to list the scanner devices:

# scanimage -L

The output should be similar to the following:

device `hpaio:/usb/Deskjet_1050_J410_series?serial=XXXXXXXXXXXXXX' is a Hewlett-Packard Deskjet_1050_J410_series all-in-one

If scanimage(1) is not able to identify the scanner, this message will appear:

No scanners were identified. If you were expecting something different,
check that the scanner is plugged in, turned on and detected by the
sane-find-scanner tool (if appropriate). Please read the documentation
which came with this software (README, FAQ, manpages).

Once scanimage(1) sees the scanner, the configuration is complete and the scanner is now ready to use.

To activate the service and have it run at boot execute the following command:

# sysrc saned_enable="YES"

While scanimage(1) can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning.

Table 21. Graphical scanner programs


GPL 2.0


GNOME Simple Scan

GPL 3.0



GPL 2.0


Chapter 10. Configuring the FreeBSD Kernel

10.1. Synopsis

The kernel is the core of the FreeBSD operating system. It is responsible for managing memory, enforcing security controls, networking, disk access, and much more. While much of FreeBSD is dynamically configurable, it is still occasionally necessary to configure and compile a custom kernel.

After reading this chapter, you will know:

  • When to build a custom kernel.

  • How to take a hardware inventory.

  • How to customize a kernel configuration file.

  • How to use the kernel configuration file to create and build a new kernel.

  • How to install the new kernel.

  • How to troubleshoot if things go wrong.

All of the commands listed in the examples in this chapter should be executed as root.

10.2. Why Build a Custom Kernel?

Traditionally, FreeBSD used a monolithic kernel. The kernel was one large program, supported a fixed list of devices, and in order to change the kernel’s behavior, one had to compile and then reboot into a new kernel.

Today, most of the functionality in the FreeBSD kernel is contained in modules which can be dynamically loaded and unloaded from the kernel as necessary. This allows the running kernel to adapt immediately to new hardware and for new functionality to be brought into the kernel. This is known as a modular kernel.

Occasionally, it is still necessary to perform static kernel configuration. Sometimes the needed functionality is so tied to the kernel that it can not be made dynamically loadable. Some security environments prevent the loading and unloading of kernel modules and require that only needed functionality is statically compiled into the kernel.

Building a custom kernel is often a rite of passage for advanced BSD users. This process, while time consuming, can provide benefits to the FreeBSD system. Unlike the GENERIC kernel, which must support a wide range of hardware, a custom kernel can be stripped down to only provide support for that computer’s hardware. This has a number of benefits, such as:

  • Faster boot time. Since the kernel will only probe the hardware on the system, the time it takes the system to boot can decrease.

  • Lower memory usage. A custom kernel often uses less memory than the GENERIC kernel by omitting unused features and device drivers. This is important because the kernel code remains resident in physical memory at all times, preventing that memory from being used by applications. For this reason, a custom kernel is useful on a system with a small amount of RAM.

  • Additional hardware support. A custom kernel can add support for devices which are not present in the GENERIC kernel.

Before building a custom kernel, consider the reason for doing so. If there is a need for specific hardware support, it may already exist as a module.

Kernel modules exist in /boot/kernel and may be dynamically loaded into the running kernel using kldload(8). Most kernel drivers have a loadable module and manual page. For example, the ath(4) wireless network driver has the following information in its manual page:

Alternatively, to load the driver as a module at boot time, place the
following line in loader.conf(5):


Adding if_ath_load="YES" to /boot/loader.conf will load this module dynamically at boot time.

In some cases, there is no associated module in /boot/kernel. This is mostly true for certain subsystems.

10.3. Finding the System Hardware

Before editing the kernel configuration file, it is recommended to perform an inventory of the machine’s hardware. On a dual-boot system, the inventory can be created from the other operating system. For example, Microsoft®'s Device Manager contains information about installed devices.

Some versions of Microsoft® Windows® have a System icon which can be used to access Device Manager.

If FreeBSD is the only installed operating system, use dmesg(8) to determine the hardware that was found and listed during the boot probe. Most device drivers on FreeBSD have a manual page which lists the hardware supported by that driver. For example, the following lines indicate that the psm(4) driver found a mouse:

psm0: <PS/2 Mouse> irq 12 on atkbdc0
psm0: [ITHREAD]
psm0: model Generic PS/2 mouse, device ID 0

Since this hardware exists, this driver should not be removed from a custom kernel configuration file.

If the output of dmesg does not display the results of the boot probe output, instead read the contents of /var/run/dmesg.boot.

Another tool for finding hardware is pciconf(8), which provides more verbose output. For example:

% pciconf -lv
ath0@pci0:3:0:0:        class=0x020000 card=0x058a1014 chip=0x1014168c rev=0x01 hdr=0x00
    vendor     = 'Atheros Communications Inc.'
    device     = 'AR5212 Atheros AR5212 802.11abg wireless'
    class      = network
    subclass   = ethernet

This output shows that the ath driver located a wireless Ethernet device.

The -k flag of man(1) can be used to provide useful information. For example, it can be used to display a list of manual pages which contain a particular device brand or name:

# man -k Atheros
ath(4)                   - Atheros IEEE 802.11 wireless network driver
ath_hal(4)               - Atheros Hardware Access Layer (HAL)

Once the hardware inventory list is created, refer to it to ensure that drivers for installed hardware are not removed as the custom kernel configuration is edited.

10.4. The Configuration File

In order to create a custom kernel configuration file and build a custom kernel, the full FreeBSD source tree must first be installed.

If /usr/src/ does not exist or it is empty, source has not been installed. Source can be installed with Git using the instructions in “Using Git”.

Once source is installed, review the contents of /usr/src/sys. This directory contains a number of subdirectories, including those which represent the following supported architectures: amd64, i386, powerpc, and sparc64. Everything inside a particular architecture’s directory deals with that architecture only and the rest of the code is machine independent code common to all platforms. Each supported architecture has a conf subdirectory which contains the GENERIC kernel configuration file for that architecture.

Do not make edits to GENERIC. Instead, copy the file to a different name and make edits to the copy. The convention is to use a name with all capital letters. When maintaining multiple FreeBSD machines with different hardware, it is a good idea to name it after the machine’s hostname. This example creates a copy, named MYKERNEL, of the GENERIC configuration file for the amd64 architecture:

# cd /usr/src/sys/amd64/conf

MYKERNEL can now be customized with any ASCII text editor. The default editor is vi, though an easier editor for beginners, called ee, is also installed with FreeBSD.

The format of the kernel configuration file is simple. Each line contains a keyword that represents a device or subsystem, an argument, and a brief description. Any text after a # is considered a comment and ignored. To remove kernel support for a device or subsystem, put a # at the beginning of the line representing that device or subsystem. Do not add or remove a # for any line that you do not understand.

It is easy to remove support for a device or option and end up with a broken kernel. For example, if the ata(4) driver is removed from the kernel configuration file, a system using ATA disk drivers may not boot. When in doubt, just leave support in the kernel.

In addition to the brief descriptions provided in this file, additional descriptions are contained in NOTES, which can be found in the same directory as GENERIC for that architecture. For architecture independent options, refer to /usr/src/sys/conf/NOTES.

When finished customizing the kernel configuration file, save a backup copy to a location outside of /usr/src.

Alternately, keep the kernel configuration file elsewhere and create a symbolic link to the file:

# cd /usr/src/sys/amd64/conf
# mkdir /root/kernels
# cp GENERIC /root/kernels/MYKERNEL
# ln -s /root/kernels/MYKERNEL

An include directive is available for use in configuration files. This allows another configuration file to be included in the current one, making it easy to maintain small changes relative to an existing file. If only a small number of additional options or drivers are required, this allows a delta to be maintained with respect to GENERIC, as seen in this example:

include GENERIC

options         IPFIREWALL
options         DUMMYNET
options         IPDIVERT

Using this method, the local configuration file expresses local differences from a GENERIC kernel. As upgrades are performed, new features added to GENERIC will also be added to the local kernel unless they are specifically prevented using nooptions or nodevice. A comprehensive list of configuration directives and their descriptions may be found in config(5).

To build a file which contains all available options, run the following command as root:

# cd /usr/src/sys/arch/conf && make LINT

10.5. Building and Installing a Custom Kernel

Once the edits to the custom configuration file have been saved, the source code for the kernel can be compiled using the following steps:

Procedure: Building a Kernel

  1. Change to this directory:

    # cd /usr/src
  2. Compile the new kernel by specifying the name of the custom kernel configuration file:

    # make buildkernel KERNCONF=MYKERNEL
  3. Install the new kernel associated with the specified kernel configuration file. This command will copy the new kernel to /boot/kernel/kernel and save the old kernel to /boot/kernel.old/kernel:

    # make installkernel KERNCONF=MYKERNEL
  4. Shutdown the system and reboot into the new kernel. If something goes wrong, refer to The kernel does not boot.

By default, when a custom kernel is compiled, all kernel modules are rebuilt. To update a kernel faster or to build only custom modules, edit /etc/make.conf before starting to build the kernel.

For example, this variable specifies the list of modules to build instead of using the default of building all modules:


Alternately, this variable lists which modules to exclude from the build process:

WITHOUT_MODULES = linux acpi sound

Additional variables are available. Refer to make.conf(5) for details.

10.6. If Something Goes Wrong

There are four categories of trouble that can occur when building a custom kernel:

config fails

If config fails, it will print the line number that is incorrect. As an example, for the following message, make sure that line 17 is typed correctly by comparing it to GENERIC or NOTES:

config: line 17: syntax error
make fails

If make fails, it is usually due to an error in the kernel configuration file which is not severe enough for config to catch. Review the configuration, and if the problem is not apparent, send an email to the FreeBSD general questions mailing list which contains the kernel configuration file.

The kernel does not boot

If the new kernel does not boot or fails to recognize devices, do not panic! Fortunately, FreeBSD has an excellent mechanism for recovering from incompatible kernels. Simply choose the kernel to boot from at the FreeBSD boot loader. This can be accessed when the system boot menu appears by selecting the "Escape to a loader prompt" option. At the prompt, type boot kernel.old, or the name of any other kernel that is known to boot properly.

After booting with a good kernel, check over the configuration file and try to build it again. One helpful resource is /var/log/messages which records the kernel messages from every successful boot. Also, dmesg(8) will print the kernel messages from the current boot.

When troubleshooting a kernel make sure to keep a copy of a kernel that is known to work, such as GENERIC. This is important because every time a new kernel is installed, kernel.old is overwritten with the last installed kernel, which may or may not be bootable. As soon as possible, move the working kernel by renaming the directory containing the good kernel:

# mv /boot/kernel /boot/kernel.bad
# mv /boot/kernel.good /boot/kernel
The kernel works, but ps(1) does not

If the kernel version differs from the one that the system utilities have been built with, for example, a kernel built from -CURRENT sources is installed on a -RELEASE system, many system status commands like ps(1) and vmstat(8) will not work. To fix this, recompile and install a world built with the same version of the source tree as the kernel. It is never a good idea to use a different version of the kernel than the rest of the operating system.

Chapter 11. Printing

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.

11.1. 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 Filters.

  1. Create a directory to store files while they are being printed:

    # mkdir -p /var/spool/lpd/lp
    # chown daemon:daemon /var/spool/lpd/lp
    # chmod 770 /var/spool/lpd/lp
  2. As root, create /etc/printcap with these contents:

    lp=/dev/unlpt0:\  (1)
    1This line is for a printer connected to a USB port.

    For a printer connected to a parallel or "printer" port, use:


    For a printer connected directly to a network, use:


    Replace network-printer-name with the DNS host name of the network printer.

  3. Enable LPD by editing /etc/rc.conf, adding this line:


    Start the service:

    # service lpd start
    Starting lpd.
  4. Print a test:

    # printf "1. This printer can print.\n2. This is the second line.\n" | lpr

    If both lines do not start at the left border, but "stairstep" instead, see Preventing Stairstepping on Plain Text Printers.

    Text files can now be printed with lpr. Give the filename on the command line, or pipe output directly into lpr.

    % lpr textfile.txt
    % ls -lh | lpr

11.2. 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.


USB printers can be connected to any available USB port on the computer.

When FreeBSD detects a USB printer, two device entries are created: /dev/ulpt0 and /dev/unlpt0. Data sent to either device will be relayed to the printer. After each print job, ulpt0 resets the USB port. Resetting the port can cause problems with some printers, so the unlpt0 device is usually used instead. unlpt0 does not reset the USB port at all.

Parallel (IEEE-1284)

The parallel port device is /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.

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 /dev/cuau0 or /dev/cuau1. Serial USB adapters can also be used, and these will appear as /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.


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.

11.2.1. 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.

11.3. 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.

Many applications from the Ports Collection and FreeBSD utilities produce PostScript® output. This table shows the utilities available to convert that into other common PDLs:

For the easiest printing, choose a printer that supports PostScript®. Printers that support PCL are the next preferred. With print/ghostscript9-base, these printers can be used as if they understood PostScript® natively. Printers that support PostScript® 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® or PCL. They often can print plain ASCII text files. 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 The particular PDL used by various models of printers can be found at

11.4. Direct Printing

For occasional printing, files can be sent directly to a printer device without any setup. For example, a file called sample.txt can be sent to a USB printer:

# 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 nc(1) can be used with them. To print the same file to a printer with the DNS hostname of netlaser:

# nc netlaser 9100 < sample.txt

11.5. 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 lpd(8). Print jobs are submitted with lpr(1).

11.5.1. 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:

# mkdir -p /var/spool/lpd/lp
# chown daemon:daemon /var/spool/lpd/lp
# chmod 770 /var/spool/lpd/lp

Printers are defined in /etc/printcap. An entry for each printer includes details like a name, the port where it is attached, and various other settings. Create /etc/printcap with these contents:

lp:\				(1)
	:lp=/dev/unlpt0:\	(2)
	:sh:\			(3)
	:mx#0:\			(4)
	:sd=/var/spool/lpd/lp:\	(5)
	:lf=/var/log/lpd-errs:	(6)
1The name of this printer. lpr(1) sends print jobs to the lp printer unless another printer is specified with -P, so the default printer should be named lp.
2The device where the printer is connected. Replace this line with the appropriate one for the connection type shown here.
3Suppress the printing of a header page at the start of a print job.
4Do not limit the maximum size of a print job.
5The path to the spooling directory for this printer. Each printer uses its own spooling directory.
6The log file where errors on this printer will be reported.

After creating /etc/printcap, use chkprintcap(8) to test it for errors:

# chkprintcap

Fix any reported problems before continuing.

Enable lpd(8) in /etc/rc.conf:


Start the service:

# service lpd start

11.5.2. Printing with 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 doc.txt to the default printer:

% lpr doc.txt
% cat doc.txt | lpr

Printers can be selected with -P. To print to a printer called laser:

% lpr -Plaser doc.txt

11.5.3. 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® 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 su(1) to become root before creating the files.

Filters are specified in /etc/printcap with the if= identifier. To use /usr/local/libexec/lf2crlf as a filter, modify /etc/printcap like this:

	:if=/usr/local/libexec/lf2crlf:\   (1)
1if= identifies the input filter that will be used on incoming text.

The backslash line continuation characters at the end of the lines in 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:

lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: 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:

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 /usr/local/libexec/lf2crlf with these contents:

/usr/bin/sed -e "s/$/${CR}/g"

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/lf2crlf

Modify /etc/printcap to use the new filter:


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. Fancy Plain Text on PostScript® Printers with print/enscript

GNUEnscript converts plain text files into nicely-formatted PostScript® for printing on PostScript® 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 print/enscript-letter or print/enscript-a4 from the Ports Collection.

Create /usr/local/libexec/enscript with these contents:

/usr/local/bin/enscript -o -

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/enscript

Modify /etc/printcap to use the new filter:


Test the filter by printing a plain text file. Printing PostScript® to PCL Printers

Many programs produce PostScript® documents. However, inexpensive printers often only understand plain text or PCL. This filter converts PostScript® files to PCL before sending them to the printer.

Install the Ghostscript PostScript® interpreter, print/ghostscript9-base, from the Ports Collection.

Create /usr/local/libexec/ps2pcl with these contents:

/usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- -

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/ps2pcl

PostScript® input sent to this script will be rendered and converted to PCL before being sent on to the printer.

Modify /etc/printcap to use this new input filter:


Test the filter by sending a small PostScript® program to it:

% printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \
72 432 moveto (PostScript printing successful.) show showpage \004" | lpr 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® file are usually %!. A filter can detect those two characters. PostScript® files can be sent on to a PostScript® printer unchanged. Text files can be converted to PostScript® with Enscript as shown earlier. Create /usr/local/libexec/psif with these contents:

#  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

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/psif

Modify /etc/printcap to use this new input filter:


Test the filter by printing PostScript® and plain text files. Other Smart Filters

Writing a filter that detects many different types of input and formats them correctly is challenging. 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 for more details.

11.5.4. Multiple Queues

The entries in /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® laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript® files directly. Two entries can be created for the same printer in /etc/printcap:



Documents sent to textprinter will be formatted by the /usr/local/libexec/enscript filter shown in an earlier example. Advanced users can print PostScript® 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.

11.5.5. Monitoring and Controlling Printing

Several utilities are available to monitor print jobs and check and control printer operation. lpq(1)

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:

% 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:

% lpq -a
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     1    (standard input)                      27320 bytes

Rank   Owner      Job  Files                                 Total Size
1st    jsmith     287  (standard input)                      22443 bytes lprm(1)

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:

# lprm -Plp -
dfA002smithy dequeued
cfA002smithy dequeued
dfA003smithy dequeued
cfA003smithy dequeued
dfA004smithy dequeued
cfA004smithy dequeued

Remove a single job from a printer. lpq(1) is used to find the job number.

% lpq
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     5    (standard input)                      12188 bytes

% lprm -Plp 5
dfA005smithy dequeued
cfA005smithy dequeued lpc(8)

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 lpc(8). Only root can use commands which modify printer status.

Show the status of all printers:

% lpc status all
	queuing is enabled
	printing is enabled
	1 entry in spool area
	printer idle
	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:

# lpc disable lp
	queuing disabled
# lpc enable lp
	queuing enabled

Stop printing, but continue to accept new jobs. Then begin printing again:

# lpc stop lp
	printing disabled
# lpc start lp
	printing enabled
	daemon started

Restart a printer after some error condition:

# lpc restart 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:

# lpc down lp Repair parts will arrive on Monday
	printer and queuing disabled
	status message is now: Repair parts will arrive on Monday

Re-enable a printer that is down:

# lpc up lp
	printing enabled
	daemon started

See lpc(8) for more commands and options.

11.5.6. Shared Printers

Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient. Aliases

The printer name is set in the first line of the entry in /etc/printcap. Additional names, or aliases, can be added after that name. Aliases are separated from the name and each other by vertical bars:


Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with

% lpr -Psalesprinter sales-report.txt

Users in the Repairs department print to their printer with

% 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. 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 /etc/printcap. These header pages only use line feed characters for new lines. Some printers will need the /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 /etc/printcap are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser.

11.5.7. References

Example files: /usr/share/examples/printing/.

The 4.3BSD Line Printer Spooler Manual, /usr/share/doc/smm/07.lpd/paper.ascii.gz.

11.6. Other Printing Systems

Several other printing systems are available in addition to the built-in lpd(8). These systems offer support for other protocols or additional features.

11.6.1. CUPS (Common UNIX® Printing System)

CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: CUPS

11.6.2. HPLIP

Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is print/hplip. The main web page is at The port handles all the installation details on FreeBSD. Configuration information is shown at

11.6.3. LPRng

LPRng was developed as an enhanced alternative to lpd(8). The port is sysutils/LPRng. For details and documentation, see

Chapter 12. Linux Binary Compatibility

12.1. Synopsis

FreeBSD provides optional binary compatibility with Linux®, commonly referred to as Linuxulator, allowing users to install and run unmodified Linux binaries. It is available for the x86 (both 32 and 64 bit) and AArch64 architectures. Some Linux-specific operating system features are not yet supported; this mostly happens with functionality specific to hardware or related to system management, such as cgroups or namespaces.

Before reading this chapter, you should:

After reading this chapter, you will know:

  • How to enable Linux binary compatibility on a FreeBSD system.

  • How to install additional Linux shared libraries.

  • How to install Linux applications on a FreeBSD system.

  • The implementation details of Linux compatibility in FreeBSD.

12.2. Configuring Linux Binary Compatibility

By default, linux(4) binary compatibility is not enabled.

To enable the Linux ABI at boot time, execute the following command:

# sysrc linux_enable="YES"

Once enabled, it can be started without rebooting executing the following command:

# service linux start

This is enough for statically linked Linux binaries to work.

The Linux service will load necessary kernel modules and mount filesystems expected by Linux applications under /compat/linux. They can be started in the same way native FreeBSD binaries can; they behave almost exactly like native processes and can be traced and debugged the usual way.

The current content of /compat/linux can be checked executing the following command:

# ls -l /compat/linux/

The output should be similar to the following:

total 1
dr-xr-xr-x  13 root  wheel  512 Apr 11 19:12 dev
dr-xr-xr-x   1 root  wheel    0 Apr 11 21:03 proc
dr-xr-xr-x   1 root  wheel    0 Apr 11 21:03 sys

12.3. Linux userlands

Linux software requires more than just an ABI to work. In order to run Linux software a Linux userland must be installed first.

If all that is wanted is to run some software already included in the Ports tree, it can be installed via package manager and pkg(8) will automatically setup the required Linux userland.

For example, to install Sublime Text 4, along with all the Linux libraries it depends on, run this command:

# pkg install linux-sublime-text4

12.3.1. CentOS Base System from FreeBSD Packages

To install the CentOS userland execute the following command:

# pkg install linux_base-c7

emulators/linux_base-c7 will place the base system derived from CentOS 7 into /compat/linux.

After installing the package, the contents of /compat/linux can be verified by running the following command to check that the CentOS userland has been installed:

# ls -l /compat/linux/

The output should be similar to the following:

total 30
lrwxr-xr-x   1 root  wheel    7 Apr 11  2018 bin -> usr/bin
drwxr-xr-x  13 root  wheel  512 Apr 11 21:10 dev
drwxr-xr-x  25 root  wheel   64 Apr 11 21:10 etc
lrwxr-xr-x   1 root  wheel    7 Apr 11  2018 lib -> usr/lib
lrwxr-xr-x   1 root  wheel    9 Apr 11  2018 lib64 -> usr/lib64
drwxr-xr-x   2 root  wheel    2 Apr 11 21:10 opt
dr-xr-xr-x   1 root  wheel    0 Apr 11 21:25 proc
lrwxr-xr-x   1 root  wheel    8 Feb 18 02:10 run -> /var/run
lrwxr-xr-x   1 root  wheel    8 Apr 11  2018 sbin -> usr/sbin
drwxr-xr-x   2 root  wheel    2 Apr 11 21:10 srv
dr-xr-xr-x   1 root  wheel    0 Apr 11 21:25 sys
drwxr-xr-x   8 root  wheel    9 Apr 11 21:10 usr
drwxr-xr-x  16 root  wheel   17 Apr 11 21:10 var

12.3.2. Debian / Ubuntu Base System with debootstrap

An alternative way of providing Linux shared libraries is by using sysutils/debootstrap. This has the advantage of providing a full Debian or Ubuntu distribution.

To install debootstrap execute the following command:

# pkg install debootstrap

debootstrap(8) needs linux(4) ABI enabled. Once enabled, execute the following command to install Ubuntu or Debian in /compat/ubuntu:

# debootstrap focal /compat/ubuntu

While it is technically possible to install into /compat/linux instead, it’s discouraged due to possible clashes with CentOS-based packages. Instead, derive the directory name from the distribution or version name, e.g., /compat/ubuntu.

The output should be similar to the following:

I: Retrieving InRelease
I: Checking Release signature
I: Valid Release signature (key id F6ECB3762474EDA9D21B7022871920D1991BC93C)
I: Retrieving Packages
I: Validating Packages
I: Resolving dependencies of required packages...
I: Resolving dependencies of base packages...
I: Checking component main on
I: Configuring console-setup...
I: Configuring kbd...
I: Configuring ubuntu-minimal...
I: Configuring libc-bin...
I: Configuring ca-certificates...
I: Base system installed successfully.

Then set up mounts in /etc/fstab.

If the contents of the home directory should be shared and to be able to run X11 applications, /home and /tmp should be mounted in the linux compat area using nullfs(5) for loopback.

The following example can be added to /etc/fstab:

# Device        Mountpoint              FStype          Options                      Dump    Pass#
devfs           /compat/ubuntu/dev      devfs           rw,late                      0       0
tmpfs           /compat/ubuntu/dev/shm  tmpfs           rw,late,size=1g,mode=1777    0       0
fdescfs         /compat/ubuntu/dev/fd   fdescfs         rw,late,linrdlnk             0       0
linprocfs       /compat/ubuntu/proc     linprocfs       rw,late                      0       0
linsysfs        /compat/ubuntu/sys      linsysfs        rw,late                      0       0
/tmp            /compat/ubuntu/tmp      nullfs          rw,late                      0       0
/home           /compat/ubuntu/home     nullfs          rw,late                      0       0

Then execute mount(8):

# mount -al

To access the system using chroot(8) execute the following command:

# chroot /compat/ubuntu /bin/bash

Then uname(1) can be executed to check the Linux environment:

# uname -s -r -m

The output should be similar to the following:

Linux 3.17.0 x86_64

Once inside the chroot, the system behaves as in a normal Ubuntu installation While systemd doesn’t work, the service(8) command works as usual.

To add the package repositories missing from defaults edit the file /compat/ubuntu/etc/apt/sources.list.

For amd64 the following example can be used:

deb focal main universe restricted multiverse
deb focal-security universe multiverse restricted main
deb focal-backports universe multiverse restricted main
deb focal-updates universe multiverse restricted main

For arm64 this other example can be used:

deb bionic main universe restricted multiverse

12.4. Advanced Topics

A list of all Linux-related sysctl(8) knobs can be found in linux(4).

Some applications require specific filesystems to be mounted.

This is normally handled by the /etc/rc.d/linux script but can be disabled at boot executing the following command:

sysrc linux_mounts_enable="NO"

Filesystems mounted by the rc script will not work for Linux processes inside chroots or jails; if needed, configure them in /etc/fstab:

devfs      /compat/linux/dev      devfs      rw,late                    0  0
tmpfs      /compat/linux/dev/shm  tmpfs      rw,late,size=1g,mode=1777  0  0
fdescfs    /compat/linux/dev/fd   fdescfs    rw,late,linrdlnk           0  0
linprocfs  /compat/linux/proc     linprocfs  rw,late                    0  0
linsysfs   /compat/linux/sys      linsysfs   rw,late                    0  0

Since the Linux binary compatibility layer has gained support for running both 32- and 64-bit Linux binaries, it is no longer possible to link the emulation functionality statically into a custom kernel.

12.4.1. Installing Additional Libraries Manually

For base system subdirectories created with debootstrap(8), use the instructions above instead.

If a Linux application complains about missing shared libraries after configuring Linux binary compatibility, determine which shared libraries the Linux binary needs and install them manually.

From a Linux system using the same CPU architecture, ldd can be used to determine which shared libraries the application needs.

For example, to check which shared libraries linuxdoom needs, run this command from a Linux system that has Doom installed:

% ldd linuxdoom

The output should be similar to the following: (DLL Jump 3.1) => /usr/X11/lib/ (DLL Jump 3.1) => /usr/X11/lib/ (DLL Jump 4.5pl26) => /lib/

Then, copy all the files in the last column of the output from the Linux system into /compat/linux on the FreeBSD system. Once copied, create symbolic links to the names in the first column.

This example will result in the following files on the FreeBSD system:

/compat/linux/usr/X11/lib/ ->
/compat/linux/usr/X11/lib/ ->
/compat/linux/lib/ ->

If a Linux shared library already exists with a matching major revision number to the first column of the ldd output, it does not need to be copied to the file named in the last column, as the existing library should work. It is advisable to copy the shared library if it is a newer version, though. The old one can be removed, as long as the symbolic link points to the new one.

For example, these libraries already exist on the FreeBSD system:

/compat/linux/lib/ ->

and ldd indicates that a binary requires a later version: (DLL Jump 4.5pl26) ->

Since the existing library is only one or two versions out of date in the last digit, the program should still work with the slightly older version. However, it is safe to replace the existing with the newer version:

/compat/linux/lib/ ->

Generally, one will need to look for the shared libraries that Linux binaries depend on only the first few times that a Linux program is installed on FreeBSD. After a while, there will be a sufficient set of Linux shared libraries on the system to be able to run newly installed Linux binaries without any extra work.

12.4.2. Branding Linux ELF Binaries

The FreeBSD kernel uses several methods to determine if the binary to be executed is a Linux one: it checks the brand in the ELF file header, looks for known ELF interpreter paths and checks ELF notes; finally, by default, unbranded ELF executables are assumed to be Linux anyway.

Should all those methods fail, an attempt to execute the binary might result in error message:

% ./my-linux-elf-binary

The output should be similar to the following:

ELF binary type not known

To help the FreeBSD kernel distinguish between a FreeBSD ELF binary and a Linux binary, use brandelf(1):

% brandelf -t Linux my-linux-elf-binary

12.4.3. Installing a Linux RPM Based Application

To install a Linux RPM-based application, first install the archivers/rpm4 package or port. Once installed, root can use this command to install a .rpm:

# cd /compat/linux
# rpm2cpio < /path/to/linux.archive.rpm | cpio -id

If necessary, brandelf the installed ELF binaries. Note that this will prevent a clean uninstall.

12.4.4. Configuring the Hostname Resolver

If DNS does not work or this error appears:

resolv+: "bind" is an invalid keyword resolv+:
"hosts" is an invalid keyword

configure /compat/linux/etc/host.conf as follows:

order hosts, bind
multi on

This specifies that /etc/hosts is searched first and DNS is searched second. When /compat/linux/etc/host.conf does not exist, Linux applications use /etc/host.conf in the host system but they complain since that file does not exist in FreeBSD. Remove bind if a name server is not configured using /etc/resolv.conf.

12.4.5. Miscellaneous

More information on how binary compatibility works with Linux® can be found in the article Linux emulation in FreeBSD.

Chapter 13. WINE

13.1. Synopsis

WINE, which stands for Wine Is Not an Emulator, is technically a software translation layer. It enables to install and run some software written for Windows® on FreeBSD (and other) systems.

It operates by intercepting system calls, or requests from the software to the operating system, and translating them from Windows® calls to calls that FreeBSD understands. It will also translate any responses as needed into what the Windows® software is expecting. So in some ways, it emulates a Windows® environment, in that it provides many of the resources Windows® applications are expecting.

However, it is not an emulator in the traditional sense. Many of these solutions operate by constructing an entire other computer using software processes in place of hardware. Virtualization (such as that provided by the emulators/qemu port) operates in this way. One of the benefits of this approach is the ability to install a full version of the OS in question to the emulator. It means that the environment will not look any different to applications than a real machine, and chances are good that everything will work on it. The downside to this approach is the fact that software acting as hardware is inherently slower than actual hardware. The computer built in software (called the guest) requires resources from the real machine (the host), and holds on to those resources for as long as it is running.

The WINE Project, on the other hand, is much lighter on system’s resources. It will translate system calls on the fly, so while it is difficult to be as fast as a real Windows® computer, it can come very close. On the other hand, WINE is trying to keep up with a moving target in terms of all the different system calls and other functionality it needs to support. As a result there may be applications that do not work as expected on WINE, will not work at all, or will not even install to begin with.

At the end of the day, WINE provides another option to try to get a particular Windows® software program running on FreeBSD. It can always serve as the first option which, if successful, offers a good experience without unnecessarily depleting the host FreeBSD system’s resources.

This chapter will describe:

  • How to install WINE on a FreeBSD system.

  • How WINE operates, and how it is different from other alternatives like virtualizaton.

  • How to fine-tune WINE to the specific needs of some applications.

  • How to install GUI helpers for WINE.

  • Common tips and solutions for on FreeBSD.

  • Considerations for WINE on FreeBSD in terms of the multi-user environment.

Before reading this chapter, it will be useful to:

13.2. WINE Overview & Concepts

WINE is a complex system, so before running it on a FreeBSD system it is worth gaining an understanding of what it is and how it works.

13.2.1. What is WINE?

As mentioned in the Synopsis for this chapter, WINE is a compatibility layer that allows Windows® applications to run on other operating systems. In theory, it means these programs should run on systems like FreeBSD, macOS, and Android.

When WINE runs a Windows® executable, two things occur:

  • Firstly, WINE implements an environment that mimics that of various versions of Windows®. For example, if an application requests access to a resource such as RAM, WINE has a memory interface that looks and acts (as far as the application is concerned) like Windows®.

  • Then, once that application makes use of that interface, WINE takes the incoming request for space in memory and translates it to something compatible with the host system. In the same way when the application retrieves that data, WINE facilitates fetching it from the host system and passing it back to the Windows® application.

13.2.2. WINE and the FreeBSD System

Installing WINE on a FreeBSD system will entail a few different components:

  • FreeBSD applications for tasks such as running the Windows® executables, configuring the WINE sub-system, or compiling programs with WINE support.

  • A large number of libraries that implement the core functions of Windows® (for example /lib/wine/, which is part of the aforementioned memory interface).

  • A number of Windows® executables, which are (or mimic) common utilities (such as /lib/wine/, which provides the standard Windows® text editor).

  • Additional Windows® assets, in particular fonts (like the Tahoma font, which is stored in share/wine/fonts/tahoma.ttf in the install root).

13.2.3. Graphical Versus Text Mode/Terminal Programs in WINE

As an operating system where terminal utilities are "first-class citizens," it is natural to assume that WINE will contain extensive support for text-mode program. However, the majority of applications for Windows®, especially the most popular ones, are designed with a graphical user interface (GUI) in mind. Therefore, WINE’s utilities are designed by default to launch graphical programs.

However, there are three methods available to run these so-called Console User Interface (CUI) programs:

  • The Bare Streams approach will display the output directly to standard output.

  • The wineconsole utility can be used with either the user or curses backed to utilize some of the enhancements the WINE system provides for CUI applications.

These approaches are described in greater detail on the WINE Wiki.

13.2.4. WINE Derivative Projects

WINE itself is a mature open source project, so it is little surprise it is used as the foundation of more complex solutions. Commercial WINE Implementations

A number of companies have taken WINE and made it a core of their own, proprietary products (WINE’s LGPL license permits this). Two of the most famous of these are as follows:

  • Codeweavers CrossOver

This solution provides a simplified "one-click" installation of WINE, which contains additional enhancements and optimizations (although the company contributes many of these back upstream to the WINE project). One area of focus for Codeweavers is to make the most popular applications install and run smoothly.

While the company once produced a native FreeBSD version of their CrossOver solution, it appears to have long been abandoned. While some resources (such as a dedicated forum) are still present, they also have seen no activity for some time.

  • Steam Proton

Gaming company Steam also uses WINE to enable Windows® games to install and run on other systems. it is primary target is Linux-based systems, though some support exists for macOS as well.

While Steam does not offer a native FreeBSD client, there are several options for using the Linux® client using FreeBSD’s Linux Compatibility Layer. WINE Companion Programs

In addition to proprietary offerings, other projects have released applications designed to work in tandem with the standard, open source version of WINE. The goals for these can range from making installation easier to offering easy ways to get popular software installed.

These solutions are covered in greater detail in the later section on GUI frontends, and include the following:

  • winetricks

  • Suyimazu

13.2.5. Alternatives to WINE

For FreeBSD users, some alternatives to using WINE are as follows:

  • Dual-Booting: A straightforward option is to run desired Windows® applications natively on that OS. This of course means exiting FreeBSD in order to boot Windows®, so this method is not feasible if access to programs in both systems is required simultaneously.

  • Virtual Machines: Virtual Machines (VMs), as mentioned earlier in this chapter, are software processes that emulate full sets of hardware, on which additional operating systems (including Windows®) can be installed and run. Modern tools make VMs easy to create and manage, but this method comes at a cost. A good portion of the host systems resources must be allocated to each VM, and those resources cannot be reclaimed by the host as long as the VM is running. A few examples of VM managers include the open source solutions qemu, bhyve, and VirtualBox. See the chapter on Virtualization for more detail.

  • Remote Access: Like many other UNIX®-like systems, FreeBSD can run a variety of applications enabling users to remotely access Windows® computers and use their programs or data. In addtion to clients such as xrdp that connect to the standard Windows® Remote Desktop Protocol, other open source standards such as vnc can also be used (provided a compatible server is present on the other side).

13.3. Installing WINE on FreeBSD

WINE can be installed via the pkg tool, or by compiling the port(s).

13.3.1. WINE Prerequistes

Before installing WINE itself, it is useful to have the following pre-requisites installed.

  • A GUI

Most Windows® programs are expecting to have a graphical user interface available. If WINE is installed without one present, its dependencies will include the Wayland compositor, and so a GUI will be installed along with WINE. But it is useful to have the GUI of choice installed, configured, and working correctly before installing WINE.

  • wine-gecko

The Windows® operating system has for some time had a default web browser pre-installed: Internet Explorer. As a result, some applications work under the assumption that there will always be something capable of displaying web pages. In order to provide this functionality, the WINE layer includes a web browser component using the Mozilla project’s Gecko engine. When WINE is first launched it will offer to download and install this, and there are reasons users might want it do so (these will be covered in a later chapter). But they can also install it prior to installing WINE, or alongside the install of WINE proper.

Install this package with the following:

# pkg install wine-gecko

Alternately, compile the port with the following:

# cd /usr/ports/emulator/wine-gecko
# make install
  • wine-mono

This port installs the MONO framework, an open source implementation of Microsoft’s .NET. Including this with the WINE installation will make it that much more likely that any applications written in .NET will install and run on the system.

To install the package:

# pkg install wine-mono

To compile from the ports collection:

# cd /usr/ports/emulator/wine-mono
# make install

13.3.2. Installing WINE via FreeBSD Package Repositories

With the pre-requisites in place, install WINE via package with the following command:

# pkg install wine

Alternately compile the WINE sub-system from source with the following:

# cd /usr/ports/emulator/wine
# make install

13.3.3. Concerns of 32- Versus 64-Bit in WINE Installations

Like most software, Windows® applications made the upgrade from the older 32-bit architecture to 64 bits. And most recent software is written for 64-bit operating systems, although modern OSes can sometimes continue to run older 32-bit programs as well. FreeBSD is no different, having had support for 64-bit since the 5.x series.

However, using old software no longer supported by default is a common use for emulators, and users commonly turn to WINE to play games and use other programs that do not run properly on modern hardware. Fortunately, FreeBSD can support all three scenarios:

  • On modern, 64-bit machine and want to run 64-bit Windows® software, simply install the ports mentioned in the above sections. The ports system will automatically install the 64-bit version.

  • Alternately, users might have an older 32-bit machine that they do not want to run with its original, now non-supported software. They can install the 32-bit (i386) version of FreeBSD, then install the ports in the above sections.

13.4. Running a First WINE Program on FreeBSD

Now that WINE is installed, the next step is to try it out by running a simple program. An easy way to do this is to download a self-contained application, i.e., one can simply unpack and run without any complex installation process.

So-called "portable" versions of applications are good choices for this test, as are programs that run with only a single executable file.

13.4.1. Running a Program from the Command Line

There are two different methods to launch a Windows program from the terminal. The first, and most straightforward is to navigate to the directory containing the program’s executable (.EXE) and issue the following:

% wine program.exe

For applications that take command-line arguments, add them after the executable as usual:

% wine program2.exe -file file.txt

Alternately, supply the full path to the executable to use it in a script, for example:

% wine /home/user/bin/program.exe

13.4.2. Running a Program from a GUI

After installation graphical shells should be updated with new associations for Windows executable (.EXE) files. It will now be possible to browse the system using a file manager, and launch the Windows application in the same way as other files and programs (either a single- or double-click, depending on the desktop’s settings).

On most desktops, check to make sure this association is correct by right-clicking on the file, and looking for an entry in the context menu to open the file. One of the options (hopefully the default one) will be with the Wine Windows Program Loader, as shown in the below screenshot:

wine run np++ 1

In the event the program does not run as expected, try launching it from the command line and review any messages displayed in the terminal to troubleshoot.

In the event WINE is not the default application for .EXE files after install, check the MIME associate for this extension in the current desktop environment, graphical shell, or file manager.

13.5. Configuring WINE Installation

With an understanding of what WINE is and how it works at a high level, the next step to effectively using it on FreeBSD is becoming familiar with its configuration. The following sections will describe the key concept of the WINE prefix, and illustrate how it is used to control the behavior of applications run through WINE.

13.5.1. WINE Prefixes

A WINE prefix is a directory, usually located beneath the default location of $HOME/.wine though it can be located elsewhere. The prefix is a set of configurations and support files used by the wine to configure and run the Windows® environment a given application needs. By default, a brand new WINE installation will create the following structure when first launched by a user:

  • .update-timestamp: contains the last modified date of file /usr/share/wine/wine.inf. It is used by WINE to determine if a prefix is out of date, and automatically update it if needed.

  • dosdevices/: contains information on mappings of Windows® resources to resources on the host FreeBSD system. For example, after a new WINE installation, this should contain at least two entries which enable access to the FreeBSD filesystem using Windows®-style drive letters:

    • c:@: A link to drive_c described below.

    • z:@: A link to the root directory of the system.

  • drive_c/: emulates the main (i.e., C:) drive of a Windows® system. It contains a directory structure and associated files mirroring that of standard Windows® systems. A fresh WINE prefix will contain Windows® 10 directories such as Users and Windows that holds the OS itself. Furthermore, applications installed within a prefix will be located in either Program Files or Program Files (x86), depending on their architecture.

  • system.reg: This Registry file contains information on the Windows® installation, which in the case of WINE is the environment in drive_c.

  • user.reg: This Registry file contains the current user’s personal configurations, made either by varous software or through the use of the Registry Editor.

  • userdef.reg: This Registry file is a default set of configurations for newly-created users.

13.5.2. Creating and Using WINE Prefixes

While WINE will create a default prefix in the user’s $HOME/.wine/, it is possible to set up multiple prefixes. There are a few reasons to do this:

  • The most common reason is to emulate different versions of Windows®, according to the compatibility needs of the software in question.

  • In addition, it is common to encounter software that does not work correctly in the default environment, and requires special configuration. it is useful to isolate these in their own, custom prefixes, so the changes do not impact other applications.

  • Similarly, copying the default or "main" prefix into a separate "testing" one in order to evaluate an application’s compatibility can reduce the chance of corruption.

Creating a prefix from the terminal requires the following command:

% WINEPREFIX="/home/username/.wine-new" winecfg

This will run the winecfg program, which can be used to configure wine prefixes (more on this in a later section). But by providing a directory path value for the WINEPREFIX environment variable, a new prefix is created at that location if one does not already exist.

Supplying the same variable to the wine program will similarly cause the selected program to be run with the specified prefix:

% WINEPREFIX="/home/username/.wine-new" wine program.exe

13.5.3. Configuring WINE Prefixes with winecfg

As described above WINE includes a tool called winecfg to configure prefixes from within a GUI. It contains a variety of functions, which are detailed in the sections below. When winecfg is run from within a prefix, or provided the location of a prefix within the WINEPREFIX variable, it enables the configuration of the selected prefix as described in the below sections.

Selections made on the Applications tab will affect the scope of changes made in the Libraries and Graphics tabs, which will be limited to the application selected. See the section on Using Winecfg in the WINE Wiki for more details. Applications
wine config 1

The Applications contains controls enabling the association of programs with a particular version of Windows®. On first start-up the Application settings section will contain a single entry: Default Settings. This corresponds to all the default configurations of the prefix, which (as the disabled Remove application button implies) cannot be deleted.

But additional applications can be added with the following process:

  1. Click the Add application button.

  2. Use the provided dialog to select the desired program’s executable.

  3. Select the version of Windows® to be used with the selected program. Libraries
wine config 2

WINE provides a set of open source library files as part of its distribution that provide the same functions as their Windows® counterparts. However, as noted earlier in this chapter, the WINE project is always trying to keep pace with new updates to these libraries. As a result, the versions that ship with WINE may be missing functionality that the latest Windows® programs are expecting.

However, winecfg makes it possible specify overrides for the built-in libraries, particularly there is a version of Windows® available on the same machine as the host FreeBSD installation. For each library to be overridden, do the following:

  1. Open the New override for library drop-down and select the library to be replaced.

  2. Click the Add button.

  3. The new override will appear in the Existing overrides list, notice the native, builtin designation in parentheses.

  4. Click to select the library.

  5. Click the Edit button.

  6. Use the provided dialog to select a corresponding library to be used in place of the built-in one.

Be sure to select a file that is truly the corresponding version of the built-in one, otherwise there may be unexpected behavior. Graphics
wine config 3

The Graphics tab provides some options to make the windows of programs run via WINE operate smoothly with FreeBSD:

  • Automatic mouse capture when windows are full-screen.

  • Allowing the FreeBSD window manager to decorate the windows, such as their title bars, for programs running via WINE.

  • Allowing the window manager to control windows for programs running via WINE, such as running resizing functions on them.

  • Create an emulated virtual desktop, within which all WINE programs will run. If this item is selected, the size of the virtual desktop can be specified using the Desktop size input boxes.

  • Setting the screen resolution for programs running via WINE. Desktop Integration
wine config 4

This tab allows configuration of the following items:

  • The theme and related visual settings to be used for programs running via WINE.

  • Whether the WINE sub-system should manage MIME types (used to determine which application opens a particular file type) internally.

  • Mappings of directories in the host FreeBSD system to useful folders within the Windows® environment. To change an existing association, select the desired item and click Browse, then use the provided dialog to select a directory. Drives
wine config 5

The Drives tab allows linking of directories in the host FreeBSD system to drive letters in the Windows® environment. The default values in this tab should look familiar, as they are displaying the contents of dosdevices/ in the current WINE prefix. Changes made via this dialog will reflect in dosdevices, and properly-formatted links created in that directory will display in this tab.

To create a new entry, such as for a CD-ROM (mounted at /mnt/cdrom), take the following steps:

  1. Click the _Add _ button.

  2. In the provided dialog, choose a free drive letter.

  3. Click OK.

  4. Fill in the Path input box by either typing the path to the resource, or click _Browse _ and use the provided dialog to select it.

By default WINE will autodetect the type of resource linked, but this can be manually overridden. See the section in the WINE Wiki for more detail on advanced options. Audio
wine config 6

This tab contains some configurable options for routing sound from Windows® programs to the native FreeBSD sound system, including:

  • Driver selection

  • Default device selection

  • Sound test About
wine config 7

The final tab contains information on the WINE project, including a link to the website. It also allows entry of (entirely optional) user information, although this is not sent anywhere as it is in other operating systems.

13.6. WINE Management GUIs

While the base install of WINE comes with a GUI configuration tool in winecfg, it is main purpose is just that: strictly configuring an existing WINE prefix. There are, however, more advanced applications that will assist in the initial installation of applications as well as optimizing their WINE environments. The below sections include a selection of the most popular.

13.6.1. Winetricks

The winetricks tool is a cross-platform, general purpose helper program for WINE. It is not developed by the WINE project proper, but rather maintained on Github by a group of contributors. It contains some automated "recipes" for getting common applications to work on WINE, both by optimizing the settings as well as acquiring some DLL libraries automatically. Installing winetricks

To install winetricks on a FreeBSD using binary packages, use the following commands (note winetricks requires either the i386-wine or i386-wine-devel package, and is therefore not installed automatically with other dependencies):

# pkg install i386-wine winetricks

To compile it from source, issue the following in the terminal:

# cd /usr/ports/emulators/i386-wine
# make install
# cd /usr/ports/emulators/winetricks
# make install

If a manual installation is required, refer to the Github account for instructions. Using winetricks

Run winetricks with the following command:

% winetricks

Note: this should be in a 32-bit prefix to run winetricks. Launching winetricks displays a window with a number of choices, as follows:

winetricks run 1

Selecting either Install an application, Install a benchmark, or Install a game shows a list with supported options, such as the one below for applications:

winetricks run 2

Selecting one or more items and clicking OK will start their installation process(es). Initially, some messages that appear to be errors may show up, but they’re actually informational alerts as winetricks configures the WINE environment to get around known issues for the application:

winetricks app install 1

Once these are circumvented, the actual installer for the application will be run:

winetricks app install 2

Once the installation completes, the new Windows application should be available from the desktop environment’s standard menu (shown in the screenshot below for the LXQT desktop environment):

winetricks menu 1

In order to remove the application, run winetricks again, and select Run an uninstaller.

winetricks uninstall 1

A Windows®-style dialog will appear with a list of installed programs and components. Select the application to be removed, then click the Modify/Remove button.

winetricks uninstall 2

This will run the applications built-in installer, which should also have the option to uninstall.

winetricks uninstall 3

13.6.2. Suyimazu

Suyimazu is an application similar to winetricks, although it was inspired by the Lutris gaming system for Linux. But while it is focused on games, there are also non-gaming applications available for install through Suyimazu. Installing Suyimazu

To install Suyimazu’s binary package, issue the following command:

# pkg install suyimazu

Suyimazu is available in the FreeBSD Ports system. However, than the emulators section of Ports or binary packages, look for it in the games section.

# cd /usr/ports/games/suyimazu
# make install Using Suyimazu

Suyimazu’s usage is quite similar to that of winetricks. When using it for the first time, launch it from the command line (or a desktop environment runner applet) with:

% Suyimazu

This should result in a friendly welcome message. Click OK to continue.

homura launch 1

The program will also offer to place a link in the application menu of compatible environments:

homura run 2

Depending on the setup of the FreeBSD machine, Suyimazu may display a message urging the install of native graphics drivers.

homura run 3

The application’s window should then appear, which amounts to a "main menu" with all its options. Many of the items are the same as winetricks, although Suyimazu offers some additional, helpful options such as opening its data folder (Open Suyimazu Folder) or running a specified program (Run a executable in prefix).

homura install 1

To select one of Suyimazu’s supported applications to install, select Installation, and click OK. This will display a list of applications Homura can install automatically. Select one, and click OK to start the process.

homura install 2

As a first step Suyimazu will download the selected program. A notification may appear in supported desktop environments.

homura install 3

The program will also create a new prefix for the application. A standard WINE dialog with this message will display.

homura install 4

Next, Suyimazu will install any prerequisites for the selected program. This may involve downloading and extracting a fair number of files, the details of which will show in dialogs.

homura install 5

Downloaded packages are automatically opened and run as required.

homura install 6

The installation may end with a simple desktop notification or message in the terminal, depending on how Suyimazu was launched. But in either case Suyimazu should return to the main screen. To confirm the installation was successful, select Launcher, and click OK.

homura install 7

This will display a list of installed applications.

homura install 8

To run the new program, select it from the list, and click OK. To uninstall the application, select Uninstallation from the main screen, which will display a similar list. Select the program to be removed, and click OK.

homura uninstall 1

13.6.3. Running Multiple Management GUIs

it is worth noting that the above solutions are not mutually exclusive. it is perfectly acceptable, even advantageous, to have both installed at the same time, as they support a different set of programs.

However, it is wise to ensure that they do not access any of the same WINE prefixes. Each of these solutions applies workarounds and makes changes to the registries based on known workarounds to existing WINE issues in order to make a given application run smoothly. Allowing both winetricks and Homura to access the same prefix could lead to some of these being overwritten, with the result being some or all applications do not work as expected.

13.7. WINE in Multi-User FreeBSD Installations

13.7.1. Issues with Using a Common WINE Prefix

Like most UNIX®-like operating systems, FreeBSD is designed for multiple users to be logged in and working at the same time. On the other hand, Windows® is multi-user in the sense that there can be multiple user accounts set up on one system. But the expectation is that only one will be using the physical machine (a desktop or laptop PC) at any given moment.

More recent consumer versions of Windows® have taken some steps to improve the OS in multi-user scenarios. But it is still largely structured around a single-user experience. Furthermore, the measures the WINE project has taken to create a compatible environment means, unlike FreeBSD applications (including WINE itself), it will resemble this single-user environment.

So it follows that each user will have to maintain their own set of configurations, which is potentially good. Yet it is advantageous to install applications, particularly large ones like office suites or games, only once. Two examples of reasons to do this are maintenance (software updates need only be applied once) and efficiency in storage (no duplicated files).

There are two strategies to minimize the impact of multiple WINE users in the system.

13.7.2. Installing Applications to a Common Drive

As shown in the section on WINE Configuration, WINE provides the ability to attach additional drives to a given prefix. In this way, applications can be installed to a common location, while each user will still have an prefix where individual settings may be kept (depending on the program). This is a good setup if there are relatively few applications to be shared between users, and they are programs that require few custom tweaks changes to the prefix in order to function.

The steps to make install applications in this way are as follows:

  1. First, set up a shared location on the system where the files will be stored, such as /mnt/windows-drive_d/. Creating new directories is described in the mkdir(1) manual page.

  2. Next, set permissions for this new directory to allow only desired users to access it. One approach to this is to create a new group such as "windows," add the desired users to that group (see the sub-section on groups in the Users and Basic Account Management section), and set to the permissions on the directory to 770 (the section on Permissions illustrates this process).

  3. Finally, add the location as a drive to the user’s prefix using the winecfg as described in the above section on WINE Configuration in this chapter.

Once complete, applications can be installed to this location, and subsequently run using the assigned drive letter (or the standard UNIX®-style directory path). However, as noted above, only one user should be running these applications (which may be accessing files within their installation directory) at the same time. Some applications may also exhibit unexpected behavior when run by a user who is not the owner, despite being a member of the group that should have full "read/write/execute" permissions for the entire directory.

13.7.3. Using a Common Installation of WINE

If, on the other hand, there are many applications to be shared, or they require specific tuning in order to work correctly, a different approach may be required. In this method, a completely separate user is created specifically for the purposes of storing the WINE prefix and all its installed applications. Individual users are then granted permission to run programs as this user using the sudo(8) command. The result is that these users can launch a WINE application as they normally would, only it will act as though launched by the newly-created user, and therefore use the centrally-maintained prefix containing both settings and programs. To accomplish this, take the following steps:

Create a new user with the following command (as root), which will step through the required details:

# adduser

Enter the username (e.g., windows) and Full name ("Microsoft Windows"). Then accept the defaults for the remainder of the questions. Next, install the sudo utility using binary packages with the following:

# pkg install sudo

Once installed, edit /etc/sudoers as follows:

# User alias specification

# define which users can run the wine/windows programs
User_Alias WINDOWS_USERS = user1,user2

# define which users can administrate (become root)
User_Alias ADMIN = user1

# Cmnd alias specification

# define which commands the WINDOWS_USERS may run
Cmnd_Alias WINDOWS = /usr/bin/wine,/usr/bin/winecfg

# Defaults
Defaults:WINDOWS_USERS env_reset
Defaults:WINDOWS_USERS env_keep += DISPLAY
Defaults    !lecture,tty_tickets,!fqdn

# User privilege specification
root    ALL=(ALL) ALL

# Members of the admin user_alias, defined above, may gain root privileges

# The WINDOWS_USERS may run WINDOWS programs as user windows without a password

The result of these changes is the users named in the User_Alias section are permitted to run the programs listed in the Cmnd Alias section using the resources listed in the Defaults section (the current display) as if they were the user listed in the final line of the file. In other words, users designates as WINDOWS_USERS can run the WINE and winecfg applications as user windows. As a bonus, the configuration here means they will not be required to enter the password for the windows user.

Next provide access to the display back to the windows user, as whom the WINE programs will be running:

% xhost +local:windows

This should be added to the list of commands run either at login or when the default graphical environment starts. Once all the above are complete, a user configured as one of the WINDOW_USERS in sudoers can run programs using the shared prefix with the following command:

% sudo -u windows wine program.exe

it is worth noting that multiple users accessing this shared environment at the same time is still risky. However, consider also that the shared environment can itself contain multiple prefixes. In this way an administrator can create a tested and verified set of programs, each with its own prefix. At the same time, one user can play a game while another works with office programs without the need for redundant software installations.

13.8. WINE on FreeBSD FAQ

The following section describes some frequently asked questions, tips/tricks, or common issues in running WINE on FreeBSD, along with their respective answers.

13.8.1. Basic Installation and Usage How to Install 32-bit and 64-bit WINE on the Same System?

As described earlier in this section, the wine and i386-wine packages conflict with one another, and therefore cannot be installed on the same system in the normal way. However, multiple installs can be achieved using mechanisms like chroots/jails, or by building WINE from source (note this does not mean building the port). Can DOS Programs Be Run on WINE?

They can, as "Console User Interface" applications as mentioned earlier in this section. However, there is an arguably better method for running DOS software: DOSBox. On the other hand, there is little reason not to at least try it. Simply create a new prefix, install the software, and if it does not work delete the prefix. Should the emulators/wine-devel Package/Port be Installed to Use the Development Version of WINE Instead of Stable?

Yes, installing this version will install the "development" version of WINE. As with the 32- and 64-bit versions, they cannot be installed together with the stable versions unless additional measures are taken.

Note that WINE also has a "Staging" version, which contains the most recent updates. This was at one time available as a FreeBSD port; however, it has since been removed. It can be compiled directly from source however.

13.8.2. Install Optimization How Should Windows® Hardware (e.g., Graphics) Drivers be Handled?

Operating system drivers transfer commands between applications and hardware. WINE emulates a Windows® environment, including the drivers, which in turn use FreeBSD’s native drivers for this transfer. it is not advisable to install Windows® drivers, as the WINE system is designed to use the host systems drivers. If, for example, a graphics card that benefits from dedicated drivers, install them using the standard FreeBSD methods, not Windows® installers. Is There a way to Make Windows® Fonts Look Better?

A user on the FreeBSD forums suggests this configuration to fix out-of-the-box look of WINE fonts, which can be slightly pixelated.

According to a post in the FreeBSD Forums, adding the following to .config/fontconfig/fonts.conf will add anti-aliasing and make text more readable.

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd>"


  <!-- antialias all fonts -->
  <match target="font">
    <edit name="antialias" mode="assign"><bool>true</bool></edit>>
    <edit name="hinting" mode="assign"><bool>true</bool></edit>>
    <edit name="hintstyle" mode="assign"><const>hintslight</const></edit>>
    <edit name="rgba" mode="assign"><const>rgb</const></edit>>
</fontconfig> Does Having Windows® Installed Elsewhere on a System Help WINE Operate?

It may, depending on the application being run. As mentioned in the section describing winecfg, some built-in WINE DLLs and other libraries can be overridden by providing a path to an alternate version. Provided the Windows® partition or drive is mounted to the FreeBSD system and accessible to the user, configuring some of these overrides will use native Windows® libraries and may decrease the chance of unexpected behavior.

13.8.3. Application-Specific Where is the Best Place to see if Application X Works on WINE?

The first step in determining compatibility should be the WINE AppDB. This is a compilation of reports of programs working (or not) on all supported platforms, although (as previously mentioned), solutions for one platform are often applicable to others. Is There Anything That Will Help Games Run Better?

Perhaps. Many Windows® games rely on DirectX, a proprietary Microsoft graphics layer. However there are projects in the open source community attempting to implement support for this technology.

The dxvk project, which is an attempt to implement DirectX using the FreeBSD-compatible Vulkan graphics sub-system, is one such. Although its primary target is WINE on Linux, some FreeBSD users report compiling and using dxvk.

In addition, work is under way on a wine-proton port. This will bring the work of Valve, developer of the Steam gaming platform, to FreeBSD. Proton is a distribution of WINE designed to allow many Windows® games to run on other operating systems with minimal setup. Is There Anywhere FreeBSD WINE Users Gather to Exchange Tips and Tricks?

There are plenty of places FreeBSD users discuss issues related to WINE that can be searched for solutions:

13.8.4. Other OS Resources

There are a number of resources focused on other operating systems that may be useful for FreeBSD users:

  • The WINE Wiki has a wealth of information on using WINE, much of which is applicable across many of WINE’s supported operating systems.

  • Similarly, the documentation available from other OS projects can also be of good value. The WINE page on the Arch Linux Wiki is a particularly good example, although some of the "Third-party applications" (i.e., "companion applications") are obviously not available on FreeBSD.

  • Finally, Codeweavers (a developer of a commercial version of WINE) is an active upstream contributor. Oftentimes answers to questions in their support forum can be of aid in troubleshooting problems with the open source version of WINE.

Part III: System Administration

The remaining chapters cover all aspects of FreeBSD system administration. Each chapter starts by describing what will be learned as a result of reading the chapter, and also details what the reader is expected to know before tackling the material.

These chapters are designed to be read as the information is needed. They do not need to be read in any particular order, nor must all of them be read before beginning to use FreeBSD.

Chapter 14. Configuration, Services, Logging and Power Management

14.1. 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.

Before reading this chapter, you should:

After reading this chapter, you will know:

  • How to use the various configuration files in /etc.

  • The basics of rc.conf configuration and /usr/local/etc/rc.d startup scripts.

  • How to tune FreeBSD using sysctl(8) variables.

  • How to configure the power management in FreeBSD.

14.2. Configuration Files

FreeBSD maintains a clear separation between the base system and third party applications and therefore this affects where the configuration files of these applications are located.

FreeBSD base system configuration is located at the /etc directory, and the /usr/local/etc directory contains all the configuration files of the applications installed on the system through the ports collection and packages.

The kernel state configuration is located in /etc/sysctl.conf. In the section The sysctl utility, the operation of sysctl(8) will be explained in more detail.

For more information about the FreeBSD file system structure refer to hier(7).

As a general rule, configuration files do not use a standard on what syntax they must follow. Although it is true that the # character is normally used to comment a line and that each line has a configuration variable.

Some applications like pkg(8) are starting to use the Universal Configuration Language (UCL).

14.2.1. The /etc directory

The /etc directory contains all of the FreeBSD base system configuration files that are responsible for configuring FreeBSD.

Extreme caution must be taken when modifying files in the /etc directory; misconfiguration could make FreeBSD unbootable or malfunction.


System configuration files and scripts.


Default system configuration files, see rc(8) for more information.


fstab(5) contains descriptive information about the various file systems.


Extra sendmail(8) configuration and other MTA configuration files.


mtree configuration files, see man: mtree[8] for more information.


Configuration files for the Pluggable Authentication Modules (PAM) library.


Scripts that are run daily, weekly, and monthly, via cron(8), see periodic(8) for more information.


System and daemon startup/control scripts, see rc(8) for more information.


Contains descriptive information about the local host name, configuration details for any potential network interfaces and which services should be started up at system initial boot time. More information in Managing System-Specific Configuration


OpenBSM audit configuration files, see audit(8) for more information.


ppp configuration files, see ppp(8) for more information.


OpenSSH configuration files, see ssh(1) for more information.


OpenSSL configuration files.


Contains settings for the kernel. More information in The sysctl utility

14.2.2. The sysctl utility

The sysctl(8) utility is used to make changes to a running FreeBSD system.

The sysctl(8) utility retrieves kernel state and allows processes with appropriate privilege to set kernel state. The state to be retrieved or set is described using a "Management Information Base" ("MIB") style name, described as a dotted set of components.

Table 23. Management Information Base


"Magic" numbers


Kernel functions and features


virtual memory






Debugging parameters




Machine dependent




POSIX 1003.1B

At its core, sysctl(8) serves two functions: to read and to modify system settings.

To view all readable variables:

% sysctl -a

The output should be similar to the following:

kern.ostype: FreeBSD
vm.swap_enabled: 1
vm.overcommit: 0
vm.domain.0.pidctrl.kdd: 8
vm.domain.0.pidctrl.kid: 4
vm.domain.0.pidctrl.kpd: 3
vfs.zfs.sync_pass_rewrite: 2
vfs.zfs.sync_pass_dont_compress: 8
vfs.zfs.sync_pass_deferred_free: 2

To read a particular variable, specify its name:

% sysctl kern.maxproc

The output should be similar to the following:

kern.maxproc: 1044

The Management Information Base (MIB) is hierarchical and hence, specifying a prefix prints all the nodes hanging from it:

% sysctl net

The output should be similar to the following: 8192 8192
net.local.dgram.recvspace: 16384
net.local.dgram.maxdgram: 2048
net.local.seqpacket.recvspace: 8192
net.local.seqpacket.maxseqpacket: 8192
net.local.sockcount: 60
net.local.taskcount: 25
net.local.recycled: 0
net.local.deferred: 0
net.local.inflight: 0
net.inet.ip.portrange.randomtime: 1
net.inet.ip.portrange.randomcps: 9999

To set a particular variable, use the variable=value syntax:

# sysctl kern.maxfiles=5000

The output should be similar to the following:

kern.maxfiles: 2088 -> 5000

To keep the configuration after a reboot it is necessary to add these variables to the /etc/sysctl.conf file as explained below.

14.2.3. The /etc/sysctl.conf file

The configuration file for sysctl(8), /etc/sysctl.conf, looks much like /etc/rc.conf.

Values are set using a variable=value syntax.

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 /etc/sysctl.conf:

# Do not log fatal signal exits (e.g., sig 11)

# Prevent users from seeing information about processes that
# are being run under another UID.

To obtain more information about what function a particular sysctl has, the following command can be executed:

% sysctl -d kern.dfldsiz

The output should be similar to the following:

kern.dfldsiz: Initial data size limit

14.2.4. Managing System-Specific Configuration

The principal location for system configuration information is /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 rc* files.

The entries in /etc/rc.conf override the default settings in /etc/defaults/rc.conf.

The file /etc/defaults/rc.conf containing the default settings should not be edited. Instead, all system-specific changes should be made to /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 /etc/rc.conf.local.

For example, these entries in /etc/rc.conf apply to all systems:


Whereas these entries in /etc/rc.conf.local apply to this system only:


Distribute /etc/rc.conf to every system using an application such as rsync or puppet, while /etc/rc.conf.local remains unique.

Upgrading the system will not overwrite /etc/rc.conf, so system configuration information will not be lost.

Both /etc/rc.conf and /etc/rc.conf.local are parsed by sh(1). This allows system operators to create complex configuration scenarios. Refer to rc.conf(5) for further information on this topic.

14.3. Managing Services in FreeBSD

FreeBSD uses the rc(8) system of startup scripts during system initialization and for managing services.

The scripts listed in /etc/rc.d provide basic services which can be controlled with the start, stop, and restart options to service(8).

A basic script may look similar to the following:

# PROVIDE: utility
# KEYWORD: shutdown

. /etc/rc.subr



load_rc_config $name

# SET THEM IN THE /etc/rc.conf FILE

run_rc_command "$1"

Refer to this article for instructions on how to create custom rc(8) scripts.

14.3.1. 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 security/openssh-portable or www/nginx are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting services.

Since the 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 /etc/rc.conf variable is set.

So the first step to start a service, like for example www/nginx is to add it to /etc/rc.conf by executing the following command:

# sysrc nginx_enable="YES"

Then nginx can be started executing the following command:

# service nginx start

To start, stop or restart a service regardless of the settings in /etc/rc.conf, these commands should be prefixed with "one". For instance, to start www/nginx regardless of the current /etc/rc.conf setting, execute the following command:

# service nginx onestart

14.3.2. Status of a Service

To determine if a service is running, use the status subcommand.

For example, to verify that www/nginx is running:

# service nginx status

The output should be similar to the following:

nginx is running as pid 27871.

14.3.3. Reload a Service

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.

Not all services support this feature.

The rc(8) system is used for network services and it also contributes to most of the system initialization. For instance, when the /etc/rc.d/bgfsck script is executed, it prints out the following message:

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, yp(8) and other RPC-based services may fail to start until after the rpcbind(8) service has started.

Additional information can be found in rc(8) and rc.subr(8).

14.3.4. Using Services to Start Services

Other services can be started using inetd(8). Working with inetd(8) and its configuration is described in depth in “The inetd Super-Server”.

In some cases, it may make more sense to use cron(8) to start system services. This approach has a number of advantages as cron(8) runs these processes as the owner of the crontab(5). This allows regular users to start and maintain their own applications.

The @reboot feature of cron(8), may be used in place of the time specification. This causes the job to run when cron(8) is started, normally during system initialization.

14.4. Cron and Periodic

Scheduling tasks to run at a certain day or time is a very common task on FreeBSD. The tool in charge of performing this task is cron(8).

In addition to tasks that can be scheduled by the user via cron(8), FreeBSD performs routine background tasks managed by periodic(8).

14.4.1. Cron

The cron(8) utility runs in the background and regularly checks /etc/crontab for tasks to execute and searches /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 crontab(5). The format of the system crontab, /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 crontab which can be used to schedule tasks that do not exist in the system crontab.

Here is a sample entry from the system crontab, /etc/crontab:

# /etc/crontab - root's crontab for FreeBSD
# $FreeBSD$ (1)
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin (2)
#minute hour    mday    month   wday    who     command (3)
# Save some entropy so that /dev/random can re-seed on boot.
*/11    *       *       *       *       operator /usr/libexec/save-entropy (4)
# Rotate log files every hour, if necessary.
0       *       *       *       *       root    newsyslog
# Perform daily/weekly/monthly maintenance.
1       3       *       *       *       root    periodic daily
15      4       *       *       6       root    periodic weekly
30      5       1       *       *       root    periodic monthly
# Adjust the time zone if the CMOS clock keeps local time, as opposed to
# UTC time.  See adjkerntz(8) for details.
1,31    0-5     *       *       *       root    adjkerntz -a
1Lines 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.
2The 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.
3This 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.
4This entry defines the values for this cron job. The */11, followed by several more * characters, specifies that /usr/libexec/save-entropy is invoked by operator every eleven 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.

14.4.2. Creating a User Crontab

To create a user crontab, invoke crontab in editor mode:

% 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:

# 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:

0 14 * * * /home/user/bin/

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:

env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/user LOGNAME=user /home/user/bin/

The environment set by cron is discussed in 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:

% crontab -l

The output should be similar to the following:

0 14 * * * /home/user/bin/

To remove all of the cron jobs in a user crontab:

% crontab -r

The output should be similar to the following:

remove crontab for user? y

14.4.3. Periodic

FreeBSD provides a set of system management scripts to check status of various subsystems, perform security-related checks, rotate log files, etc. These scripts are run on a periodic basis: daily. weekly, or monthly. The management of these tasks is performed by periodic(8) and its configuration resides in periodic.conf(5). The periodic tasks are initiated by entries in the system crontab, shown above.

Scripts executed by periodic(8) are located in /etc/periodic/ for base utilities and in /usr/local/etc/periodic/ for third-party software.

They are organized in 4 subdirectories, daily, weekly, monthly and security.

14.4.4. Enable or Disable Periodic Tasks

FreeBSD has some scripts enabled by default to run periodically.

To enable or disable a task, the first step is to edit /etc/periodic.conf executing the following command:

# ee /etc/periodic.conf

And then to enable, for example, daily_status_zfs_enable put the following content in the file:


To disable a task that is active by default, all that needs to be done is to change YES to NO.

14.4.5. Configuring the Output of Periodic Tasks

In /etc/periodic.conf the variables daily_output, weekly_output and monthly_output specifies where to send the results of the script execution.

By default the output of the periodic scripts are emailed to root, and therefore it is best to read root’s mail or alias root to a mailbox that is monitored.

To send the results to another email or to other emails, add the email addresses separated by spaces to /etc/periodic.conf:


To log periodic output instead of receiving it as email, add the following lines to /etc/periodic.conf. newsyslog(8) will rotate these files at the appropriate times:


14.5. 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(8), to manage logging. By default, syslogd is enabled and started when the system boots.

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.

14.5.1. Configuring Local Logging

The configuration file, /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 /etc/syslog.conf from FreeBSD:

# $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 (1)
*.notice;authpriv.none;kern.debug;;mail.crit;news.err   /var/log/messages
security.*                                      /var/log/security;                         /var/log/auth.log                                       /var/log/maillog (2)
cron.*                                          /var/log/cron
*.=debug                                        /var/log/debug.log (3)
*.emerg                                         *                                     /var/log/daemon.log
# uncomment this to log all writes to /dev/console to /var/log/console.log
# touch /var/log/console.log and chmod it to mode 600 before it will work                                   /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
# *.>=notice                                    /var/log/devd.log (4)
include                                         /etc/syslog.d
include                                         /usr/local/etc/syslog.d
1Matches 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 (/dev/console).
2Matches all messages from the mail facility at level info or above and logs the messages to /var/log/maillog.
3Uses a comparison flag (=) to only match messages at level debug and logs them to /var/log/debug.log.
4Is 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 devd(8) are logged to /var/log/devd.log.

For more information about /etc/syslog.conf, its syntax, and more advanced usage examples, see syslog.conf(5).

14.5.2. Logging Facilities

A facility describes the part of the system generating the message. Facilities are a way of separating the different messages so that it is easier for the user to consult the logs.

Table 24. syslog facilities


The authorization system: login(1), su(1), getty(8), etc.


The same as auth, but logged to a file readable only by root.


Messages written to /dev/console by the kernel console output driver.


Messages written by the cron(8) daemon.


System daemons, such as routed(8), that are not provided for explicitly by other facilities.


The file transfer protocol daemons: ftpd(8), tftpd(8).


Messages generated by the kernel. These cannot be generated by any user processes.


The line printer spooling system: lpr(1), lpc(8), lpd(8), etc.


The mail system.


This facility adds a record every 20 minutes.


The network news system.


The network time protocol system.


Security subsystems, such as ipfw(4).


Messages generated internally by syslogd(8).


Messages generated by random user processes. This is the default facility identifier if none is specified.


The Unix-to-Unix Copy system. An ancient protocol. Really weird to see messages from this facility.

local0 through local7

Reserved for local use.

14.5.3. Logging Levels

The level describes the severity of the message, and is a keyword from the following ordered list (higher to lower):

Table 25. syslog levels


A panic condition. This is normally broadcast to all users.


A condition that should be corrected immediately, such as a corrupted system database.


Critical conditions, e.g., hard device errors.




Warning messages.


Conditions that are not error conditions, but should possibly be handled specially.


Informational messages.


Messages that contain information normally of use only when debugging a program.


This special level disables a particular facility.

14.5.4. Read Log Messages

By default FreeBSD log files use the format rfc3164, also known as The BSD syslog Protocol. Learn more about other formats and how to use them at syslog(8).

Typically the logs have the following syntax:

date time hostname program[pid]: the message

The output of the /var/log/cron file will be used as an example:

Jul 16 12:40:00 FreeBSD /usr/sbin/cron[81519]: (root) CMD (/usr/libexec/atrun)
Jul 16 12:44:00 FreeBSD /usr/sbin/cron[83072]: (operator) CMD (/usr/libexec/save-entropy)

Verbose logging, so the facility and the level on each message will be added, can be enabled in syslog(8) by running the following command:

# sysrc syslogd_flags="-vv"

Once the function is activated, the facility and the level will be displayed in the log as shown in the following example:

Jul 16 17:40:00 <> FreeBSD /usr/sbin/cron[1016]: (root) CMD (/usr/libexec/atrun)
Jul 16 17:44:00 <> FreeBSD /usr/sbin/cron[1030]: (operator) CMD (/usr/libexec/save-entropy)

14.5.5. Log Management and Rotation

Log files can grow quickly, taking up disk space and making it more difficult to locate useful information.

In FreeBSD, newsyslog(8) is used to manage log files and attempt to mitigate this.

This built-in program periodically rotates and compresses log files, and optionally creates missing log files and signals programs when log files are moved.

Since newsyslog is run from cron(8), it cannot rotate files more often than it is scheduled to run from cron(8). In the default configuration, it runs every hour.

Here is the default configuration in FreeBSD, more information in newsyslog.conf(5):

# 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.
# 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/auth.log                       600  7     1000 @0101T JC
/var/log/console.log                    600  5     1000 *     J
/var/log/cron                           600  3     1000 *     JC
/var/log/daily.log                      640  7     *    @T00  JN
/var/log/debug.log                      600  7     1000 *     JC
/var/log/init.log                       644  3     1000 *     J
/var/log/kerberos.log                   600  7     1000 *     J
/var/log/maillog                        640  7     *    @T00  JC
/var/log/messages                       644  5     1000 @0101T JC
/var/log/monthly.log                    640  12    *    $M1D0 JN
/var/log/devd.log                       644  3     1000 *     JC
/var/log/security                       600  10    1000 *     JC
/var/log/utx.log                        644  3     *    @01T05 B
/var/log/weekly.log                     640  5     *    $W6D0 JN
/var/log/daemon.log                     644  5     1000 @0101T JC

<include> /etc/newsyslog.conf.d/[!.]*.conf
<include> /usr/local/etc/newsyslog.conf.d/[!.]*.conf
  1. logfilename - Name of the system log file to be archived.

  2. [owner:group] - This optional field specifies the owner and group for the archive file.

  3. mode - Specify the file mode of the log file and archives. Valid mode bits are 0666. (That is, read and write permissions for the rotated log may be specified for the owner, group, and others.)

  4. count - Specify the maximum number of archive files which may exist.

  5. size - When the size of the log file reaches size in kilobytes, the log file will be trimmed as described above. If this field contains an asterisk ('*'), the log file will not be trimmed based on size.

  6. when - Consist of an interval, a specific time, or both. Supported options in newsyslog.conf(5).

  7. flags - Indicates the flags that newsyslog accepts, supported options in newsyslog.conf(5).

  8. [/pid_file] - This optional field specifies the file name containing a daemon’s process ID or to find a group process ID.

  9. [sig_num] - This optional field specifies the signal that will be sent to the daemon process.

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.

14.5.6. 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, will collect logging information for the local network.

Host B, named, 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 /etc/hosts. Proper name resolution is required so that log entries are not rejected by the logging server.

On the log server, edit /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 /var/log/logclient.log.

Example 22. Sample Log Server Configuration
*.*     /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 syslog.conf(5).

Next, execute the following commands:

# sysrc syslogd_enable="YES"
# sysrc syslogd_flags="-a -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 syslogd(8) for a full list of possible options.

Finally, create the log file:

# touch /var/log/logclient.log

At this point, syslogd should be restarted and verified:

# 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 /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, execute the following commands on the logging client:

# sysrc syslogd_enable="YES"
# sysrc 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 /etc/syslog.conf. In this example, all logged facilities are sent to a remote system, denoted by the @ symbol, with the specified hostname:


After saving the edit, restart syslogd for the changes to take effect:

# service syslogd restart

To test that log messages are being sent across the network, use logger(1) on the client to send a message to syslogd:

# logger "Test message from logclient"

This message should now exist both in /var/log/messages on the client and /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 /etc/rc.conf. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or /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, /var/log/logclient.log on the logging server is empty and /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:

sysrc syslogd_flags="-d -a -v -v"
# service syslogd restart

Debugging data similar to the following will flash on the console immediately after the restart:

logmsg: pri 56, flags 4, from, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from, msg syslogd: kernel boot file is /boot/kernel/kernel
Logging to FILE /var/log/messages
syslogd: kernel boot file is /boot/kernel/kernel
validate: dgram from IP, port 514, name;
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:

# service syslogd restart

The output should be similar to the following:

logmsg: pri 56, flags 4, from, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from, msg syslogd: kernel boot file is /boot/kernel/kernel
syslogd: kernel boot file is /boot/kernel/kernel
logmsg: pri 166, flags 17, from,
msg Dec 10 20:55:02 <syslog.err> syslogd: exiting on signal 2
validate: dgram from IP, port 514, name;
accepted in rule 0.
logmsg: pri 15, flags 0, from, 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 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 newsyslog.conf(5) for additional information.

14.6. 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 run some actions triggered by events related to those limits.

14.6.1. ACPI configuration

On FreeBSD the management of these resources is managed by the acpi(4) kernel device.

In FreeBSD the acpi(4) driver is loaded by default at system boot.

This driver cannot be unloaded after boot because the system bus uses it for various hardware interactions.

In addition to acpi(4), FreeBSD has several dedicated kernel modules for various ACPI vendor subsystems. These modules will add some extra functionality like fan speed, keyboard backlit or screen brightness.

The list can be obtained by running the following command:

% ls /boot/kernel | grep acpi

The output should be similar to the following:


In the event that, for example, an IBM/Lenovo laptop is used, it will be necessary to load the module acpi_ibm(4) by executing the following command:

# kldload acpi_ibm

And add this line to /boot/loader.conf to load it at boot:


14.6.2. CPU Power Management

CPU is the most consuming part of the system. Knowing how to improve CPU efficiency is a fundamental part of our system in order to save energy.

In order to make proper use of the machine’s resources in a correct way, FreeBSD supports technologies such as Intel Turbo Boost, AMD Turbo Core, Intel Speed Shift among others through the use of powerd(8) and cpufreq[4].

The first step will be to obtain the CPU information by executing the following command:

% sysctl dev.cpu.0 (1)
1In this case the 0 digit represents the first core of the CPU.

The output should be similar to the following:

dev.cpu.0.cx_method: C1/mwait/hwc C2/mwait/hwc C3/mwait/hwc/bma
dev.cpu.0.cx_usage_counters: 3507294 0 0
dev.cpu.0.cx_usage: 100.00% 0.00% 0.00% last 3804us
dev.cpu.0.cx_lowest: C3 (1)
dev.cpu.0.cx_supported: C1/1/1 C2/2/1 C3/3/57 (2)
dev.cpu.0.freq_levels: 2267/35000 2266/35000 1600/15000 800/12000 (3)
dev.cpu.0.freq: 1600 (4)
dev.cpu.0.temperature: 40.0C (5)
dev.cpu.0.coretemp.throttle_log: 0
dev.cpu.0.coretemp.tjmax: 105.0C
dev.cpu.0.coretemp.resolution: 1 65
dev.cpu.0.%parent: acpi0
dev.cpu.0.%pnpinfo: _HID=none _UID=0 _CID=none
dev.cpu.0.%location: handle=\_PR_.CPU0
dev.cpu.0.%driver: cpu
dev.cpu.0.%desc: ACPI CPU
1Lowest Cx state to use for idling the CPU.
2CPU supported Cx states.
3Currently available levels for the CPU (frequency/power usage).
4Current active CPU frequency in MHz.
5Current temperature of the CPU.

If the temperature information is not displayed, load the coretemp(4) module. In case of using an AMD CPU, load the amdtemp(4) module.

Once the CPU information is available the easiest way to configure power saving is to let powerd(8) take over.

Enable powerd(8) service in /etc/rc.conf to start at system boot:

# sysrc powerd_enable=YES

It will also be necessary to indicate certain parameters to powerd(8) to tell it how to manage the state of the CPU executing the following command:

# sysrc powerd_flags="-a hiadaptive -i 25 -r 85 -N"
  1. -a: Selects the mode to use while on AC power.

  2. hiadaptive: Operation mode. More info at powerd(8).

  3. -i: Specifies the CPU load percent level when adaptive mode should begin to degrade performance to save power.

  4. -r: Specifies the CPU load percent level where adaptive mode should consider the CPU running and increase performance.

  5. -N: Treat "nice" time as idle for the purpose of load calculation; i.e., do not increase the CPU frequency if the CPU is only busy with "nice" processes.

And then enable the service executing the following command:

# service powerd start

14.6.3. CPU Frequency Control

FreeBSD includes a generic cpufreq(4) driver to allow the administrator, or software such as powerd(8) and sysutils/powerdxx, to manage the frequency of the CPU to achieve the desired balance between performance and economy. A lower setting will save power while reducing the heat generated by the CPU. A higher setting will increase performance at the cost of using additional power and generating more heat.

14.6.4. Intel® Enhanced Speed Step™

The Intel® Enhanced Speed Step™ driver, est(4), replaces the generic cpufreq(4) driver for CPUs that provide this feature. The CPU frequency can be statically adjusted using sysctl(8), or with the /etc/rc.d/power_profile startup script. Additional software, such as powerd(8) or sysutils/powerdxx, can be used to automatically adjust the CPU frequency based on processor utilization.

Each supported frequency, along with its expected power consumption, can be listed by examining the sysctl(3) tree:

# sysctl dev.cpufreq.0.freq_driver dev.cpu.0.freq_levels dev.cpu.0.freq

The output should be similar to the following:

dev.cpufreq.0.freq_driver: est0
dev.cpu.0.freq_levels: 3001/53000 3000/53000 2900/50301 2700/46082 2600/43525 2400/39557 2300/37137 2100/33398 2000/31112 1800/27610 1700/25455 1500/22171 1400/20144 1200/17084 1100/15181 900/12329 800/10550
dev.cpu.0.freq: 800

A frequency 1 MHz higher than the maximum frequency of the CPU indicates the Intel® Turbo Boost™ feature.

14.6.5. Intel Speed Shift™

Users running newer Intel® CPUs may find some differences in dynamic frequency control when upgrading to FreeBSD 13. A new driver for the Intel® Speed Shift™ feature set, available on certain SKUs, exposes the ability for the hardware to dynamically vary the core frequencies, including on a per core basis. FreeBSD 13 comes with the hwpstate_intel(4) driver to automatically enable Speed Shift™ control on equipped CPUs, replacing the older Enhanced Speed Step™ est(4) driver. The sysctl(8) dev.cpufreq.%d.freq_driver will indicate if the system is using Speed Shift.

To determine which frequency control driver is being used, examining the dev.cpufreq.0.freq_driver oid.

# sysctl dev.cpufreq.0.freq_driver

The output should be similar to the following:

dev.cpufreq.0.freq_driver: hwpstate_intel0

This indicates that the new hwpstate_intel(4) driver is in use. On such systems, the oid dev.cpu.%d.freq_levels will show only the maximum CPU frequency, and will indicate a power consumption level of -1.

The current CPU frequency can be determined by examining the dev.cpu.%d.freq oid.

# sysctl dev.cpu.0.freq_levels dev.cpu.0.freq

The output should be similar to the following:

dev.cpu.0.freq_levels: 3696/-1
dev.cpu.0.freq: 898

For more information, including on how to balance performance and energy use, and on how to disable this driver, refer to the man page hwpstate_intel(4).

Users accustomed to using powerd(8) or sysutils/powerdxx will find these utilities have been superseded by the hwpstate_intel(4) driver and no longer work as expected.

14.6.6. Graphics Card Power Management

Graphics cards have become a fundamental part of computing in recent years. Some graphics cards may have excessive power consumption. FreeBSD allows certain configurations to improve power consumption.

In case of using a Intel® graphics card with the graphics/drm-kmod driver these options can be added to /boot/loader.conf:

compat.linuxkpi.fastboot=1 (1)
compat.linuxkpi.enable_dc=2 (2)
compat.linuxkpi.enable_fbc=1 (3)
1Try to skip unnecessary mode sets at boot time.
2Enable power-saving display C-states.
3Enable frame buffer compression for power savings

14.6.7. Suspend/Resume

The suspend/resume function allows the machine to be kept in a state in which there is no a big energy consumption and allows the system to be resumed without having to lose the state of the running programs.

In order for the suspend/resume functionality to work correctly the graphics drivers must be loaded on the system. In non-KMS-supported graphics cards sc(4) must be used not to break the suspend/resume functionality.

More information about which driver to use and how to configure it can be found at the The X Window System chapter.

acpi(4) supports the next list of sleep states:

Table 26. Supported Sleep States
S1Quick suspend to RAM. The CPU enters a lower power state, but most peripherals are left running.


Lower power state than S1, but with the same basic characteristics. Not supported by many systems.

S3 (Sleep mode)

Suspend to RAM. Most devices are powered off, and the system stops running except for memory refresh.

S4 (Hibernation)

Suspend to disk. All devices are powered off, and the system stops running. When resuming, the system starts as if from a cold power on. Not yet supported by FreeBSD.


System shuts down cleanly and powers off. Configuring Suspend/Resume

The first step will be to know which type of sleep states supports the hardware we are using executing the following command:

% sysctl hw.acpi.supported_sleep_state

The output should be similar to the following:

hw.acpi.supported_sleep_state: S3 S4 S5

As stated above FreeBSD does not yet support the S4 state.

acpiconf(8) can be used to check if the S3 state works correctly by running the following command, if it succeeds, the screen should go black and the machine will turn off:

# acpiconf -s 3

In the vast majority of cases the Suspend/Resume functionality wants to be used on a laptop.

FreeBSD can be configured to enter the S3 state when closing the lid by adding the following line to the /etc/sysctl.conf file.

hw.acpi.lid_switch_state=S3 Troubleshooting in Suspend/Resume

A lot of effort has been made to make the Suspend and Resume functions work properly and in the best way on FreeBSD. But currently the Suspend and Resume functions only work properly on some specific laptops.

Some checks can be done in case it doesn’t work properly.

In some cases it is enough to turn off the bluetooth. In others it is enough loading the correct driver for the graphics card, etc.

In case it doesn’t work correctly, some tips can be found on the FreeBSD Wiki in the section Suspend/Resume.

14.7. Adding Swap Space

Sometimes a FreeBSD 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 file system.

For information on how to encrypt swap space, which options exist, and why it should be done, refer to “Encrypting Swap”.

14.7.1. Swap on a New Hard Drive or Existing Partition

Adding a new drive for swap gives better performance than using a partition on an existing drive. Setting up partitions and drives is explained in Adding Disks while Designing the Partition Layout discusses partition layouts and swap partition size considerations.

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.

swapon(8) can be used to add a swap partition to the system executing the following command:

# swapon /dev/ada1p2

To automatically add this swap partition on boot, add an entry to /etc/fstab:

/dev/ada1p2 none swap sw 0 0

See fstab(5) for an explanation of the entries in /etc/fstab.

14.7.2. Creating a Swap File

These examples create a 512M swap file called /usr/swap0.

Swap files on ZFS file systems are strongly discouraged, as swapping can lead to system hangs.

The first step is to create the swap file:

# dd if=/dev/zero of=/usr/swap0 bs=1m count=512

The second step is to put the proper permissions on the new file:

# chmod 0600 /usr/swap0

The third step is to inform the system about the swap file by adding a line to /etc/fstab:

md none swap sw,file=/usr/swap0,late 0 0

Swap space will be added on system startup. To add swap space immediately, use swapon(8):

# swapon -aL

Chapter 15. The FreeBSD Booting Process

15.1. Synopsis

The process of starting a computer and loading the operating system is referred to as "the bootstrap process", or "booting". FreeBSD’s boot process provides a great deal of flexibility in customizing what happens when the system starts, including the ability to select from different operating systems installed on the same computer, different versions of the same operating system, or a different installed kernel.

This chapter details the configuration options that can be set. It demonstrates how to customize the FreeBSD boot process, including everything that happens until the FreeBSD kernel has started, probed for devices, and started init(8). This occurs when the text color of the boot messages changes from bright white to grey.

After reading this chapter, you will recognize:

  • The components of the FreeBSD bootstrap system and how they interact.

  • The options that can be passed to the components in the FreeBSD bootstrap in order to control the boot process.

  • The basics of setting device hints.

  • How to boot into single- and multi-user mode and how to properly shut down a FreeBSD system.

This chapter only describes the boot process for FreeBSD running on x86 and amd64 systems.

15.2. FreeBSD Boot Process

Turning on a computer and starting the operating system poses an interesting dilemma. By definition, the computer does not know how to do anything until the operating system is started. This includes running programs from the disk. If the computer can not run a program from the disk without the operating system, and the operating system programs are on the disk, how is the operating system started?

This problem parallels one in the book The Adventures of Baron Munchausen. A character had fallen part way down a manhole, and pulled himself out by grabbing his bootstraps and lifting. In the early days of computing, the term bootstrap was applied to the mechanism used to load the operating system. It has since become shortened to "booting".

On x86 hardware, the Basic Input/Output System (BIOS) is responsible for loading the operating system. The BIOS looks on the hard disk for the Master Boot Record (MBR), which must be located in a specific place on the disk. The BIOS has enough knowledge to load and run the MBR, and assumes that the MBR can then carry out the rest of the tasks involved in loading the operating system, possibly with the help of the BIOS.

FreeBSD provides for booting from both the older MBR standard, and the newer GUID Partition Table (GPT). GPT partitioning is often found on computers with the Unified Extensible Firmware Interface (UEFI). However, FreeBSD can boot from GPT partitions even on machines with only a legacy BIOS with gptboot(8). Work is under way to provide direct UEFI booting.

The code within the MBR is typically referred to as a boot manager, especially when it interacts with the user. The boot manager usually has more code in the first track of the disk or within the file system. Examples of boot managers include the standard FreeBSD boot manager boot0, also called Boot Easy, and GNU GRUB, which is used by many Linux® distributions.

Users of GRUB should refer to GNU-provided documentation.

If only one operating system is installed, the MBR searches for the first bootable (active) slice on the disk, and then runs the code on that slice to load the remainder of the operating system. When multiple operating systems are present, a different boot manager can be installed to display a list of operating systems so the user can select one to boot.

The remainder of the FreeBSD bootstrap system is divided into three stages. The first stage knows just enough to get the computer into a specific state and run the second stage. The second stage can do a little bit more, before running the third stage. The third stage finishes the task of loading the operating system. The work is split into three stages because the MBR puts limits on the size of the programs that can be run at stages one and two. Chaining the tasks together allows FreeBSD to provide a more flexible loader.

The kernel is then started and begins to probe for devices and initialize them for use. Once the kernel boot process is finished, the kernel passes control to the user process init(8), which makes sure the disks are in a usable state, starts the user-level resource configuration which mounts file systems, sets up network cards to communicate on the network, and starts the processes which have been configured to run at startup.

This section describes these stages in more detail and demonstrates how to interact with the FreeBSD boot process.

15.2.1. The Boot Manager

The boot manager code in the MBR is sometimes referred to as stage zero of the boot process. By default, FreeBSD uses the boot0 boot manager.

The MBR installed by the FreeBSD installer is based on /boot/boot0. The size and capability of boot0 is restricted to 446 bytes due to the slice table and 0x55AA identifier at the end of the MBR. If boot0 and multiple operating systems are installed, a message similar to this example will be displayed at boot time:

Example 23. boot0 Screenshot
F1 Win
F2 FreeBSD

Default: F2

Other operating systems will overwrite an existing MBR if they are installed after FreeBSD. If this happens, or to replace the existing MBR with the FreeBSD MBR, use the following command:

# fdisk -B -b /boot/boot0 device

where device is the boot disk, such as ad0 for the first IDE disk, ad2 for the first IDE disk on a second IDE controller, or da0 for the first SCSI disk. To create a custom configuration of the MBR, refer to boot0cfg(8).

15.2.2. Stage One and Stage Two

Conceptually, the first and second stages are part of the same program on the same area of the disk. Due to space constraints, they have been split into two, but are always installed together. They are copied from the combined /boot/boot by the FreeBSD installer or bsdlabel.

These two stages are located outside file systems, in the first track of the boot slice, starting with the first sector. This is where boot0, or any other boot manager, expects to find a program to run which will continue the boot process.

The first stage, boot1, is very simple, since it can only be 512 bytes in size. It knows just enough about the FreeBSD bsdlabel, which stores information about the slice, to find and execute boot2.

Stage two, boot2, is slightly more sophisticated, and understands the FreeBSD file system enough to find files. It can provide a simple interface to choose the kernel or loader to run. It runs loader, which is much more sophisticated and provides a boot configuration file. If the boot process is interrupted at stage two, the following interactive screen is displayed:

Example 24. boot2 Screenshot
>> FreeBSD/i386 BOOT
Default: 0:ad(0,a)/boot/loader

To replace the installed boot1 and boot2, use bsdlabel, where diskslice is the disk and slice to boot from, such as ad0s1 for the first slice on the first IDE disk:

# bsdlabel -B diskslice

If just the disk name is used, such as ad0, bsdlabel will create the disk in "dangerously dedicated mode", without slices. This is probably not the desired action, so double check the diskslice before pressing Return.

15.2.3. Stage Three

The loader is the final stage of the three-stage bootstrap process. It is located on the file system, usually as /boot/loader.

The loader is intended as an interactive method for configuration, using a built-in command set, backed up by a more powerful interpreter which has a more complex command set.

During initialization, loader will probe for a console and for disks, and figure out which disk it is booting from. It will set variables accordingly, and an interpreter is started where user commands can be passed from a script or interactively.

The loader will then read /boot/loader.rc, which by default reads in /boot/defaults/loader.conf which sets reasonable defaults for variables and reads /boot/loader.conf for local changes to those variables. loader.rc then acts on these variables, loading whichever modules and kernel are selected.

Finally, by default, loader issues a 10 second wait for key presses, and boots the kernel if it is not interrupted. If interrupted, the user is presented with a prompt which understands the command set, where the user may adjust variables, unload all modules, load modules, and then finally boot or reboot. Loader Built-In Commands lists the most commonly used loader commands. For a complete discussion of all available commands, refer to loader(8).

Table 27. Loader Built-In Commands

autoboot seconds

Proceeds to boot the kernel if not interrupted within the time span given, in seconds. It displays a countdown, and the default time span is 10 seconds.

boot [-options] [kernelname]

Immediately proceeds to boot the kernel, with any specified options or kernel name. Providing a kernel name on the command-line is only applicable after an unload has been issued. Otherwise, the previously-loaded kernel will be used. If kernelname is not qualified, it will be searched under /boot/kernel and /boot/modules.


Goes through the same automatic configuration of modules based on specified variables, most commonly kernel. This only makes sense if unload is used first, before changing some variables.

help [topic]

Shows help messages read from /boot/ If the topic given is index, the list of available topics is displayed.

include filename …​

Reads the specified file and interprets it line by line. An error immediately stops the include.

load [-t type] filename

Loads the kernel, kernel module, or file of the type given, with the specified filename. Any arguments after filename are passed to the file. If filename is not qualified, it will be searched under /boot/kernel and /boot/modules.

ls [-l] [path]

Displays a listing of files in the given path, or the root directory, if the path is not specified. If -l is specified, file sizes will also be shown.

lsdev [-v]

Lists all of the devices from which it may be possible to load modules. If -v is specified, more details are printed.

lsmod [-v]

Displays loaded modules. If -v is specified, more details are shown.

more filename

Displays the files specified, with a pause at each LINES displayed.


Immediately reboots the system.

set variable, set variable=value

Sets the specified environment variables.


Removes all loaded modules.

Here are some practical examples of loader usage. To boot the usual kernel in single-user mode:

 boot -s

To unload the usual kernel and modules and then load the previous or another, specified kernel:

 load /path/to/kernelfile

Use the qualified /boot/GENERIC/kernel to refer to the default kernel that comes with an installation, or /boot/kernel.old/kernel, to refer to the previously installed kernel before a system upgrade or before configuring a custom kernel.

Use the following to load the usual modules with another kernel. Note that in this case it is not necessary the qualified name:

set kernel="mykernel"

To load an automated kernel configuration script:

 load -t userconfig_script /boot/kernel.conf

15.2.4. Last Stage

Once the kernel is loaded by either loader or by boot2, which bypasses loader, it examines any boot flags and adjusts its behavior as necessary. Kernel Interaction During Boot lists the commonly used boot flags. Refer to boot(8) for more information on the other boot flags.

Table 28. Kernel Interaction During Boot


During kernel initialization, ask for the device to mount as the root file system.


Boot the root file system from a CDROM.


Boot into single-user mode.


Be more verbose during kernel startup.

Once the kernel has finished booting, it passes control to the user process init(8), which is located at /sbin/init, or the program path specified in the init_path variable in loader. This is the last stage of the boot process.

The boot sequence makes sure that the file systems available on the system are consistent. If a UFS file system is not, and fsck cannot fix the inconsistencies, init drops the system into single-user mode so that the system administrator can resolve the problem directly. Otherwise, the system boots into multi-user mode. Single-User Mode

A user can specify this mode by booting with -s or by setting the boot_single variable in loader. It can also be reached by running shutdown now from multi-user mode. Single-user mode begins with this message:

Enter full pathname of shell or RETURN for /bin/sh:

If the user presses Enter, the system will enter the default Bourne shell. To specify a different shell, input the full path to the shell.

Single-user mode is usually used to repair a system that will not boot due to an inconsistent file system or an error in a boot configuration file. It can also be used to reset the root password when it is unknown. These actions are possible as the single-user mode prompt gives full, local access to the system and its configuration files. There is no networking in this mode.

While single-user mode is useful for repairing a system, it poses a security risk unless the system is in a physically secure location. By default, any user who can gain physical access to a system will have full control of that system after booting into single-user mode.

If the system console is changed to insecure in /etc/ttys, the system will first prompt for the root password before initiating single-user mode. This adds a measure of security while removing the ability to reset the root password when it is unknown.

Example 25. Configuring an Insecure Console in /etc/ttys
# name  getty                           type    status          comments
# If console is marked "insecure", then init will ask for the root password
# when going to single-user mode.
console none                            unknown off insecure

An insecure console means that physical security to the console is considered to be insecure, so only someone who knows the root password may use single-user mode. Multi-User Mode

If init finds the file systems to be in order, or once the user has finished their commands in single-user mode and has typed exit to leave single-user mode, the system enters multi-user mode, in which it starts the resource configuration of the system.

The resource configuration system reads in configuration defaults from /etc/defaults/rc.conf and system-specific details from /etc/rc.conf. It then proceeds to mount the system file systems listed in /etc/fstab. It starts up networking services, miscellaneous system daemons, then the startup scripts of locally installed packages.

To learn more about the resource configuration system, refer to rc(8) and examine the scripts located in /etc/rc.d.

15.3. Device Hints

During initial system startup, the boot loader(8) reads device.hints(5). This file stores kernel boot information known as variables, sometimes referred to as "device hints". These "device hints" are used by device drivers for device configuration.

Device hints may also be specified at the Stage 3 boot loader prompt, as demonstrated in Stage Three. Variables can be added using set, removed with unset, and viewed show. Variables set in /boot/device.hints can also be overridden. Device hints entered at the boot loader are not permanent and will not be applied on the next reboot.

Once the system is booted, kenv(1) can be used to dump all of the variables.

The syntax for /boot/device.hints is one variable per line, using the hash "#" as comment markers. Lines are constructed as follows:


The syntax for the Stage 3 boot loader is:

 set hint.driver.unit.keyword=value

where driver is the device driver name, unit is the device driver unit number, and keyword is the hint keyword. The keyword may consist of the following options:

  • at: specifies the bus which the device is attached to.

  • port: specifies the start address of the I/O to be used.

  • irq: specifies the interrupt request number to be used.

  • drq: specifies the DMA channel number.

  • maddr: specifies the physical memory address occupied by the device.

  • flags: sets various flag bits for the device.

  • disabled: if set to 1 the device is disabled.

Since device drivers may accept or require more hints not listed here, viewing a driver’s manual page is recommended. For more information, refer to device.hints(5), kenv(1), loader.conf(5), and loader(8).

15.4. Shutdown Sequence

Upon controlled shutdown using shutdown(8), init(8) will attempt to run the script /etc/rc.shutdown, and then proceed to send all processes the TERM signal, and subsequently the KILL signal to any that do not terminate in a timely manner.

To power down a FreeBSD machine on architectures and systems that support power management, use shutdown -p now to turn the power off immediately. To reboot a FreeBSD system, use shutdown -r now. One must be root or a member of operator in order to run shutdown(8). One can also use halt(8) and reboot(8). Refer to their manual pages and to shutdown(8) for more information.

Modify group membership by referring to “Users and Basic Account Management”.

Power management requires acpi(4) to be loaded as a module or statically compiled into a custom kernel.

Chapter 16. Security

16.1. 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 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 Mandatory Access Control and Internet firewalls are discussed in Firewalls.

16.2. Introduction

Security is everyone’s responsibility. A weak entry point in any system could allow intruders to gain access to critical information and cause havoc on an entire network. One of the core principles of information security is the CIA triad, which stands for the Confidentiality, Integrity, and Availability of information systems.

The CIA triad is a bedrock concept of computer security as customers and users expect their data to be protected. For example, a customer expects that their credit card information is securely stored (confidentiality), that their orders are not changed behind the scenes (integrity), and that they have access to their order information at all times (availability).

To provide CIA, security professionals apply a defense in depth strategy. The idea of defense in depth is to add several layers of security to prevent one single layer failing and the entire security system collapsing. For example, a system administrator cannot simply turn on a firewall and consider the network or system secure. One must also audit accounts, check the integrity of binaries, and ensure malicious tools are not installed. To implement an effective security strategy, one must understand threats and how to defend against them.

What is a threat as it pertains to computer security? Threats are not limited to remote attackers who attempt to access a system without permission from a remote location. Threats also include employees, malicious software, unauthorized network devices, natural disasters, security vulnerabilities, and even competing corporations.

Systems and networks can be accessed without permission, sometimes by accident, or by remote attackers, and in some cases, via corporate espionage or former employees. As a user, it is important to prepare for and admit when a mistake has led to a security breach and report possible issues to the security team. As an administrator, it is important to know of the threats and be prepared to mitigate them.

When applying security to systems, it is recommended to start by securing the basic accounts and system configuration, and then to secure the network layer so that it adheres to the system policy and the organization’s security procedures. Many organizations already have a security policy that covers the configuration of technology devices. The policy should include the security configuration of workstations, desktops, mobile devices, phones, production servers, and development servers. In many cases, standard operating procedures (SOPs) already exist. When in doubt, ask the security team.

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.

16.2.1. 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:

# pw lock toor

The second method is to prevent login access by changing the shell to /usr/sbin/nologin. Only the superuser can change the shell for other users:

# chsh -s /usr/sbin/nologin toor

The /usr/sbin/nologin shell prevents the system from assigning a shell to the user when they attempt to login.

16.2.2. 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 /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 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 /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 apache24:

# pw groupadd webadmin -M trhodes -g 6000
# visudo
%webadmin ALL=(ALL) /usr/sbin/service apache24 *

16.2.3. 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.

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:

# grep dru /etc/master.passwd

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 /etc/login.conf:


To change the algorithm to Blowfish, modify that line to look like this:


Then run cap_mkdb /etc/login.conf as described in Configuring Login Classes. 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 OpenSSH. Kerberos users may need to make additional changes to implement OpenSSH in their network. These changes are described in Kerberos.

16.2.4. 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 module. This module is enforced when a user changes their password.

To configure this module, become the superuser and uncomment the line containing in /etc/pam.d/passwd. Then, edit that line to match the password policy:

password        requisite         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 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:

% 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 /etc/login.conf. The default login class contains an example:

#       :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:

# 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 pw(8).

16.2.5. 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, 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 ENTER:

# 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 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.

16.2.6. 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 /bin, and saves those values to a hidden file in root's home directory, /root/.bin_chksum_mtree:

# 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 /root/.bin_cksum_mtree should yield output similar to the following:

#          user: root
#       machine: dreadnaught
#          tree: /bin
#          date: Mon Feb  3 10:19:53 2014

# .
/set type=file uid=0 gid=0 mode=0555 nlink=1 flags=none
.               type=dir mode=0755 nlink=2 size=1024 \
    \133        nlink=2 size=11704 time=1380277977.000000000 \
                cksum=484492447 \
    cat         size=12096 time=1380277975.000000000 cksum=3909216944 \
    chflags     size=8168 time=1380277975.000000000 cksum=3949425175 \
    chio        size=18520 time=1380277975.000000000 cksum=2208263309 \
    chmod       size=8640 time=1380277975.000000000 cksum=2214429708 \

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:

# mtree -s 3483151339707503 -p /bin < /root/.bin_chksum_mtree >> /root/.bin_chksum_output
# mtree: /bin checksum: 3427012225

This should produce the same checksum for /bin that was produced when the specification was created. If no changes have occurred to the binaries in this directory, the /root/.bin_chksum_output output file will be empty. To simulate a change, change the date on /bin/cat using touch and run the verification command again:

# 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 /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /etc, and /usr/local/etc.

More advanced IDS systems exist, such as 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 mtree(8).

16.2.7. 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 “Tuning with sysctl(8)”.

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 /etc/rc.conf, and the value of kern_securelevel to the desired security level. See security(7) and init(8) for more information on these settings and the available security levels.

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 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 security(7).

16.3. TCP Wrapper

TCP Wrapper is a host-based access control system which extends the abilities of “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 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.

16.3.1. Initial Configuration

To enable TCP Wrapper in FreeBSD, add the following lines to /etc/rc.conf:


Then, properly configure /etc/hosts.allow.

Unlike other implementations of TCP Wrapper, the use of hosts.deny is deprecated in FreeBSD. All configuration options should be placed in /etc/hosts.allow.

In the simplest configuration, daemon connection policies are set to either permit or block, depending on the options in /etc/hosts.allow. The default configuration in 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 mail/qpopper daemon, the following lines should be appended to hosts.allow:

# This line is required for POP3 connections:
qpopper : ALL : allow

Whenever this file is edited, restart inetd:

# service inetd restart

16.3.2. 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 hosts.allow:

# The rest of the daemons are protected.
	: severity \
	: twist /bin/echo "You are not welcome to use %d from %h."

In this example, the message "You are not allowed to use daemon name from hostname." will be returned for any daemon not configured in hosts.allow. This is useful for sending a reply back to the connection initiator right after the established connection is dropped. Any message returned must be wrapped in quote (") characters.

It may be possible to launch a denial of service attack on the server if an attacker floods these daemons with connection requests.

Another possibility is to use 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:

# We do not allow connections from
ALL : \
	: spawn (/bin/echo %a from %h attempted to access %d >> \
	  /var/log/connections.log) \
	: deny

This will deny all connection attempts from * and log the hostname, IP address, and the daemon to which access was attempted to /var/log/connections.log. This example uses the substitution characters %a and %h. Refer to hosts_access(5) for the complete list.

To match every instance of a daemon, domain, or IP address, use ALL. Another wildcard is PARANOID which may be used to match any host which provides an IP address that may be forged because the IP address differs from its resolved hostname. In this example, all connection requests to Sendmail which have an IP address that varies from its hostname will be denied:

# Block possibly spoofed requests to sendmail:
sendmail : PARANOID : deny

Using the PARANOID wildcard will result in denied connections if the client or server has a broken DNS setup.

To learn more about wildcards and their associated functionality, refer to hosts_access(5).

When adding new configuration lines, make sure that any unneeded entries for that daemon are commented out in hosts.allow.

16.4. 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 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 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

  • The Kerberos realm will be EXAMPLE.ORG.

Use real domain names when setting up Kerberos, even if it will run internally. This avoids DNS problems and assures inter-operation with other Kerberos realms.

16.4.1. 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 security/heimdal package as follows:

# pkg install heimdal

Next, update /etc/rc.conf using sysrc as follows:

# sysrc kdc_enable=yes
# sysrc kadmind_enable=yes

Next, edit /etc/krb5.conf as follows:

    default_realm = EXAMPLE.ORG
	kdc =
	admin_server =
[domain_realm] = EXAMPLE.ORG

In this example, the KDC will use the fully-qualified hostname 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 /etc/krb5.conf. For large organizations that have their own DNS servers, the above example could be trimmed to:

      default_realm = EXAMPLE.ORG
[domain_realm] = EXAMPLE.ORG

With the following lines being included in the zone file:

_kerberos._udp      IN  SRV     01 00 88
_kerberos._tcp      IN  SRV     01 00 88
_kpasswd._udp       IN  SRV     01 00 464
_kerberos-adm._tcp  IN  SRV     01 00 749
_kerberos           IN  TXT     EXAMPLE.ORG

In order for clients to be able to find the Kerberos services, they must have either a fully configured /etc/krb5.conf or a minimally configured /etc/krb5.conf and a properly configured DNS server.

Next, create the Kerberos database which contains the keys of all principals (users and hosts) encrypted with a master password. It is not required to remember this password as it will be stored in /var/heimdal/m-key; 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:

# 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 kadmin(8) can be used on the KDC in a mode that operates directly on the database, without using the 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:

# kadmin -l
kadmin> init EXAMPLE.ORG
Realm max ticket life [unlimited]:

Lastly, while still in kadmin, create the first principal using add. Stick to the default options for the principal for now, as these can be changed later with modify. Type ? at the prompt to see the available options.

kadmin> add tillman
Max ticket life [unlimited]:
Max renewable life [unlimited]:
Principal expiration time [never]:
Password expiration time [never]:
Attributes []:
Password: xxxxxxxx
Verifying password - Password: xxxxxxxx

Next, start the KDC services by running:

# 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:

% kinit tillman
tillman@EXAMPLE.ORG's Password:

Confirm that a ticket was successfully obtained using klist:

% 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:

% kdestroy

16.4.2. 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 /etc/krb5.conf. The version from the KDC can be used as-is, or it can be regenerated on the new system.

Next, create /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 keytab is generated on an administrator’s trusted machine using kadmin, then securely transferred to the server, e.g., with 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 /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 ssh(1), and perform administration locally using kadmin -l.

After installing /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:

# kadmin
kadmin> add --random-key host/
Max ticket life [unlimited]:
Max renewable life [unlimited]:
Principal expiration time [never]:
Password expiration time [never]:
Attributes []:
kadmin> ext_keytab host/
kadmin> exit

Note that ext_keytab stores the extracted key in /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:

# kadmin
kadmin> ext_keytab --keytab=/tmp/example.keytab host/
kadmin> exit

The keytab can then be securely copied to the server using 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 krb5.keytab. It is now ready for the Kerberos-using services to be enabled. One of the most common such services is sshd(8), which supports Kerberos via the GSS-API. In /etc/ssh/sshd_config, add the line:

GSSAPIAuthentication yes

After making this change, sshd(8) must be restarted for the new configuration to take effect: service sshd restart.

16.4.3. Configuring a Client to Use Kerberos

As it was for the server, the client requires configuration in /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 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 .k5login and .k5users files, placed in a user’s home directory, can be used to solve this problem. For example, if the following .k5login is placed in the home directory of webdevelopers, both principals listed will have access to that account without requiring a shared password:

Refer to ksu(1) for more information about .k5users.

16.4.4. 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 is recommended. Be careful of path issues: the MIT port installs into /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 rc.conf:


16.4.5. 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. “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 www/mod_auth_kerb.

  • All hosts in the realm must be both forward and reverse resolvable in DNS or, at a minimum, exist in /etc/hosts. CNAMEs will work, but the A and PTR records must be correct and in place. The error message for unresolvable hosts is not intuitive: Kerberos5 refuses authentication because Read req failed: Key table entry not found.

  • Some operating systems that act as clients to the KDC do not set the permissions for ksu to be setuid root. This means that ksu does not work. This is a permissions problem, not a KDC error.

  • With MITKerberos, to allow a principal to have a ticket life longer than the default lifetime of ten hours, use modify_principal at the 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 krb5.dict to prevent specific bad passwords from being used as described in kadmind(8), remember that it only applies to principals that have a password policy assigned to them. The format used in krb5.dict is one string per line. Creating a symbolic link to /usr/share/dict/words might be useful.

16.4.6. 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 security/tripwire can alleviate this.

16.5. 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 Transport Layer Security 1.0/1.1/1.2/1.3 (TLSv1/TLSv1.1/TLSv1.2/TLSv1.3) network security protocols and can be used as a general cryptographic library.

OpenSSL is often used to encrypt authentication of mail clients and to secure web based transactions such as credit card payments. Some ports, such as www/apache24 and databases/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 security/openssl port, add the following to /etc/make.conf:

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, 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 “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 OpenSSL Cookbook.

16.5.1. 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.

# 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 (e.g., city) []:Pittsburgh
Organization Name (e.g., company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (e.g., section) []:Systems Administrator
Common Name (e.g., YOUR name) []
Email Address []

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 openssl(1).

This command will create two files in the current directory. The certificate request, req.pem, can be sent to a CA who will validate the entered credentials, sign the request, and return the signed certificate. The second file, cert.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:

# 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:

# 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 (e.g., city) []:Pittsburgh
Organization Name (e.g., company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (e.g., section) []:Systems Administrator
Common Name (e.g. server FQDN or YOUR name) []
Email Address []

This will create two new files in the current directory: a private key file cert.key, and the certificate itself, cert.crt. These should be placed in a directory, preferably under /etc/ssl/, which is readable only by root. Permissions of 0700 are appropriate for these files and can be set using chmod.

16.5.2. Using Certificates

One use for a certificate is to encrypt connections to the Sendmail mail server in order to prevent the use of clear text authentication.

Some mail clients will display an error if the user has not installed a local copy of the certificate. Refer to the documentation included with the software for more information on certificate installation.

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 /etc/rc.conf:


This will automatically create a self-signed certificate, /etc/mail/certs/host.cert, a signing key, /etc/mail/certs/host.key, and a CA certificate, /etc/mail/certs/cacert.pem. The certificate will use the Common Name specified in sendmail_cert_cn. After saving the edits, restart Sendmail:

# service sendmail restart

If all went well, there will be no error messages in /var/log/maillog. For a simple test, connect to the mail server’s listening port using telnet:

# telnet 25
Connected to
Escape character is '^]'.
220 ESMTP Sendmail 8.14.7/8.14.7; Fri, 18 Apr 2014 11:50:32 -0400 (EDT)
ehlo Hello [], pleased to meet you
250 HELP
221 2.0.0 closing connection
Connection closed by foreign host.

If the STARTTLS line appears in the output, everything is working correctly.

16.6. 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 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 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 Configuring the FreeBSD Kernel:

options   IPSEC        IP security
device    crypto

If IPsec debugging support is desired, the following kernel option should also be added:

options   IPSEC_DEBUG  debug for IP security

This rest of this chapter demonstrates the process of setting up an 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 and the home LAN’s external IP address is

  • The internal addresses of the two networks can be either public or private IP addresses. However, the address space must not overlap. In this example, the corporate LAN’s internal IP address is and the home LAN’s internal IP address is

           corporate                          home -- <--> --

16.6.1. Configuring a VPN on FreeBSD

To begin, security/ipsec-tools must be installed from the Ports Collection. This software provides a number of applications which support the configuration.

The next requirement is to create two gif(4) pseudo-devices which will be used to tunnel packets and allow both networks to communicate properly. As root, run the following command on each gateway:

corp-gw# ifconfig gif0 create
corp-gw# ifconfig gif0
corp-gw# ifconfig gif0 tunnel
home-gw# ifconfig gif0 create
home-gw# ifconfig gif0
home-gw# ifconfig gif0 tunnel

Verify the setup on each gateway, using ifconfig gif0. Here is the output from the home gateway:

gif0: flags=8051 mtu 1280
tunnel inet -->
inet6 fe80::2e0:81ff:fe02:5881%gif0 prefixlen 64 scopeid 0x6
inet --> netmask 0xffffff00

Here is the output from the corporate gateway:

gif0: flags=8051 mtu 1280
tunnel inet -->
inet --> netmask 0xffffff00
inet6 fe80::250:bfff:fe3a:c1f%gif0 prefixlen 64 scopeid 0x4

Once complete, both internal IP addresses should be reachable using ping(8):

home-gw# ping
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=64 time=42.786 ms
64 bytes from icmp_seq=1 ttl=64 time=19.255 ms
64 bytes from icmp_seq=2 ttl=64 time=20.440 ms
64 bytes from icmp_seq=3 ttl=64 time=21.036 ms
--- 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-gw# ping
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=64 time=28.106 ms
64 bytes from icmp_seq=1 ttl=64 time=42.917 ms
64 bytes from icmp_seq=2 ttl=64 time=127.525 ms
64 bytes from icmp_seq=3 ttl=64 time=119.896 ms
64 bytes from icmp_seq=4 ttl=64 time=154.524 ms
--- 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 the networks behind each gateway. The following commands will achieve this goal:

corp-gw# route add
corp-gw# route add net gateway
home-gw# route add
home-gw# route add host gateway

Internal machines should be reachable from each gateway as well as from machines behind the gateways. Again, use ping(8) to confirm:

corp-gw# ping -c 3
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=63 time=92.391 ms
64 bytes from icmp_seq=1 ttl=63 time=21.870 ms
64 bytes from icmp_seq=2 ttl=63 time=198.022 ms
--- ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 21.870/101.846/198.022/74.001 ms

home-gw# ping -c 3
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=64 time=53.491 ms
64 bytes from icmp_seq=1 ttl=64 time=23.395 ms
64 bytes from icmp_seq=2 ttl=64 time=23.865 ms
--- ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max/stddev = 21.145/31.721/53.491/12.179 ms

At this point, traffic is flowing between the networks encapsulated in a gif tunnel but without any encryption. Next, use IPSec to encrypt traffic using pre-shared keys (PSK). Other than the IP addresses, /usr/local/etc/racoon/racoon.conf on both gateways will be identical and look similar to:

path    pre_shared_key  "/usr/local/etc/racoon/psk.txt"; #location of pre-shared key file
log     debug;	#log verbosity setting: set to 'notify' when testing and debugging is complete

padding	# options are not to be changed
        maximum_length  20;
        randomize       off;
        strict_check    off;
        exclusive_tail  off;

timer	# timing options. change as needed
        counter         5;
        interval        20 sec;
        persend         1;
#       natt_keepalive  15 sec;
        phase1          30 sec;
        phase2          15 sec;

listen	# address [port] that racoon will listen on
        isakmp [500];
        isakmp_natt [4500];

remote [500]
        exchange_mode   main,aggressive;
        doi             ipsec_doi;
        situation       identity_only;
        my_identifier   address;
        peers_identifier        address;
        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 any address 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 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 /usr/local/etc/racoon/setkey.conf.

# To the home network
spdadd any -P out ipsec esp/tunnel/;
spdadd any -P in ipsec esp/tunnel/;

Once in place, racoon may be started on both gateways using the following command:

# /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf -l /var/log/racoon.log

The output should be similar to the following:

corp-gw# /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[500]-[500] spi:623b9b3bd2492452:7deab82d54ff704a
2006-01-30 01:36:05: INFO: initiate new phase 2 negotiation:[0][0]
2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel[0]->[0] spi=28496098(0x1b2d0e2)
2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel[0]->[0] spi=47784998(0x2d92426)
2006-01-30 01:36:13: INFO: respond new phase 2 negotiation:[0][0]
2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel[0]->[0] spi=124397467(0x76a279b)
2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel[0]->[0] spi=175852902(0xa7b4d66)

To ensure the tunnel is working properly, switch to another console and use tcpdump(1) to view network traffic using the following command. Replace em0 with the network interface card as required:

corp-gw# tcpdump -i em0 host and dst

Data similar to the following should appear on the console. If not, there is an issue and debugging the returned data will be required.

01:47:32.021683 IP > ESP(spi=0x02acbf9f,seq=0xa)
01:47:33.022442 IP > ESP(spi=0x02acbf9f,seq=0xb)
01:47:34.024218 IP > 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 ipfw(8) firewall, add the following lines to the firewall configuration file:

ipfw add 00201 allow log esp from any to any
ipfw add 00202 allow log ah from any to any
ipfw add 00203 allow log ipencap from any to any
ipfw add 00204 allow log udp from any 500 to any

The rule numbers may need to be altered depending on the current host configuration.

For users of pf(4) or ipf(8), the following rules should do the trick:

pass in quick proto esp from any to any
pass in quick proto ah from any to any
pass in quick proto ipencap from any to any
pass in quick proto udp from any port = 500 to any port = 500
pass in quick on gif0 from any to any
pass out quick proto esp from any to any
pass out quick proto ah from any to any
pass out quick proto ipencap from any to any
pass out quick proto udp from any port = 500 to any port = 500
pass out quick on gif0 from any to any

Finally, to allow the machine to start support for the VPN during system initialization, add the following lines to /etc/rc.conf:

ipsec_file="/usr/local/etc/racoon/setkey.conf" # allows setting up spd policies on boot

16.7. 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.

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

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.

16.7.1. 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:

# ssh
The authenticity of host ' (' 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 '' (ECDSA) to the list of known hosts.
Password for user_password

SSH utilizes a key fingerprint system to verify the authenticity of the server when the client connects. When the user accepts the key’s fingerprint by typing yes when connecting for the first time, a copy of the key is saved to .ssh/known_hosts in the user’s home directory. Future attempts to login are verified against the saved key and ssh will display an alert if the server’s key does not match the saved key. If this occurs, the user should first verify why the key has changed before continuing with the connection.

Recent versions of OpenSSH only accept SSHv2 connections. SSH protocol version 1 is obsolete.

Use scp(1) to securely copy a file to or from a remote machine. This example copies COPYRIGHT on the remote system to a file of the same name in the current directory of the local system:

Password for *******
COPYRIGHT            100% |*****************************|  4735

Since the fingerprint was already verified for this host, the server’s key is automatically checked before prompting for the user’s password.

The arguments passed to 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:<path_to_remote_file>. 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 sftp(1) for a list of available commands while in an sftp session. Key-based Authentication

Instead of using passwords, a client can be configured to connect to the remote machine using keys. To generate 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.

% 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):  (1)
Enter same passphrase again:                 (2)
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/
The key fingerprint is:
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|                 |
|                 |
|        . o..    |
|       .S*+*o    |
|      . O=Oo . . |
|       = Oo= oo..|
|      .oB.* +.oo.|
|       =OE**.o..=|
1Type a passphrase here. It can contain spaces and symbols.
2Retype the passphrase to verify it.

The private key is stored in ~/.ssh/id_rsa and the public key is stored in ~/.ssh/ The public key must be copied to ~/.ssh/authorized_keys on the remote machine for key-based authentication to work.

Many users believe that keys are secure by design and will use a key without a passphrase. This is dangerous behavior. An administrator can verify that a key pair is protected by a passphrase by viewing the private key manually. If the private key file contains the word ENCRYPTED, the key owner is using a passphrase. In addition, to better secure end users, from may be placed in the public key file. For example, adding from="" 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 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 ssh-agent(1) and 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:

% ssh-agent csh
% ssh-add
Enter passphrase for key '/usr/home/user/.ssh/id_rsa':  (1)
Identity added: /usr/home/user/.ssh/id_rsa (/usr/home/user/.ssh/id_rsa)
1Enter the passphrase for the key.

To use ssh-agent in Xorg, add an entry for it in ~/.xinitrc. This provides the ssh-agent services to all programs launched in Xorg. An example ~/.xinitrc might look like this:

exec ssh-agent startxfce4

This launches ssh-agent, which in turn launches XFCE, every time Xorg starts. Once Xorg has been restarted so that the changes can take effect, run ssh-add to load all of the SSH keys. 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:

% ssh -N -f -L 5023:localhost:23

This example uses the following options:


Indicates no command, or tunnel only. If omitted, ssh initiates a normal session.


Forces ssh to run in the background.


Indicates a local tunnel in localport:remotehost:remoteport format.

The login name to use on the specified remote SSH server.

An SSH tunnel works by creating a listen socket on localhost on the specified localport. It then forwards any connections received on localport via the SSH connection to the specified remotehost:remoteport. In the example, port 5023 on the client is forwarded to port 23 on the remote machine. Since port 23 is used by telnet, this creates an encrypted telnet session through an SSH tunnel.

This method can be used to wrap any number of insecure TCP protocols such as SMTP, POP3, and FTP, as seen in the following examples.

Example 26. Create a Secure Tunnel for SMTP
% ssh -N -f -L 5025:localhost:25's password: *****
% telnet localhost 5025
Connected to localhost.
Escape character is '^]'.

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.

Example 27. Secure Access of a POP3 Server

In this example, there is an SSH server that accepts connections from the outside. On the same network resides a mail server running a POP3 server. To check email in a secure manner, create an SSH connection to the SSH server and tunnel through to the mail server:

% ssh -N -f -L'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

Example 28. Bypassing a Firewall

Some firewalls filter both incoming and outgoing connections. For example, a firewall might limit access from remote machines to ports 22 and 80 to only allow SSH and web surfing. This prevents access to any other service which uses a port other than 22 or 80.

The solution is to create an SSH connection to a machine outside of the network’s firewall and use it to tunnel to the desired service:

% ssh -N -f -L's password: *******

In this example, a streaming Ogg Vorbis client can now be pointed to localhost port 8888, which will be forwarded over to on port 8000, successfully bypassing the firewall.

16.7.2. 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 service(8) command:

# service sshd status

If the service is not running, add the following line to /etc/rc.conf.


This will start sshd, the daemon program for OpenSSH, the next time the system boots. To start it now:

# 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 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.

16.7.3. 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, add this line to /etc/ssh/sshd_config:

AllowUsers root@

To allow admin to log in from anywhere, list that user without specifying an IP address:

AllowUsers admin

Multiple users should be listed on the same line, like so:

AllowUsers root@ admin

After making changes to /etc/ssh/sshd_config, tell sshd to reload its configuration file by running:

# service sshd reload

When this keyword is used, it is important to list each user that needs to log into this machine. Any user that is not specified in that line will be locked out. Also, the keywords used in the OpenSSH server configuration file are case-sensitive. If the keyword is not spelled correctly, including its case, it will be ignored. Always test changes to this file to make sure that the edits are working as expected. Refer to 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 ssh-keygen(1) and send the administrator the public key. This key file will be placed in the authorized_keys as described above in the client section. To force the users to use keys only, the following option may be configured:

AuthenticationMethods publickey

Do not confuse /etc/ssh/sshd_config with /etc/ssh/ssh_config (note the extra d in the first filename). The first file configures the server and the second file configures the client. Refer to ssh_config(5) for a listing of the available client settings.

16.8. Access Control Lists

Access Control Lists (ACLs) extend the standard UNIX® permission model in a POSIX®.1e compatible way. This permits an administrator to take advantage of a more fine-grained permissions model.

The FreeBSD GENERIC kernel provides ACL support for UFS file systems. Users who prefer to compile a custom kernel must include the following option in their custom kernel configuration file:

options UFS_ACL

If this option is not compiled in, a warning message will be displayed when attempting to mount a file system with ACL support. ACLs rely on extended attributes which are natively supported in UFS2.

This chapter describes how to enable ACL support and provides some usage examples.

16.8.1. Enabling ACL Support

ACLs are enabled by the mount-time administrative flag, acls, which may be added to /etc/fstab. The mount-time flag can also be automatically set in a persistent manner using 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 fstab entry or if the devices re-order. This prevents accidental mounting of the file system without ACL support.

It is desirable to discourage accidental mounting without ACLs enabled because nasty things can happen if ACLs are enabled, then disabled, then re-enabled without flushing the extended attributes. In general, once ACLs are enabled on a file system, they should not be disabled, as the resulting file protections may not be compatible with those intended by the users of the system, and re-enabling ACLs may re-attach the previous ACLs to files that have since had their permissions changed, resulting in unpredictable behavior.

File systems with ACLs enabled will show a plus (+) sign in their permission settings:

drwx------  2 robert  robert  512 Dec 27 11:54 private
drwxrwx---+ 2 robert  robert  512 Dec 23 10:57 directory1
drwxrwx---+ 2 robert  robert  512 Dec 22 10:20 directory2
drwxrwx---+ 2 robert  robert  512 Dec 27 11:57 directory3
drwxr-xr-x  2 robert  robert  512 Nov 10 11:54 public_html

In this example, directory1, directory2, and directory3 are all taking advantage of ACLs, whereas private and public_html are not.

16.8.2. Using ACLs

File system ACLs can be viewed using getfacl. For instance, to view the ACL settings on test:

% getfacl test

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.

% setfacl -k test

To modify the default ACL entries, use -m:

% 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 getfacl(1) and setfacl(1) for more information about the options available for these commands.

16.9. 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 instructions for installing pkg.

Installation provides 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 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:

# pkg audit -F

pkg displays messages any published vulnerabilities in installed packages:

Affected package: cups-base-
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 ports-mgmt/portmaster.

16.10. 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 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 FreeBSD website and mailed to the FreeBSD security notifications mailing list, FreeBSD security mailing list, and FreeBSD announcements mailing list mailing lists.

This section describes the format of a FreeBSD security advisory.

16.10.1. Format of a Security Advisory

Here is an example of a FreeBSD security advisory:

Hash: SHA512

FreeBSD-SA-14:04.bind                                       Security Advisory
                                                          The FreeBSD Project

Topic:          BIND remote denial of service vulnerability

Category:       contrib
Module:         bind
Announced:      2014-01-14
Credits:        ISC
Affects:        FreeBSD 8.x and FreeBSD 9.x
Corrected:      2014-01-14 19:38:37 UTC (stable/9, 9.2-STABLE)
                2014-01-14 19:42:28 UTC (releng/9.2, 9.2-RELEASE-p3)
                2014-01-14 19:42:28 UTC (releng/9.1, 9.1-RELEASE-p10)
                2014-01-14 19:38:37 UTC (stable/8, 8.4-STABLE)
                2014-01-14 19:42:28 UTC (releng/8.4, 8.4-RELEASE-p7)
                2014-01-14 19:42:28 UTC (releng/8.3, 8.3-RELEASE-p14)
CVE Name:       CVE-2014-0591

For general information regarding FreeBSD Security Advisories,
including descriptions of the fields above, security branches, and the
following sections, please visit <URL:>.

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
# fetch
# gpg --verify bind-release.patch.asc

[FreeBSD 9.2-STABLE]
# fetch
# fetch
# gpg --verify bind-stable-9.patch.asc

b) Execute the following commands as root:

# cd /usr/src
# patch < /path/to/patch

Recompile the operating system using buildworld and installworld as
described in <URL:>.

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 man: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://

Or visit the following URL, replacing NNNNNN with the revision number:


VII. References



The latest revision of this advisory is available at


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 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 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.

16.11. Process Accounting

Process accounting is a security method in which an administrator may keep track of system resources used and their allocation among users, provide for system monitoring, and minimally track a user’s commands.

Process accounting has both positive and negative points. One of the positives is that an intrusion may be narrowed down to the point of entry. A negative is the amount of logs generated by process accounting, and the disk space they may require. This section walks an administrator through the basics of process accounting.

If more fine-grained accounting is needed, refer to Security Event Auditing.

16.11.1. Enabling and Utilizing Process Accounting

Before using process accounting, it must be enabled using the following commands:

# sysrc accounting_enable=yes
# service accounting start

The accounting information is stored in files located in /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 /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 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:

# lastcomm ls trhodes ttyp1

Many other useful options exist and are explained in lastcomm(1), acct(5), and sa(8).

16.12. 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 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 /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 /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.

16.12.1. Configuring Login Classes

In the traditional method, login classes and the resource limits to apply to a login class are defined in /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.

Whenever /etc/login.conf is edited, the /etc/login.conf.db must be updated by executing the following command:

# 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.

Login Class Resource Limits lists the most commonly used resource limits. All of the available resource limits and capabilities are described in detail in login.conf(5).

Table 29. Login Class Resource Limits
Resource LimitDescription


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.


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.


The maximum size of a file the user may own. Unlike disk quotas (Disk Quotas), this limit is enforced on individual files, not the set of all files a user owns.


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.


The maximum amount of memory a process may request to be locked into main memory using mlock(2). Some system-critical programs, such as amd(8), lock into main memory so that if the system begins to swap, they do not contribute to disk thrashing.


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.


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.


The limit on the amount of network memory a user may consume. This can be generally used to limit network communications.


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 /etc/rc are assigned to the daemon login class.

  • Although the default /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 cap.mkdb(1), getrlimit(2), and login.conf(5).

16.12.2. Enabling and Configuring Resource Limits

The kern.racct.enable tunable must be set to a non-zero value. Custom kernels require specific configuration:

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:


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 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:

% 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:

# rctl -a jail:httpd:memoryuse:deny=2G/jail

Rules will persist across reboots if they have been added to /etc/rctl.conf. The format is a rule, without the preceding command. For example, the previous rule could be added as:

# Block jail from using more than 2G memory:

To remove a rule, use rctl to remove it from the list:

# rctl -r user:trhodes:maxproc:deny=10/user

A method for removing all rules is documented in rctl(8). However, if removing all rules for a single user is required, this command may be issued:

# rctl -r user:trhodes

Many other resources exist which can be used to exert additional control over various subjects. See rctl(8) to learn about them.

16.13. 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 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 security/sudo or by use of the pkg(8) utility. To use the pkg(8) tool:

# 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 tas