diff --git a/documentation/content/en/books/handbook/mail/_index.adoc b/documentation/content/en/books/handbook/mail/_index.adoc index e4a832e8b1..aa05ce5dc2 100644 --- a/documentation/content/en/books/handbook/mail/_index.adoc +++ b/documentation/content/en/books/handbook/mail/_index.adoc @@ -1,1119 +1,1119 @@ --- title: Chapter 30. Electronic Mail part: IV. Network Communication prev: books/handbook/ppp-and-slip next: books/handbook/network-servers description: This chapter provides a basic introduction to running a mail server on FreeBSD, as well as an introduction to sending and receiving email using FreeBSD tags: ["mail", "sendmail", "MTA", "SMTP", "user agents", "fetchmail", "procmail", "alpine", "mut"] showBookMenu: true weight: 35 path: "/books/handbook/" --- [[mail]] = Electronic Mail :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 30 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/mail/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[mail-synopsis]] == Synopsis "Electronic Mail", better known as email, is one of the most widely used forms of communication today. This chapter provides a basic introduction to running a mail server on FreeBSD, as well as an introduction to sending and receiving email using FreeBSD For more complete coverage of this subject, refer to the books listed in crossref:bibliography[bibliography,Bibliography]. After reading this chapter, you will know: * Which software components are involved in sending and receiving electronic mail. * Where basic Sendmail configuration files are located in FreeBSD. * The difference between remote and local mailboxes. * How to block spammers from illegally using a mail server as a relay. * How to install and configure an alternate Mail Transfer Agent, replacing Sendmail. * How to troubleshoot common mail server problems. * How to set up the system to send mail only. * How to use mail with a dialup connection. * How to configure SMTP authentication for added security. * How to install and use a Mail User Agent, such as mutt, to send and receive email. * How to download mail from a remote POP or IMAP server. * How to automatically apply filters and rules to incoming email. Before reading this chapter, you should: * Properly set up a network connection (crossref:advanced-networking[advanced-networking,Advanced Networking]). * Properly set up the DNS information for a mail host (crossref:network-servers[network-servers,Network Servers]). * Know how to install additional third-party software (crossref:ports[ports,Installing Applications: Packages and Ports]). [[mail-using]] == Mail Components There are five major parts involved in an email exchange: the Mail User Agent (MUA), the Mail Transfer Agent (MTA), a mail host, a remote or local mailbox, and DNS. This section provides an overview of these components. Mail User Agent (MUA):: The Mail User Agent (MUA) is an application which is used to compose, send, and receive emails. This application can be a command line program, such as the built-in `mail` utility or a third-party application from the Ports Collection, such as mutt, alpine, or elm. Dozens of graphical programs are also available in the Ports Collection, including Claws Mail, Evolution, and Thunderbird. Some organizations provide a web mail program which can be accessed through a web browser. More information about installing and using a MUA on FreeBSD can be found in <>. Mail Transfer Agent (MTA):: The Mail Transfer Agent (MTA) is responsible for receiving incoming mail and delivering outgoing mail. FreeBSD ships with Sendmail as the default MTA, but it also supports numerous other mail server daemons, including Exim, Postfix, and qmail. Sendmail configuration is described in <>. If another MTA is installed using the Ports Collection, refer to its post-installation message for FreeBSD-specific configuration details and the application's website for more general configuration instructions. Mail Host and Mailboxes:: The mail host is a server that is responsible for delivering and receiving mail for a host or a network. The mail host collects all mail sent to the domain and stores it either in the default [.filename]#mbox# or the alternative Maildir format, depending on the configuration. Once mail has been stored, it may either be read locally using a MUA or remotely accessed and collected using protocols such as POP or IMAP. If mail is read locally, a POP or IMAP server does not need to be installed. + To access mailboxes remotely, a POP or IMAP server is required as these protocols allow users to connect to their mailboxes from remote locations. IMAP offers several advantages over POP. These include the ability to store a copy of messages on a remote server after they are downloaded and concurrent updates. IMAP can be useful over low-speed links as it allows users to fetch the structure of messages without downloading them. It can also perform tasks such as searching on the server in order to minimize data transfer between clients and servers. + Several POP and IMAP servers are available in the Ports Collection. These include package:mail/qpopper[], package:mail/imap-uw[], package:mail/courier-imap[], and package:mail/dovecot2[]. + [WARNING] ==== It should be noted that both POP and IMAP transmit information, including username and password credentials, in clear-text. To secure the transmission of information across these protocols, consider tunneling sessions over man:ssh[1] (crossref:security[security-ssh-tunneling,"SSH Tunneling"]) or using SSL (crossref:security[openssl,"OpenSSL"]). ==== Domain Name System (DNS):: The Domain Name System (DNS) and its daemon `named` play a large role in the delivery of email. In order to deliver mail from one site to another, the MTA will look up the remote site in DNS to determine which host will receive mail for the destination. This process also occurs when mail is sent from a remote host to the MTA. + In addition to mapping hostnames to IP addresses, DNS is responsible for storing information specific to mail delivery, known as Mail eXchanger MX records. The MX record specifies which hosts will receive mail for a particular domain. + To view the MX records for a domain, specify the type of record. Refer to man:host[1], for more details about this command: + [source,shell] .... % host -t mx FreeBSD.org FreeBSD.org mail is handled by 10 mx1.FreeBSD.org .... + Refer to crossref:network-servers[network-dns,"Domain Name System (DNS)"] for more information about DNS and its configuration. [[sendmail]] == Sendmail Configuration Files Sendmail is the default MTA installed with FreeBSD. It accepts mail from MUAs and delivers it to the appropriate mail host, as defined by its configuration. Sendmail can also accept network connections and deliver mail to local mailboxes or to another program. The configuration files for Sendmail are located in [.filename]#/etc/mail#. This section describes these files in more detail. [.filename]#/etc/mail/access#:: This access database file defines which hosts or IP addresses have access to the local mail server and what kind of access they have. Hosts listed as `OK`, which is the default option, are allowed to send mail to this host as long as the mail's final destination is the local machine. Hosts listed as `REJECT` are rejected for all mail connections. Hosts listed as `RELAY` are allowed to send mail for any destination using this mail server. Hosts listed as `ERROR` will have their mail returned with the specified mail error. If a host is listed as `SKIP`, Sendmail will abort the current search for this entry without accepting or rejecting the mail. Hosts listed as `QUARANTINE` will have their messages held and will receive the specified text as the reason for the hold. + Examples of using these options for both IPv4 and IPv6 addresses can be found in the FreeBSD sample configuration, [.filename]#/etc/mail/access.sample#: + [.programlisting] .... # $FreeBSD$ # # Mail relay access control list. Default is to reject mail unless the # destination is local, or listed in /etc/mail/local-host-names # ## Examples (commented out for safety) #From:cyberspammer.com ERROR:"550 We don't accept mail from spammers" #From:okay.cyberspammer.com OK #Connect:sendmail.org RELAY #To:sendmail.org RELAY #Connect:128.32 RELAY #Connect:128.32.2 SKIP #Connect:IPv6:1:2:3:4:5:6:7 RELAY #Connect:suspicious.example.com QUARANTINE:Mail from suspicious host #Connect:[127.0.0.3] OK #Connect:[IPv6:1:2:3:4:5:6:7:8] OK .... + To configure the access database, use the format shown in the sample to make entries in [.filename]#/etc/mail/access#, but do not put a comment symbol (`+#+`) in front of the entries. Create an entry for each host or network whose access should be configured. Mail senders that match the left side of the table are affected by the action on the right side of the table. + Whenever this file is updated, update its database and restart Sendmail: + [source,shell] .... # makemap hash /etc/mail/access < /etc/mail/access # service sendmail restart .... [.filename]#/etc/mail/aliases#:: This database file contains a list of virtual mailboxes that are expanded to users, files, programs, or other aliases. Here are a few entries to illustrate the file format: + [.programlisting] .... root: localuser ftp-bugs: joe,eric,paul bit.bucket: /dev/null procmail: "|/usr/local/bin/procmail" .... + The mailbox name on the left side of the colon is expanded to the target(s) on the right. The first entry expands the `root` mailbox to the `localuser` mailbox, which is then looked up in the [.filename]#/etc/mail/aliases# database. If no match is found, the message is delivered to `localuser`. The second entry shows a mail list. Mail to `ftp-bugs` is expanded to the three local mailboxes `joe`, `eric`, and `paul`. A remote mailbox could be specified as _user@example.com_. The third entry shows how to write mail to a file, in this case [.filename]#/dev/null#. The last entry demonstrates how to send mail to a program, [.filename]#/usr/local/bin/procmail#, through a UNIX(R) pipe. Refer to man:aliases[5] for more information about the format of this file. + Whenever this file is updated, run `newaliases` to update and initialize the aliases database. [.filename]#/etc/mail/sendmail.cf#:: This is the master configuration file for Sendmail. It controls the overall behavior of Sendmail, including everything from rewriting email addresses to printing rejection messages to remote mail servers. Accordingly, this configuration file is quite complex. Fortunately, this file rarely needs to be changed for standard mail servers. + The master Sendmail configuration file can be built from man:m4[1] macros that define the features and behavior of Sendmail. Refer to [.filename]#/usr/src/contrib/sendmail/cf/README# for some of the details. + Whenever changes to this file are made, Sendmail needs to be restarted for the changes to take effect. [.filename]#/etc/mail/virtusertable#:: This database file maps mail addresses for virtual domains and users to real mailboxes. These mailboxes can be local, remote, aliases defined in [.filename]#/etc/mail/aliases#, or files. This allows multiple virtual domains to be hosted on one machine. + FreeBSD provides a sample configuration file in [.filename]#/etc/mail/virtusertable.sample# to further demonstrate its format. The following example demonstrates how to create custom entries using that format: + [.programlisting] .... root@example.com root postmaster@example.com postmaster@noc.example.net @example.com joe .... + This file is processed in a first match order. When an email address matches the address on the left, it is mapped to the local mailbox listed on the right. The format of the first entry in this example maps a specific email address to a local mailbox, whereas the format of the second entry maps a specific email address to a remote mailbox. Finally, any email address from `example.com` which has not matched any of the previous entries will match the last mapping and be sent to the local mailbox `joe`. When creating custom entries, use this format and add them to [.filename]#/etc/mail/virtusertable#. Whenever this file is edited, update its database and restart Sendmail: + [source,shell] .... # makemap hash /etc/mail/virtusertable < /etc/mail/virtusertable # service sendmail restart .... [.filename]#/etc/mail/relay-domains#:: In a default FreeBSD installation, Sendmail is configured to only send mail from the host it is running on. For example, if a POP server is available, users will be able to check mail from remote locations but they will not be able to send outgoing emails from outside locations. Typically, a few moments after the attempt, an email will be sent from `MAILER-DAEMON` with a `5.7 Relaying Denied` message. + The most straightforward solution is to add the ISP's FQDN to [.filename]#/etc/mail/relay-domains#. If multiple addresses are needed, add them one per line: + [.programlisting] .... your.isp.example.com other.isp.example.net users-isp.example.org www.example.org .... + After creating or editing this file, restart Sendmail with `service sendmail restart`. + Now any mail sent through the system by any host in this list, provided the user has an account on the system, will succeed. This allows users to send mail from the system remotely without opening the system up to relaying SPAM from the Internet. [[mail-changingmta]] == Changing the Mail Transfer Agent FreeBSD comes with Sendmail already installed as the MTA which is in charge of outgoing and incoming mail. However, the system administrator can change the system's MTA. A wide choice of alternative MTAs is available from the `mail` category of the FreeBSD Ports Collection. Once a new MTA is installed, configure and test the new software before replacing Sendmail. Refer to the documentation of the new MTA for information on how to configure the software. Once the new MTA is working, use the instructions in this section to disable Sendmail and configure FreeBSD to use the replacement MTA. [[mail-disable-sendmail]] === Disable Sendmail [WARNING] ==== If Sendmail's outgoing mail service is disabled, it is important that it is replaced with an alternative mail delivery system. Otherwise, system functions such as man:periodic[8] will be unable to deliver their results by email. Many parts of the system expect a functional MTA. If applications continue to use Sendmail's binaries to try to send email after they are disabled, mail could go into an inactive Sendmail queue and never be delivered. ==== In order to completely disable Sendmail, add or edit the following lines in [.filename]#/etc/rc.conf#: [.programlisting] .... sendmail_enable="NO" sendmail_submit_enable="NO" sendmail_outbound_enable="NO" sendmail_msp_queue_enable="NO" .... To only disable Sendmail's incoming mail service, use only this entry in [.filename]#/etc/rc.conf#: [.programlisting] .... sendmail_enable="NO" .... More information on Sendmail's startup options is available in man:rc.sendmail[8]. === Replace the Default MTA When a new MTA is installed using the Ports Collection, its startup script is also installed and startup instructions are mentioned in its package message. Before starting the new MTA, stop the running Sendmail processes. This example stops all of these services, then starts the Postfix service: [source,shell] .... # service sendmail stop # service postfix start .... To start the replacement MTA at system boot, add its configuration line to [.filename]#/etc/rc.conf#. This entry enables the Postfix MTA: [.programlisting] .... postfix_enable="YES" .... Some extra configuration is needed as Sendmail is so ubiquitous that some software assumes it is already installed and configured. Check [.filename]#/etc/periodic.conf# and make sure that these values are set to `NO`. If this file does not exist, create it with these entries: [.programlisting] .... daily_clean_hoststat_enable="NO" daily_status_mail_rejects_enable="NO" daily_status_include_submit_mailq="NO" daily_submit_queuerun="NO" .... Some alternative MTAs provide their own compatible implementations of the Sendmail command-line interface in order to facilitate using them as drop-in replacements for Sendmail. However, some MUAs may try to execute standard Sendmail binaries instead of the new MTA's binaries. FreeBSD uses [.filename]#/etc/mail/mailer.conf# to map the expected Sendmail binaries to the location of the new binaries. More information about this mapping can be found in man:mailwrapper[8]. The default [.filename]#/etc/mail/mailer.conf# looks like this: [.programlisting] .... # $FreeBSD$ # # Execute the "real" sendmail program, named /usr/libexec/sendmail/sendmail # sendmail /usr/libexec/sendmail/sendmail send-mail /usr/libexec/sendmail/sendmail mailq /usr/libexec/sendmail/sendmail newaliases /usr/libexec/sendmail/sendmail hoststat /usr/libexec/sendmail/sendmail purgestat /usr/libexec/sendmail/sendmail .... When any of the commands listed on the left are run, the system actually executes the associated command shown on the right. This system makes it easy to change what binaries are executed when these default binaries are invoked. Some MTAs, when installed using the Ports Collection, will prompt to update this file for the new binaries. For example, Postfix will update the file like this: [.programlisting] .... # # Execute the Postfix sendmail program, named /usr/local/sbin/sendmail # sendmail /usr/local/sbin/sendmail send-mail /usr/local/sbin/sendmail mailq /usr/local/sbin/sendmail newaliases /usr/local/sbin/sendmail .... If the installation of the MTA does not automatically update [.filename]#/etc/mail/mailer.conf#, edit this file in a text editor so that it points to the new binaries. This example points to the binaries installed by package:mail/ssmtp[]: [.programlisting] .... sendmail /usr/local/sbin/ssmtp send-mail /usr/local/sbin/ssmtp mailq /usr/local/sbin/ssmtp newaliases /usr/local/sbin/ssmtp hoststat /usr/bin/true purgestat /usr/bin/true .... Once everything is configured, it is recommended to reboot the system. Rebooting provides the opportunity to ensure that the system is correctly configured to start the new MTA automatically on boot. [[mail-trouble]] == Troubleshooting === Why do I have to use the FQDN for hosts on my site? The host may actually be in a different domain. For example, in order for a host in `foo.bar.edu` to reach a host called `mumble` in the `bar.edu` domain, refer to it by the Fully-Qualified Domain Name FQDN, `mumble.bar.edu`, instead of just `mumble`. This is because the version of BIND which ships with FreeBSD no longer provides default abbreviations for non-FQDNs other than the local domain. An unqualified host such as `mumble` must either be found as `mumble.foo.bar.edu`, or it will be searched for in the root domain. In older versions of BIND, the search continued across `mumble.bar.edu`, and `mumble.edu`. RFC 1535 details why this is considered bad practice or even a security hole. As a good workaround, place the line: [.programlisting] .... search foo.bar.edu bar.edu .... instead of the previous: [.programlisting] .... domain foo.bar.edu .... into [.filename]#/etc/resolv.conf#. However, make sure that the search order does not go beyond the "boundary between local and public administration", as RFC 1535 calls it. === How can I run a mail server on a dial-up PPP host? Connect to a FreeBSD mail gateway on the LAN. The PPP connection is non-dedicated. One way to do this is to get a full-time Internet server to provide secondary MX services for the domain. In this example, the domain is `example.com` and the ISP has configured `example.net` to provide secondary MX services to the domain: [.programlisting] .... example.com. MX 10 example.com. MX 20 example.net. .... Only one host should be specified as the final recipient. For Sendmail, add `Cw example.com` in [.filename]#/etc/mail/sendmail.cf# on `example.com`. When the sending MTA attempts to deliver mail, it will try to connect to the system, `example.com`, over the PPP link. This will time out if the destination is offline. The MTA will automatically deliver it to the secondary MX site at the Internet Service Provider (ISP), `example.net`. The secondary MX site will periodically try to connect to the primary MX host, `example.com`. Use something like this as a login script: [.programlisting] .... #!/bin/sh # Put me in /usr/local/bin/pppmyisp ( sleep 60 ; /usr/sbin/sendmail -q ) & /usr/sbin/ppp -direct pppmyisp .... When creating a separate login script for users, instead use `sendmail -qRexample.com` in the script above. This will force all mail in the queue for `example.com` to be processed immediately. A further refinement of the situation can be seen from this example from the {freebsd-isp}: [.programlisting] .... > we provide the secondary MX for a customer. The customer connects to > our services several times a day automatically to get the mails to > his primary MX (We do not call his site when a mail for his domains > arrived). Our sendmail sends the mailqueue every 30 minutes. At the > moment he has to stay 30 minutes online to be sure that all mail is > gone to the primary MX. > > Is there a command that would initiate sendmail to send all the mails > now? The user has not root-privileges on our machine of course. In the privacy flags section of sendmail.cf, there is a definition Opgoaway,restrictqrun Remove restrictqrun to allow non-root users to start the queue processing. You might also like to rearrange the MXs. We are the 1st MX for our customers like this, and we have defined: # If we are the best MX for a host, try directly instead of generating # local config error. OwTrue That way a remote site will deliver straight to you, without trying the customer connection. You then send to your customer. Only works for hosts, so you need to get your customer to name their mail machine customer.com as well as hostname.customer.com in the DNS. Just put an A record in the DNS for customer.com. .... [[mail-advanced]] == Advanced Topics This section covers more involved topics such as mail configuration and setting up mail for an entire domain. [[mail-config]] === Basic Configuration Out of the box, one can send email to external hosts as long as [.filename]#/etc/resolv.conf# is configured or the network has access to a configured DNS server. To have email delivered to the MTA on the FreeBSD host, do one of the following: * Run a DNS server for the domain. * Get mail delivered directly to the FQDN for the machine. In order to have mail delivered directly to a host, it must have a permanent static IP address, not a dynamic IP address. If the system is behind a firewall, it must be configured to allow SMTP traffic. To receive mail directly at a host, one of these two must be configured: * Make sure that the lowest-numbered MX record in DNS points to the host's static IP address. * Make sure there is no MX entry in the DNS for the host. Either of the above will allow mail to be received directly at the host. Try this: [source,shell] .... # hostname example.FreeBSD.org # host example.FreeBSD.org example.FreeBSD.org has address 204.216.27.XX .... In this example, mail sent directly to mailto:yourlogin@example.FreeBSD.org[yourlogin@example.FreeBSD.org] should work without problems, assuming Sendmail is running correctly on `example.FreeBSD.org`. For this example: [source,shell] .... # host example.FreeBSD.org example.FreeBSD.org has address 204.216.27.XX example.FreeBSD.org mail is handled (pri=10) by nevdull.FreeBSD.org .... All mail sent to `example.FreeBSD.org` will be collected on `hub` under the same username instead of being sent directly to your host. The above information is handled by the DNS server. The DNS record that carries mail routing information is the MX entry. If no MX record exists, mail will be delivered directly to the host by way of its IP address. The MX entry for `freefall.FreeBSD.org` at one time looked like this: [.programlisting] .... freefall MX 30 mail.crl.net freefall MX 40 agora.rdrop.com freefall MX 10 freefall.FreeBSD.org freefall MX 20 who.cdrom.com .... `freefall` had many MX entries. The lowest MX number is the host that receives mail directly, if available. If it is not accessible for some reason, the next lower-numbered host will accept messages temporarily, and pass it along when a lower-numbered host becomes available. Alternate MX sites should have separate Internet connections in order to be most useful. Your ISP can provide this service. [[mail-domain]] === Mail for a Domain When configuring an MTA for a network, any mail sent to hosts in its domain should be diverted to the MTA so that users can receive their mail on the master mail server. To make life easiest, a user account with the same _username_ should exist on both the MTA and the system with the MUA. Use man:adduser[8] to create the user accounts. The MTA must be the designated mail exchanger for each workstation on the network. This is done in the DNS configuration with an MX record: [.programlisting] .... example.FreeBSD.org A 204.216.27.XX ; Workstation MX 10 nevdull.FreeBSD.org ; Mailhost .... This will redirect mail for the workstation to the MTA no matter where the A record points. The mail is sent to the MX host. This must be configured on a DNS server. If the network does not run its own DNS server, talk to the ISP or DNS provider. The following is an example of virtual email hosting. Consider a customer with the domain `customer1.org`, where all the mail for `customer1.org` should be sent to `mail.myhost.com`. The DNS entry should look like this: [.programlisting] .... customer1.org MX 10 mail.myhost.com .... An `A` record is _not_ needed for `customer1.org` in order to only handle email for that domain. However, running `ping` against `customer1.org` will not work unless an `A` record exists for it. Tell the MTA which domains and/or hostnames it should accept mail for. Either of the following will work for Sendmail: * Add the hosts to [.filename]#/etc/mail/local-host-names# when using the `FEATURE(use_cw_file)`. * Add a `Cwyour.host.com` line to [.filename]#/etc/sendmail.cf#. [[outgoing-only]] == Setting Up to Send Only There are many instances where one may only want to send mail through a relay. Some examples are: * The computer is a desktop machine that needs to use programs such as man:mail[1], using the ISP's mail relay. * The computer is a server that does not handle mail locally, but needs to pass off all mail to a relay for processing. While any MTA is capable of filling this particular niche, it can be difficult to properly configure a full-featured MTA just to handle offloading mail. Programs such as Sendmail and Postfix are overkill for this use. Additionally, a typical Internet access service agreement may forbid one from running a "mail server". The easiest way to fulfill those needs is to install the package:mail/ssmtp[] port: [source,shell] .... # cd /usr/ports/mail/ssmtp # make install replace clean .... Once installed, package:mail/ssmtp[] can be configured with [.filename]#/usr/local/etc/ssmtp/ssmtp.conf#: [.programlisting] .... root=yourrealemail@example.com mailhub=mail.example.com rewriteDomain=example.com hostname=_HOSTNAME_ .... Use the real email address for `root`. Enter the ISP's outgoing mail relay in place of `mail.example.com`. Some ISPs call this the "outgoing mail server" or "SMTP server". Make sure to disable Sendmail, including the outgoing mail service. See <> for details. package:mail/ssmtp[] has some other options available. Refer to the examples in [.filename]#/usr/local/etc/ssmtp# or the manual page of ssmtp for more information. Setting up ssmtp in this manner allows any software on the computer that needs to send mail to function properly, while not violating the ISP's usage policy or allowing the computer to be hijacked for spamming. [[SMTP-dialup]] == Using Mail with a Dialup Connection When using a static IP address, one should not need to adjust the default configuration. Set the hostname to the assigned Internet name and Sendmail will do the rest. When using a dynamically assigned IP address and a dialup PPP connection to the Internet, one usually has a mailbox on the ISP's mail server. In this example, the ISP's domain is `example.net`, the user name is `user`, the hostname is `bsd.home`, and the ISP has allowed `relay.example.net` as a mail relay. In order to retrieve mail from the ISP's mailbox, install a retrieval agent from the Ports Collection. package:mail/fetchmail[] is a good choice as it supports many different protocols. Usually, the ISP will provide POP. When using user PPP, email can be automatically fetched when an Internet connection is established with the following entry in [.filename]#/etc/ppp/ppp.linkup#: [.programlisting] .... MYADDR: !bg su user -c fetchmail .... When using Sendmail to deliver mail to non-local accounts, configure Sendmail to process the mail queue as soon as the Internet connection is established. To do this, add this line after the above `fetchmail` entry in [.filename]#/etc/ppp/ppp.linkup#: [.programlisting] .... !bg su user -c "sendmail -q" .... In this example, there is an account for `user` on `bsd.home`. In the home directory of `user` on `bsd.home`, create a [.filename]#.fetchmailrc# which contains this line: [.programlisting] .... poll example.net protocol pop3 fetchall pass MySecret .... This file should not be readable by anyone except `user` as it contains the password `MySecret`. In order to send mail with the correct `from:` header, configure Sendmail to use mailto:user@example.net[user@example.net] rather than mailto:user@bsd.home[user@bsd.home] and to send all mail via `relay.example.net`, allowing quicker mail transmission. The following [.filename]#.mc# should suffice: [.programlisting] .... VERSIONID(`bsd.home.mc version 1.0') OSTYPE(bsd4.4)dnl FEATURE(nouucp)dnl MAILER(local)dnl MAILER(smtp)dnl Cwlocalhost Cwbsd.home MASQUERADE_AS(`example.net')dnl FEATURE(allmasquerade)dnl FEATURE(masquerade_envelope)dnl FEATURE(nocanonify)dnl FEATURE(nodns)dnl define(`SMART_HOST', `relay.example.net') Dmbsd.home define(`confDOMAIN_NAME',`bsd.home')dnl define(`confDELIVERY_MODE',`deferred')dnl .... Refer to the previous section for details of how to convert this file into the [.filename]#sendmail.cf# format. Do not forget to restart Sendmail after updating [.filename]#sendmail.cf#. [[SMTP-Auth]] == SMTP Authentication Configuring SMTP authentication on the MTA provides a number of benefits. SMTP authentication adds a layer of security to Sendmail, and provides mobile users who switch hosts the ability to use the same MTA without the need to reconfigure their mail client's settings each time. [.procedure] . Install package:security/cyrus-sasl2[] from the Ports Collection. This port supports a number of compile-time options. For the SMTP authentication method demonstrated in this example, make sure that `LOGIN` is not disabled. . After installing package:security/cyrus-sasl2[], edit [.filename]#/usr/local/lib/sasl2/Sendmail.conf#, or create it if it does not exist, and add the following line: + [.programlisting] .... pwcheck_method: saslauthd .... . Next, install package:security/cyrus-sasl2-saslauthd[] and add the following line to [.filename]#/etc/rc.conf#: + [.programlisting] .... saslauthd_enable="YES" .... + Finally, start the saslauthd daemon: + [source,shell] .... # service saslauthd start .... + This daemon serves as a broker for Sendmail to authenticate against the FreeBSD man:passwd[5] database. This saves the trouble of creating a new set of usernames and passwords for each user that needs to use SMTP authentication, and keeps the login and mail password the same. . Next, edit [.filename]#/etc/make.conf# and add the following lines: + [.programlisting] .... SENDMAIL_CFLAGS=-I/usr/local/include/sasl -DSASL SENDMAIL_LDADD=/usr/local/lib/libsasl2.so .... + These lines provide Sendmail the proper configuration options for linking to package:cyrus-sasl2[] at compile time. Make sure that package:cyrus-sasl2[] has been installed before recompiling Sendmail. . Recompile Sendmail by executing the following commands: + [source,shell] .... # cd /usr/src/lib/libsmutil # make cleandir && make obj && make # cd /usr/src/lib/libsm # make cleandir && make obj && make # cd /usr/src/usr.sbin/sendmail # make cleandir && make obj && make && make install .... + This compile should not have any problems if [.filename]#/usr/src# has not changed extensively and the shared libraries it needs are available. . After Sendmail has been compiled and reinstalled, edit [.filename]#/etc/mail/freebsd.mc# or the local [.filename]#.mc#. Many administrators choose to use the output from man:hostname[1] as the name of [.filename]#.mc# for uniqueness. Add these lines: + [.programlisting] .... dnl set SASL options TRUST_AUTH_MECH(`GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl define(`confAUTH_MECHANISMS', `GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN')dnl .... + These options configure the different methods available to Sendmail for authenticating users. To use a method other than pwcheck, refer to the Sendmail documentation. . Finally, run man:make[1] while in [.filename]#/etc/mail#. That will run the new [.filename]#.mc# and create a [.filename]#.cf# named either [.filename]#freebsd.cf# or the name used for the local [.filename]#.mc#. Then, run `make install restart`, which will copy the file to [.filename]#sendmail.cf#, and properly restart Sendmail. For more information about this process, refer to [.filename]#/etc/mail/Makefile#. To test the configuration, use a MUA to send a test message. For further investigation, set the `LogLevel` of Sendmail to `13` and watch [.filename]#/var/log/maillog# for any errors. For more information, refer to http://www.sendmail.org/~ca/email/auth.html[SMTP authentication]. [[mail-agents]] == Mail User Agents A MUA is an application that is used to send and receive email. As email "evolves" and becomes more complex, MUAs are becoming increasingly powerful and provide users increased functionality and flexibility. The `mail` category of the FreeBSD Ports Collection contains numerous MUAs. These include graphical email clients such as Evolution or Balsa and console based clients such as mutt or alpine. [[mail-command]] === `mail` man:mail[1] is the default MUA installed with FreeBSD. It is a console based MUA that offers the basic functionality required to send and receive text-based email. It provides limited attachment support and can only access local mailboxes. Although `mail` does not natively support interaction with POP or IMAP servers, these mailboxes may be downloaded to a local [.filename]#mbox# using an application such as fetchmail. In order to send and receive email, run `mail`: [source,shell] .... % mail .... The contents of the user's mailbox in [.filename]#/var/mail# are automatically read by `mail`. Should the mailbox be empty, the utility exits with a message indicating that no mail could be found. If mail exists, the application interface starts, and a list of messages will be displayed. Messages are automatically numbered, as can be seen in the following example: [source,shell] .... Mail version 8.1 6/6/93. Type ? for help. "/var/mail/marcs": 3 messages 3 new >N 1 root@localhost Mon Mar 8 14:05 14/510 "test" N 2 root@localhost Mon Mar 8 14:05 14/509 "user account" N 3 root@localhost Mon Mar 8 14:05 14/509 "sample" .... Messages can now be read by typing kbd:[t] followed by the message number. This example reads the first email: [source,shell] .... & t 1 Message 1: From root@localhost Mon Mar 8 14:05:52 2004 X-Original-To: marcs@localhost Delivered-To: marcs@localhost To: marcs@localhost Subject: test Date: Mon, 8 Mar 2004 14:05:52 +0200 (SAST) From: root@localhost (Charlie Root) This is a test message, please reply if you receive it. .... As seen in this example, the message will be displayed with full headers. To display the list of messages again, press kbd:[h]. If the email requires a reply, press either kbd:[R] or kbd:[r] `mail` keys. kbd:[R] instructs `mail` to reply only to the sender of the email, while kbd:[r] replies to all other recipients of the message. These commands can be suffixed with the mail number of the message to reply to. After typing the response, the end of the message should be marked by a single kbd:[.] on its own line. An example can be seen below: [source,shell] .... & R 1 To: root@localhost Subject: Re: test Thank you, I did get your email. . EOT .... In order to send a new email, press kbd:[m], followed by the recipient email address. Multiple recipients may be specified by separating each address with the kbd:[,] delimiter. The subject of the message may then be entered, followed by the message contents. The end of the message should be specified by putting a single kbd:[.] on its own line. [source,shell] .... & mail root@localhost Subject: I mastered mail Now I can send and receive email using mail ... :) . EOT .... While using `mail`, press kbd:[?] to display help at any time. Refer to man:mail[1] for more help on how to use `mail`. [NOTE] ==== man:mail[1] was not designed to handle attachments and thus deals with them poorly. Newer MUAs handle attachments in a more intelligent way. Users who prefer to use `mail` may find the package:converters/mpack[] port to be of considerable use. ==== [[mutt-command]] === mutt mutt is a powerful MUA, with many features, including: * The ability to thread messages. * PGP support for digital signing and encryption of email. * MIME support. * Maildir support. * Highly customizable. Refer to http://www.mutt.org[http://www.mutt.org] for more information on mutt. mutt may be installed using the package:mail/mutt[] port. After the port has been installed, mutt can be started by issuing the following command: [source,shell] .... % mutt .... mutt will automatically read and display the contents of the user mailbox in [.filename]#/var/mail#. If no mails are found, mutt will wait for commands from the user. The example below shows mutt displaying a list of messages: -image::mutt1.png[] +image::mutt1.png[mutt email client showing a list of messages] To read an email, select it using the cursor keys and press kbd:[Enter]. An example of mutt displaying email can be seen below: -image::mutt2.png[] +image::mutt2.png[mutt email client displaying an email] Similar to man:mail[1], mutt can be used to reply only to the sender of the message as well as to all recipients. To reply only to the sender of the email, press kbd:[r]. To send a group reply to the original sender as well as all the message recipients, press kbd:[g]. [NOTE] ==== By default, mutt uses the man:vi[1] editor for creating and replying to emails. Each user can customize this by creating or editing the [.filename]#.muttrc# in their home directory and setting the `editor` variable or by setting the `EDITOR` environment variable. Refer to http://www.mutt.org/[http://www.mutt.org/] for more information about configuring mutt. ==== To compose a new mail message, press kbd:[m]. After a valid subject has been given, mutt will start man:vi[1] so the email can be written. Once the contents of the email are complete, save and quit from `vi`. mutt will resume, displaying a summary screen of the mail that is to be delivered. In order to send the mail, press kbd:[y]. An example of the summary screen can be seen below: -image::mutt3.png[] +image::mutt3.png[mutt email client showing the summary screen] mutt contains extensive help which can be accessed from most of the menus by pressing kbd:[?]. The top line also displays the keyboard shortcuts where appropriate. [[alpine-command]] === alpine alpine is aimed at a beginner user, but also includes some advanced features. [WARNING] ==== alpine has had several remote vulnerabilities discovered in the past, which allowed remote attackers to execute arbitrary code as users on the local system, by the action of sending a specially-prepared email. While _known_ problems have been fixed, alpine code is written in an insecure style and the FreeBSD Security Officer believes there are likely to be other undiscovered vulnerabilities. Users install alpine at their own risk. ==== The current version of alpine may be installed using the package:mail/alpine[] port. Once the port has installed, alpine can be started by issuing the following command: [source,shell] .... % alpine .... The first time alpine runs, it displays a greeting page with a brief introduction, as well as a request from the alpine development team to send an anonymous email message allowing them to judge how many users are using their client. To send this anonymous message, press kbd:[Enter]. Alternatively, press kbd:[E] to exit the greeting without sending an anonymous message. An example of the greeting page is shown below: -image::pine1.png[] +image::pine1.png[alpine email client showing the greeting page] The main menu is then presented, which can be navigated using the cursor keys. This main menu provides shortcuts for the composing new mails, browsing mail directories, and administering address book entries. Below the main menu, relevant keyboard shortcuts to perform functions specific to the task at hand are shown. The default directory opened by alpine is [.filename]#inbox#. To view the message index, press kbd:[I], or select the [.guimenuitem]#MESSAGE INDEX# option shown below: -image::pine2.png[] +image::pine2.png[alpine email client showing the default directory] The message index shows messages in the current directory and can be navigated by using the cursor keys. Highlighted messages can be read by pressing kbd:[Enter]. -image::pine3.png[] +image::pine3.png[alpine email client showing the message index] In the screenshot below, a sample message is displayed by alpine. Contextual keyboard shortcuts are displayed at the bottom of the screen. An example of one of a shortcut is kbd:[r], which tells the MUA to reply to the current message being displayed. -image::pine4.png[] +image::pine4.png[alpine email client showing an email] Replying to an email in alpine is done using the pico editor, which is installed by default with alpine. pico makes it easy to navigate the message and is easier for novice users to use than man:vi[1] or man:mail[1]. Once the reply is complete, the message can be sent by pressing kbd:[Ctrl+X]. alpine will ask for confirmation before sending the message. -image::pine5.png[] +image::pine5.png[alpine email client showing the message compose window] alpine can be customized using the [.guimenuitem]#SETUP# option from the main menu. Consult http://www.washington.edu/alpine/[http://www.washington.edu/alpine/] for more information. [[mail-fetchmail]] == Using fetchmail fetchmail is a full-featured IMAP and POP client. It allows users to automatically download mail from remote IMAP and POP servers and save it into local mailboxes where it can be accessed more easily. fetchmail can be installed using the package:mail/fetchmail[] port, and offers various features, including: * Support for the POP3, APOP, KPOP, IMAP, ETRN and ODMR protocols. * Ability to forward mail using SMTP, which allows filtering, forwarding, and aliasing to function normally. * May be run in daemon mode to check periodically for new messages. * Can retrieve multiple mailboxes and forward them, based on configuration, to different local users. This section explains some of the basic features of fetchmail. This utility requires a [.filename]#.fetchmailrc# configuration in the user's home directory in order to run correctly. This file includes server information as well as login credentials. Due to the sensitive nature of the contents of this file, it is advisable to make it readable only by the user, with the following command: [source,shell] .... % chmod 600 .fetchmailrc .... The following [.filename]#.fetchmailrc# serves as an example for downloading a single user mailbox using POP. It tells fetchmail to connect to `example.com` using a username of `joesoap` and a password of `XXX`. This example assumes that the user `joesoap` exists on the local system. [.programlisting] .... poll example.com protocol pop3 username "joesoap" password "XXX" .... The next example connects to multiple POP and IMAP servers and redirects to different local usernames where applicable: [.programlisting] .... poll example.com proto pop3: user "joesoap", with password "XXX", is "jsoap" here; user "andrea", with password "XXXX"; poll example2.net proto imap: user "john", with password "XXXXX", is "myth" here; .... fetchmail can be run in daemon mode by running it with `-d`, followed by the interval (in seconds) that fetchmail should poll servers listed in [.filename]#.fetchmailrc#. The following example configures fetchmail to poll every 600 seconds: [source,shell] .... % fetchmail -d 600 .... More information on fetchmail can be found at http://www.fetchmail.info/[http://www.fetchmail.info/]. [[mail-procmail]] == Using procmail procmail is a powerful application used to filter incoming mail. It allows users to define "rules" which can be matched to incoming mails to perform specific functions or to reroute mail to alternative mailboxes or email addresses. procmail can be installed using the package:mail/procmail[] port. Once installed, it can be directly integrated into most MTAs. Consult the MTA documentation for more information. Alternatively, procmail can be integrated by adding the following line to a [.filename]#.forward# in the home directory of the user: [.programlisting] .... "|exec /usr/local/bin/procmail || exit 75" .... The following section displays some basic procmail rules, as well as brief descriptions of what they do. Rules must be inserted into a [.filename]#.procmailrc#, which must reside in the user's home directory. The majority of these rules can be found in man:procmailex[5]. To forward all mail from mailto:user@example.com[user@example.com] to an external address of mailto:goodmail@example2.com[goodmail@example2.com]: [.programlisting] .... :0 * ^From.*user@example.com ! goodmail@example2.com .... To forward all mails shorter than 1000 bytes to an external address of mailto:goodmail@example2.com[goodmail@example2.com]: [.programlisting] .... :0 * < 1000 ! goodmail@example2.com .... To send all mail sent to mailto:alternate@example.com[alternate@example.com] to a mailbox called [.filename]#alternate#: [.programlisting] .... :0 * ^TOalternate@example.com alternate .... To send all mail with a subject of "Spam" to [.filename]#/dev/null#: [.programlisting] .... :0 ^Subject:.*Spam /dev/null .... A useful recipe that parses incoming `FreeBSD.org` mailing lists and places each list in its own mailbox: [.programlisting] .... :0 * ^Sender:.owner-freebsd-\/[^@]+@FreeBSD.ORG { LISTNAME=${MATCH} :0 * LISTNAME??^\/[^@]+ FreeBSD-${MATCH} } .... diff --git a/documentation/content/en/books/handbook/virtualization/_index.adoc b/documentation/content/en/books/handbook/virtualization/_index.adoc index f5223e72bd..6d4067d786 100644 --- a/documentation/content/en/books/handbook/virtualization/_index.adoc +++ b/documentation/content/en/books/handbook/virtualization/_index.adoc @@ -1,1172 +1,1172 @@ --- title: Chapter 23. Virtualization part: Part III. System Administration prev: books/handbook/filesystems next: books/handbook/l10n description: Virtualization software allows multiple operating systems to run simultaneously on the same computer tags: ["virtualization", "Parallels", "VMware", "VirtualBox", "bhyve", "XEN"] showBookMenu: true weight: 27 path: "/books/handbook/" --- [[virtualization]] = Virtualization :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 23 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/virtualization/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[virtualization-synopsis]] == Synopsis Virtualization software allows multiple operating systems to run simultaneously on the same computer. Such software systems for PCs often involve a host operating system which runs the virtualization software and supports any number of guest operating systems. After reading this chapter, you will know: * The difference between a host operating system and a guest operating system. * How to install FreeBSD on the following virtualization platforms: ** Parallels Desktop(Intel(R)-based Apple(R) macOS(R)) ** VMware Fusion(Intel(R)-based Apple(R) macOS(R)) ** VirtualBox(TM)(Microsoft(R) Windows(R), Intel(R)-based Apple(R) macOS(R), Linux) ** bhyve(FreeBSD) * How to tune a FreeBSD system for best performance under virtualization. Before reading this chapter, you should: * Understand the crossref:basics[basics,basics of UNIX(R) and FreeBSD]. * Know how to crossref:bsdinstall[bsdinstall,install FreeBSD]. * Know how to crossref:advanced-networking[advanced-networking,set up a network connection]. * Know how to crossref:ports[ports,install additional third-party software]. [[virtualization-guest-parallelsdesktop]] == FreeBSD as a Guest on Parallels Desktop for macOS(R) Parallels Desktop for Mac(R) is a commercial software product available for Intel(R) based Apple(R) Mac(R) computers running macOS(R) 10.4.6 or higher. FreeBSD is a fully supported guest operating system. Once Parallels has been installed on macOS(R), the user must configure a virtual machine and then install the desired guest operating system. [[virtualization-guest-parallelsdesktop-install]] === Installing FreeBSD on Parallels Desktop on Mac(R) The first step in installing FreeBSD on Parallels is to create a new virtual machine for installing FreeBSD. Select [.guimenuitem]#FreeBSD# as the menu:Guest OS Type[] when prompted: -image::parallels-freebsd1.png[] +image::parallels-freebsd1.png[Parallels setup wizard showing FreeBSD as chosen OS] Choose a reasonable amount of disk and memory depending on the plans for this virtual FreeBSD instance. 4GB of disk space and 512MB of RAM work well for most uses of FreeBSD under Parallels: -image::parallels-freebsd2.png[] +image::parallels-freebsd2.png[Parallels setup wizard showing the amount of RAM allocated] -image::parallels-freebsd3.png[] +image::parallels-freebsd3.png[Parallels setup wizard showing the disk menu] -image::parallels-freebsd4.png[] +image::parallels-freebsd4.png[Parallels setup wizard showing the menu for setting the disk size and type] -image::parallels-freebsd5.png[] +image::parallels-freebsd5.png[Parallels setup wizard showing the menu for setting the disk location] Select the type of networking and a network interface: -image::parallels-freebsd6.png[] +image::parallels-freebsd6.png[Parallels setup wizard showing the network menu] -image::parallels-freebsd7.png[] +image::parallels-freebsd7.png[Parallels setup wizard showing the menu with the network type options] Save and finish the configuration: -image::parallels-freebsd8.png[] +image::parallels-freebsd8.png[Parallels setup wizard showing the menu to configure the name of the machine and the directory where to save the configuration] -image::parallels-freebsd9.png[] +image::parallels-freebsd9.png[Parallels setup wizard indicating that the configuration is complete and asking the user if he wants to start guest OS installation] After the FreeBSD virtual machine has been created, FreeBSD can be installed on it. This is best done with an official FreeBSD CD/DVD or with an ISO image downloaded from an official FTP site. Copy the appropriate ISO image to the local Mac(R) filesystem or insert a CD/DVD in the Mac(R)'s CD-ROM drive. Click on the disc icon in the bottom right corner of the FreeBSD Parallels window. This will bring up a window that can be used to associate the CD-ROM drive in the virtual machine with the ISO file on disk or with the real CD-ROM drive. -image::parallels-freebsd11.png[] +image::parallels-freebsd11.png[Parallels showing a summary of the newly created machine with information and actions to execute on the machine] Once this association with the CD-ROM source has been made, reboot the FreeBSD virtual machine by clicking the reboot icon. Parallels will reboot with a special BIOS that first checks if there is a CD-ROM. -image::parallels-freebsd10.png[] +image::parallels-freebsd10.png[Parallels showing the BIOS running] In this case it will find the FreeBSD installation media and begin a normal FreeBSD installation. Perform the installation, but do not attempt to configure Xorg at this time. -image::parallels-freebsd12.png[] +image::parallels-freebsd12.png[Parallels showing a snippet of the FreeBSD installation process] When the installation is finished, reboot into the newly installed FreeBSD virtual machine. -image::parallels-freebsd13.png[] +image::parallels-freebsd13.png[Parallels showing the boot of FreeBSD] [[virtualization-guest-parallels-configure]] === Configuring FreeBSD on Parallels After FreeBSD has been successfully installed on macOS(R) X with Parallels, there are a number of configuration steps that can be taken to optimize the system for virtualized operation. [.procedure] . Set Boot Loader Variables + The most important step is to reduce the `kern.hz` tunable to reduce the CPU utilization of FreeBSD under the Parallels environment. This is accomplished by adding the following line to [.filename]#/boot/loader.conf#: + [.programlisting] .... kern.hz=100 .... + Without this setting, an idle FreeBSD Parallels guest will use roughly 15% of the CPU of a single processor iMac(R). After this change the usage will be closer to 5%. . Create a New Kernel Configuration File + All of the SCSI, FireWire, and USB device drivers can be removed from a custom kernel configuration file. Parallels provides a virtual network adapter used by the man:ed[4] driver, so all network devices except for man:ed[4] and man:miibus[4] can be removed from the kernel. . Configure Networking + The most basic networking setup uses DHCP to connect the virtual machine to the same local area network as the host Mac(R). This can be accomplished by adding `ifconfig_ed0="DHCP"` to [.filename]#/etc/rc.conf#. More advanced networking setups are described in crossref:advanced-networking[advanced-networking,Advanced Networking]. [[virtualization-guest-vmware]] == FreeBSD as a Guest on VMware Fusion for macOS(R) VMware Fusion for Mac(R) is a commercial software product available for Intel(R) based Apple(R) Mac(R) computers running macOS(R) 10.11 or higher. FreeBSD is a fully supported guest operating system. Once VMware Fusion has been installed on macOS(R), the user can configure a virtual machine and then install the desired guest operating system. [[virtualization-guest-vmware-install]] === Installing FreeBSD on VMware Fusion The first step is to start VMware Fusion which will load the Virtual Machine Library. Click [.guimenuitem]#+->New# to create the virtual machine: image::vmware-freebsd01.png[width=35%] This will load the New Virtual Machine Assistant. Choose [.guimenuitem]#Create a custom virtual machine# and click [.guimenuitem]#Continue# to proceed: image::vmware-freebsd02.png[width=45%] Select [.guimenuitem]#Other# as the [.guimenuitem]#Operating System# and either [.guimenuitem]#FreeBSD X# or [.guimenuitem]#FreeBSD X 64-bit#, as the menu:Version[] when prompted: image::vmware-freebsd03.png[width=45%] Choose the firmware(UEFI is recommended): image::vmware-freebsd04.png[width=45%] Choose [.guimenuitem]#Create a new virtual disk# and click [.guimenuitem]#Continue#: image::vmware-freebsd05.png[width=45%] Check the configuration and click [.guimenuitem]#Finish#: image::vmware-freebsd06.png[width=45%] Choose the name of the virtual machine and the directory where it should be saved: image::vmware-freebsd07.png[width=45%] Press command+E to open virtual machine settings and click [.guimenuitem]#CD/DVD#: image::vmware-freebsd08.png[width=45%] Choose FreeBSD ISO image or from a CD/DVD: image::vmware-freebsd09.png[width=45%] Start the virtual machine: image::vmware-freebsd10.png[width=25%] Install FreeBSD as usual: image::vmware-freebsd11.png[width=25%] Once the install is complete, the settings of the virtual machine can be modified, such as memory usage and the number of CPUs the virtual machine will have access to: [NOTE] ==== The System Hardware settings of the virtual machine cannot be modified while the virtual machine is running. ==== image::vmware-freebsd12.png[width=45%] The status of the CD-ROM device. Normally the CD/DVD/ISO is disconnected from the virtual machine when it is no longer needed. image::vmware-freebsd09.png[width=45%] The last thing to change is how the virtual machine will connect to the network. To allow connections to the virtual machine from other machines besides the host, choose [.guimenuitem]#Connect directly to the physical network (Bridged)#. Otherwise, [.guimenuitem]#Share the host's internet connection (NAT)# is preferred so that the virtual machine can have access to the Internet, but the network cannot access the virtual machine. image::vmware-freebsd13.png[width=45%] After modifying the settings, boot the newly installed FreeBSD virtual machine. [[virtualization-guest-vmware-configure]] === Configuring FreeBSD on VMware Fusion After FreeBSD has been successfully installed on macOS(R) X with VMware Fusion, there are a number of configuration steps that can be taken to optimize the system for virtualized operation. [.procedure] . Set Boot Loader Variables + The most important step is to reduce the `kern.hz` tunable to reduce the CPU utilization of FreeBSD under the VMware Fusion environment. This is accomplished by adding the following line to [.filename]#/boot/loader.conf#: + [.programlisting] .... kern.hz=100 .... + Without this setting, an idle FreeBSD VMware Fusion guest will use roughly 15% of the CPU of a single processor iMac(R). After this change, the usage will be closer to 5%. . Create a New Kernel Configuration File + All of the FireWire, and USB device drivers can be removed from a custom kernel configuration file. VMware Fusion provides a virtual network adapter used by the man:em[4] driver, so all network devices except for man:em[4] can be removed from the kernel. . Configure Networking + The most basic networking setup uses DHCP to connect the virtual machine to the same local area network as the host Mac(R). This can be accomplished by adding `ifconfig_em0="DHCP"` to [.filename]#/etc/rc.conf#. More advanced networking setups are described in crossref:advanced-networking[advanced-networking,Advanced Networking]. + . Install drivers and open-vm-tools + To run FreeBSD smoothly on VMWare, drivers should be installed: + [source,shell] .... # pkg install xf86-video-vmware xf86-input-vmmouse open-vm-tools .... [[virtualization-guest-virtualbox]] == FreeBSD as a Guest on VirtualBox(TM) FreeBSD works well as a guest in VirtualBox(TM). The virtualization software is available for most common operating systems, including FreeBSD itself. The VirtualBox(TM) guest additions provide support for: * Clipboard sharing. * Mouse pointer integration. * Host time synchronization. * Window scaling. * Seamless mode. [NOTE] ==== These commands are run in the FreeBSD guest. ==== First, install the package:emulators/virtualbox-ose-additions[] package or port in the FreeBSD guest. This will install the port: [source,shell] .... # cd /usr/ports/emulators/virtualbox-ose-additions && make install clean .... Add these lines to [.filename]#/etc/rc.conf#: [.programlisting] .... vboxguest_enable="YES" vboxservice_enable="YES" .... If man:ntpd[8] or man:ntpdate[8] is used, disable host time synchronization: [.programlisting] .... vboxservice_flags="--disable-timesync" .... Xorg will automatically recognize the `vboxvideo` driver. It can also be manually entered in [.filename]#/etc/X11/xorg.conf#: [.programlisting] .... Section "Device" Identifier "Card0" Driver "vboxvideo" VendorName "InnoTek Systemberatung GmbH" BoardName "VirtualBox Graphics Adapter" EndSection .... To use the `vboxmouse` driver, adjust the mouse section in [.filename]#/etc/X11/xorg.conf#: [.programlisting] .... Section "InputDevice" Identifier "Mouse0" Driver "vboxmouse" EndSection .... HAL users should create the following [.filename]#/usr/local/etc/hal/fdi/policy/90-vboxguest.fdi# or copy it from [.filename]#/usr/local/share/hal/fdi/policy/10osvendor/90-vboxguest.fdi#: [.programlisting] .... input input.mouse vboxmouse /dev/vboxguest .... Shared folders for file transfers between host and VM are accessible by mounting them using `mount_vboxvfs`. A shared folder can be created on the host using the VirtualBox GUI or via `vboxmanage`. For example, to create a shared folder called _myshare_ under [.filename]#/mnt/bsdboxshare# for the VM named _BSDBox_, run: [source,shell] .... # vboxmanage sharedfolder add 'BSDBox' --name myshare --hostpath /mnt/bsdboxshare .... Note that the shared folder name must not contain spaces. Mount the shared folder from within the guest system like this: [source,shell] .... # mount_vboxvfs -w myshare /mnt .... [[virtualization-host-virtualbox]] == FreeBSD as a Host with VirtualBox(TM) VirtualBox(TM) is an actively developed, complete virtualization package, that is available for most operating systems including Windows(R), macOS(R), Linux(R) and FreeBSD. It is equally capable of running Windows(R) or UNIX(R)-like guests. It is released as open source software, but with closed-source components available in a separate extension pack. These components include support for USB 2.0 devices. More information may be found on the http://www.virtualbox.org/wiki/Downloads[Downloads page of the VirtualBox(TM) wiki]. Currently, these extensions are not available for FreeBSD. [[virtualization-virtualbox-install]] === Installing VirtualBox(TM) VirtualBox(TM) is available as a FreeBSD package or port in package:emulators/virtualbox-ose[]. The port can be installed using these commands: [source,shell] .... # cd /usr/ports/emulators/virtualbox-ose # make install clean .... One useful option in the port's configuration menu is the `GuestAdditions` suite of programs. These provide a number of useful features in guest operating systems, like mouse pointer integration (allowing the mouse to be shared between host and guest without the need to press a special keyboard shortcut to switch) and faster video rendering, especially in Windows(R) guests. The guest additions are available in the menu:Devices[] menu, after the installation of the guest is finished. A few configuration changes are needed before VirtualBox(TM) is started for the first time. The port installs a kernel module in [.filename]#/boot/modules# which must be loaded into the running kernel: [source,shell] .... # kldload vboxdrv .... To ensure the module is always loaded after a reboot, add this line to [.filename]#/boot/loader.conf#: [.programlisting] .... vboxdrv_load="YES" .... To use the kernel modules that allow bridged or host-only networking, add this line to [.filename]#/etc/rc.conf# and reboot the computer: [.programlisting] .... vboxnet_enable="YES" .... The `vboxusers` group is created during installation of VirtualBox(TM). All users that need access to VirtualBox(TM) will have to be added as members of this group. `pw` can be used to add new members: [source,shell] .... # pw groupmod vboxusers -m yourusername .... The default permissions for [.filename]#/dev/vboxnetctl# are restrictive and need to be changed for bridged networking: [source,shell] .... # chown root:vboxusers /dev/vboxnetctl # chmod 0660 /dev/vboxnetctl .... To make this permissions change permanent, add these lines to [.filename]#/etc/devfs.conf#: [.programlisting] .... own vboxnetctl root:vboxusers perm vboxnetctl 0660 .... To launch VirtualBox(TM), type from an Xorg session: [source,shell] .... % VirtualBox .... For more information on configuring and using VirtualBox(TM), refer to the http://www.virtualbox.org[official website]. For FreeBSD-specific information and troubleshooting instructions, refer to the http://wiki.FreeBSD.org/VirtualBox[relevant page in the FreeBSD wiki]. [[virtualization-virtualbox-usb-support]] === VirtualBox(TM) USB Support VirtualBox(TM) can be configured to pass USB devices through to the guest operating system. The host controller of the OSE version is limited to emulating USB 1.1 devices until the extension pack supporting USB 2.0 and 3.0 devices becomes available on FreeBSD. For VirtualBox(TM) to be aware of USB devices attached to the machine, the user needs to be a member of the `operator` group. [source,shell] .... # pw groupmod operator -m yourusername .... Then, add the following to [.filename]#/etc/devfs.rules#, or create this file if it does not exist yet: [.programlisting] .... [system=10] add path 'usb/*' mode 0660 group operator .... To load these new rules, add the following to [.filename]#/etc/rc.conf#: [.programlisting] .... devfs_system_ruleset="system" .... Then, restart devfs: [source,shell] .... # service devfs restart .... Restart the login session and VirtualBox(TM) for these changes to take effect, and create USB filters as necessary. [[virtualization-virtualbox-host-dvd-cd-access]] === VirtualBox(TM) Host DVD/CD Access Access to the host DVD/CD drives from guests is achieved through the sharing of the physical drives. Within VirtualBox(TM), this is set up from the Storage window in the Settings of the virtual machine. If needed, create an empty IDECD/DVD device first. Then choose the Host Drive from the popup menu for the virtual CD/DVD drive selection. A checkbox labeled `Passthrough` will appear. This allows the virtual machine to use the hardware directly. For example, audio CDs or the burner will only function if this option is selected. HAL needs to run for VirtualBox(TM)DVD/CD functions to work, so enable it in [.filename]#/etc/rc.conf# and start it if it is not already running: [.programlisting] .... hald_enable="YES" .... [source,shell] .... # service hald start .... In order for users to be able to use VirtualBox(TM)DVD/CD functions, they need access to [.filename]#/dev/xpt0#, [.filename]#/dev/cdN#, and [.filename]#/dev/passN#. This is usually achieved by making the user a member of `operator`. Permissions to these devices have to be corrected by adding these lines to [.filename]#/etc/devfs.conf#: [.programlisting] .... perm cd* 0660 perm xpt0 0660 perm pass* 0660 .... [source,shell] .... # service devfs restart .... [[virtualization-host-bhyve]] == FreeBSD as a Host with bhyve The bhyve BSD-licensed hypervisor became part of the base system with FreeBSD 10.0-RELEASE. This hypervisor supports a number of guests, including FreeBSD, OpenBSD, and many Linux(R) distributions. By default, bhyve provides access to serial console and does not emulate a graphical console. Virtualization offload features of newer CPUs are used to avoid the legacy methods of translating instructions and manually managing memory mappings. The bhyve design requires a processor that supports Intel(R) Extended Page Tables (EPT) or AMD(R) Rapid Virtualization Indexing (RVI) or Nested Page Tables (NPT). Hosting Linux(R) guests or FreeBSD guests with more than one vCPU requires VMX unrestricted mode support (UG). Most newer processors, specifically the Intel(R) Core(TM) i3/i5/i7 and Intel(R) Xeon(TM) E3/E5/E7, support these features. UG support was introduced with Intel's Westmere micro-architecture. For a complete list of Intel(R) processors that support EPT, refer to https://ark.intel.com/content/www/us/en/ark/search/featurefilter.html?productType=873&0_ExtendedPageTables=True[]. RVI is found on the third generation and later of the AMD Opteron(TM) (Barcelona) processors. The easiest way to tell if a processor supports bhyve is to run `dmesg` or look in [.filename]#/var/run/dmesg.boot# for the `POPCNT` processor feature flag on the `Features2` line for AMD(R) processors or `EPT` and `UG` on the `VT-x` line for Intel(R) processors. [[virtualization-bhyve-prep]] === Preparing the Host The first step to creating a virtual machine in bhyve is configuring the host system. First, load the bhyve kernel module: [source,shell] .... # kldload vmm .... Then, create a [.filename]#tap# interface for the network device in the virtual machine to attach to. In order for the network device to participate in the network, also create a bridge interface containing the [.filename]#tap# interface and the physical interface as members. In this example, the physical interface is _igb0_: [source,shell] .... # ifconfig tap0 create # sysctl net.link.tap.up_on_open=1 net.link.tap.up_on_open: 0 -> 1 # ifconfig bridge0 create # ifconfig bridge0 addm igb0 addm tap0 # ifconfig bridge0 up .... [[virtualization-bhyve-freebsd]] === Creating a FreeBSD Guest Create a file to use as the virtual disk for the guest machine. Specify the size and name of the virtual disk: [source,shell] .... # truncate -s 16G guest.img .... Download an installation image of FreeBSD to install: [source,shell] .... # fetch ftp://ftp.freebsd.org/pub/FreeBSD/releases/ISO-IMAGES/12.2/FreeBSD-12.2-RELEASE-amd64-bootonly.iso FreeBSD-12.2-RELEASE-amd64-bootonly.iso 100% of 230 MB 570 kBps 06m17s .... FreeBSD comes with an example script for running a virtual machine in bhyve. The script will start the virtual machine and run it in a loop, so it will automatically restart if it crashes. The script takes a number of options to control the configuration of the machine: `-c` controls the number of virtual CPUs, `-m` limits the amount of memory available to the guest, `-t` defines which [.filename]#tap# device to use, `-d` indicates which disk image to use, `-i` tells bhyve to boot from the CD image instead of the disk, and `-I` defines which CD image to use. The last parameter is the name of the virtual machine, used to track the running machines. This example starts the virtual machine in installation mode: [source,shell] .... # sh /usr/share/examples/bhyve/vmrun.sh -c 1 -m 1024M -t tap0 -d guest.img -i -I FreeBSD-12.2-RELEASE-amd64-bootonly.iso guestname .... The virtual machine will boot and start the installer. After installing a system in the virtual machine, when the system asks about dropping in to a shell at the end of the installation, choose btn:[Yes]. Reboot the virtual machine. While rebooting the virtual machine causes bhyve to exit, the [.filename]#vmrun.sh# script runs `bhyve` in a loop and will automatically restart it. When this happens, choose the reboot option from the boot loader menu in order to escape the loop. Now the guest can be started from the virtual disk: [source,shell] .... # sh /usr/share/examples/bhyve/vmrun.sh -c 4 -m 1024M -t tap0 -d guest.img guestname .... [[virtualization-bhyve-linux]] === Creating a Linux(R) Guest In order to boot operating systems other than FreeBSD, the package:sysutils/grub2-bhyve[] port must be first installed. Next, create a file to use as the virtual disk for the guest machine: [source,shell] .... # truncate -s 16G linux.img .... Starting a virtual machine with bhyve is a two step process. First a kernel must be loaded, then the guest can be started. The Linux(R) kernel is loaded with package:sysutils/grub2-bhyve[]. Create a [.filename]#device.map# that grub will use to map the virtual devices to the files on the host system: [.programlisting] .... (hd0) ./linux.img (cd0) ./somelinux.iso .... Use package:sysutils/grub2-bhyve[] to load the Linux(R) kernel from the ISO image: [source,shell] .... # grub-bhyve -m device.map -r cd0 -M 1024M linuxguest .... This will start grub. If the installation CD contains a [.filename]#grub.cfg#, a menu will be displayed. If not, the `vmlinuz` and `initrd` files must be located and loaded manually: [source,shell] .... grub> ls (hd0) (cd0) (cd0,msdos1) (host) grub> ls (cd0)/isolinux boot.cat boot.msg grub.conf initrd.img isolinux.bin isolinux.cfg memtest splash.jpg TRANS.TBL vesamenu.c32 vmlinuz grub> linux (cd0)/isolinux/vmlinuz grub> initrd (cd0)/isolinux/initrd.img grub> boot .... Now that the Linux(R) kernel is loaded, the guest can be started: [source,shell] .... # bhyve -A -H -P -s 0:0,hostbridge -s 1:0,lpc -s 2:0,virtio-net,tap0 -s 3:0,virtio-blk,./linux.img \ -s 4:0,ahci-cd,./somelinux.iso -l com1,stdio -c 4 -m 1024M linuxguest .... The system will boot and start the installer. After installing a system in the virtual machine, reboot the virtual machine. This will cause bhyve to exit. The instance of the virtual machine needs to be destroyed before it can be started again: [source,shell] .... # bhyvectl --destroy --vm=linuxguest .... Now the guest can be started directly from the virtual disk. Load the kernel: [source,shell] .... # grub-bhyve -m device.map -r hd0,msdos1 -M 1024M linuxguest grub> ls (hd0) (hd0,msdos2) (hd0,msdos1) (cd0) (cd0,msdos1) (host) (lvm/VolGroup-lv_swap) (lvm/VolGroup-lv_root) grub> ls (hd0,msdos1)/ lost+found/ grub/ efi/ System.map-2.6.32-431.el6.x86_64 config-2.6.32-431.el6.x 86_64 symvers-2.6.32-431.el6.x86_64.gz vmlinuz-2.6.32-431.el6.x86_64 initramfs-2.6.32-431.el6.x86_64.img grub> linux (hd0,msdos1)/vmlinuz-2.6.32-431.el6.x86_64 root=/dev/mapper/VolGroup-lv_root grub> initrd (hd0,msdos1)/initramfs-2.6.32-431.el6.x86_64.img grub> boot .... Boot the virtual machine: [source,shell] .... # bhyve -A -H -P -s 0:0,hostbridge -s 1:0,lpc -s 2:0,virtio-net,tap0 \ -s 3:0,virtio-blk,./linux.img -l com1,stdio -c 4 -m 1024M linuxguest .... Linux(R) will now boot in the virtual machine and eventually present you with the login prompt. Login and use the virtual machine. When you are finished, reboot the virtual machine to exit bhyve. Destroy the virtual machine instance: [source,shell] .... # bhyvectl --destroy --vm=linuxguest .... [[virtualization-bhyve-uefi]] === Booting bhyve Virtual Machines with UEFI Firmware In addition to bhyveload and grub-bhyve, the bhyve hypervisor can also boot virtual machines using the UEFI userspace firmware. This option may support guest operating systems that are not supported by the other loaders. In order to make use of the UEFI support in bhyve, first obtain the UEFI firmware images. This can be done by installing package:sysutils/bhyve-firmware[] port or package. With the firmware in place, add the flags `-l bootrom,_/path/to/firmware_` to your bhyve command line. The actual bhyve command may look like this: [source,shell] .... # bhyve -AHP -s 0:0,hostbridge -s 1:0,lpc \ -s 2:0,virtio-net,tap1 -s 3:0,virtio-blk,./disk.img \ -s 4:0,ahci-cd,./install.iso -c 4 -m 1024M \ -l bootrom,/usr/local/share/uefi-firmware/BHYVE_UEFI.fd \ guest .... package:sysutils/bhyve-firmware[] also contains a CSM-enabled firmware, to boot guests with no UEFI support in legacy BIOS mode: [source,shell] .... # bhyve -AHP -s 0:0,hostbridge -s 1:0,lpc \ -s 2:0,virtio-net,tap1 -s 3:0,virtio-blk,./disk.img \ -s 4:0,ahci-cd,./install.iso -c 4 -m 1024M \ -l bootrom,/usr/local/share/uefi-firmware/BHYVE_UEFI_CSM.fd \ guest .... [[virtualization-bhyve-framebuffer]] === Graphical UEFI Framebuffer for bhyve Guests The UEFI firmware support is particularly useful with predominantly graphical guest operating systems such as Microsoft Windows(R). Support for the UEFI-GOP framebuffer may also be enabled with the `-s 29,fbuf,tcp=_0.0.0.0:5900_` flags. The framebuffer resolution may be configured with `w=_800_` and `h=_600_`, and bhyve can be instructed to wait for a VNC connection before booting the guest by adding `wait`. The framebuffer may be accessed from the host or over the network via the VNC protocol. Additionally, `-s 30,xhci,tablet` can be added to achieve precise mouse cursor synchronization with the host. The resulting bhyve command would look like this: [source,shell] .... # bhyve -AHP -s 0:0,hostbridge -s 31:0,lpc \ -s 2:0,virtio-net,tap1 -s 3:0,virtio-blk,./disk.img \ -s 4:0,ahci-cd,./install.iso -c 4 -m 1024M \ -s 29,fbuf,tcp=0.0.0.0:5900,w=800,h=600,wait \ -s 30,xhci,tablet \ -l bootrom,/usr/local/share/uefi-firmware/BHYVE_UEFI.fd \ guest .... Note, in BIOS emulation mode, the framebuffer will cease receiving updates once control is passed from firmware to guest operating system. [[virtualization-bhyve-zfs]] === Using ZFS with bhyve Guests If ZFS is available on the host machine, using ZFS volumes instead of disk image files can provide significant performance benefits for the guest VMs. A ZFS volume can be created by: [source,shell] .... # zfs create -V16G -o volmode=dev zroot/linuxdisk0 .... When starting the VM, specify the ZFS volume as the disk drive: [source,shell] .... # bhyve -A -H -P -s 0:0,hostbridge -s 1:0,lpc -s 2:0,virtio-net,tap0 -s3:0,virtio-blk,/dev/zvol/zroot/linuxdisk0 \ -l com1,stdio -c 4 -m 1024M linuxguest .... [[virtualization-bhyve-nmdm]] === Virtual Machine Consoles It is advantageous to wrap the bhyve console in a session management tool such as package:sysutils/tmux[] or package:sysutils/screen[] in order to detach and reattach to the console. It is also possible to have the console of bhyve be a null modem device that can be accessed with `cu`. To do this, load the [.filename]#nmdm# kernel module and replace `-l com1,stdio` with `-l com1,/dev/nmdm0A`. The [.filename]#/dev/nmdm# devices are created automatically as needed, where each is a pair, corresponding to the two ends of the null modem cable ([.filename]#/dev/nmdm0A# and [.filename]#/dev/nmdm0B#). See man:nmdm[4] for more information. [source,shell] .... # kldload nmdm # bhyve -A -H -P -s 0:0,hostbridge -s 1:0,lpc -s 2:0,virtio-net,tap0 -s 3:0,virtio-blk,./linux.img \ -l com1,/dev/nmdm0A -c 4 -m 1024M linuxguest # cu -l /dev/nmdm0B Connected Ubuntu 13.10 handbook ttyS0 handbook login: .... [[virtualization-bhyve-managing]] === Managing Virtual Machines A device node is created in [.filename]#/dev/vmm# for each virtual machine. This allows the administrator to easily see a list of the running virtual machines: [source,shell] .... # ls -al /dev/vmm total 1 dr-xr-xr-x 2 root wheel 512 Mar 17 12:19 ./ dr-xr-xr-x 14 root wheel 512 Mar 17 06:38 ../ crw------- 1 root wheel 0x1a2 Mar 17 12:20 guestname crw------- 1 root wheel 0x19f Mar 17 12:19 linuxguest crw------- 1 root wheel 0x1a1 Mar 17 12:19 otherguest .... A specified virtual machine can be destroyed using `bhyvectl`: [source,shell] .... # bhyvectl --destroy --vm=guestname .... [[virtualization-bhyve-onboot]] === Persistent Configuration In order to configure the system to start bhyve guests at boot time, the following configurations must be made in the specified files: [.procedure] . [.filename]#/etc/sysctl.conf# + [.programlisting] .... net.link.tap.up_on_open=1 .... . [.filename]#/etc/rc.conf# + [.programlisting] .... cloned_interfaces="bridge0 tap0" ifconfig_bridge0="addm igb0 addm tap0" kld_list="nmdm vmm" .... [[virtualization-host-xen]] == FreeBSD as a Xen(TM)-Host Xen is a GPLv2-licensed https://en.wikipedia.org/wiki/Hypervisor#Classification[type 1 hypervisor] for Intel(R) and ARM(R) architectures. FreeBSD has included i386(TM) and AMD(R) 64-Bit https://wiki.xenproject.org/wiki/DomU[DomU] and https://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud[Amazon EC2] unprivileged domain (virtual machine) support since FreeBSD 8.0 and includes Dom0 control domain (host) support in FreeBSD 11.0. Support for para-virtualized (PV) domains has been removed from FreeBSD 11 in favor of hardware virtualized (HVM) domains, which provides better performance. Xen(TM) is a bare-metal hypervisor, which means that it is the first program loaded after the BIOS. A special privileged guest called the Domain-0 (`Dom0` for short) is then started. The Dom0 uses its special privileges to directly access the underlying physical hardware, making it a high-performance solution. It is able to access the disk controllers and network adapters directly. The Xen(TM) management tools to manage and control the Xen(TM) hypervisor are also used by the Dom0 to create, list, and destroy VMs. Dom0 provides virtual disks and networking for unprivileged domains, often called `DomU`. Xen(TM) Dom0 can be compared to the service console of other hypervisor solutions, while the DomU is where individual guest VMs are run. Xen(TM) can migrate VMs between different Xen(TM) servers. When the two xen hosts share the same underlying storage, the migration can be done without having to shut the VM down first. Instead, the migration is performed live while the DomU is running and there is no need to restart it or plan a downtime. This is useful in maintenance scenarios or upgrade windows to ensure that the services provided by the DomU are still provided. Many more features of Xen(TM) are listed on the https://wiki.xenproject.org/wiki/Category:Overview[Xen Wiki Overview page]. Note that not all features are supported on FreeBSD yet. [[virtualization-host-xen-requirements]] === Hardware Requirements for Xen(TM) Dom0 To run the Xen(TM) hypervisor on a host, certain hardware functionality is required. Hardware virtualized domains require Extended Page Table (http://en.wikipedia.org/wiki/Extended_Page_Table[EPT]) and Input/Output Memory Management Unit (http://en.wikipedia.org/wiki/List_of_IOMMU-supporting_hardware[IOMMU]) support in the host processor. [NOTE] ==== In order to run a FreeBSD Xen(TM) Dom0 the box must be booted using legacy boot (BIOS). ==== [[virtualization-host-xen-dom0-setup]] === Xen(TM) Dom0 Control Domain Setup Users of FreeBSD 11 should install the package:emulators/xen-kernel47[] and package:sysutils/xen-tools47[] packages that are based on Xen version 4.7. Systems running on FreeBSD-12.0 or newer can use Xen 4.11 provided by package:emulators/xen-kernel411[] and package:sysutils/xen-tools411[], respectively. Configuration files must be edited to prepare the host for the Dom0 integration after the Xen packages are installed. An entry to [.filename]#/etc/sysctl.conf# disables the limit on how many pages of memory are allowed to be wired. Otherwise, DomU VMs with higher memory requirements will not run. [source,shell] .... # echo 'vm.max_wired=-1' >> /etc/sysctl.conf .... Another memory-related setting involves changing [.filename]#/etc/login.conf#, setting the `memorylocked` option to `unlimited`. Otherwise, creating DomU domains may fail with `Cannot allocate memory` errors. After making the change to [.filename]#/etc/login.conf#, run `cap_mkdb` to update the capability database. See crossref:security[security-resourcelimits,"Resource Limits"] for details. [source,shell] .... # sed -i '' -e 's/memorylocked=64K/memorylocked=unlimited/' /etc/login.conf # cap_mkdb /etc/login.conf .... Add an entry for the Xen(TM) console to [.filename]#/etc/ttys#: [source,shell] .... # echo 'xc0 "/usr/libexec/getty Pc" xterm onifconsole secure' >> /etc/ttys .... Selecting a Xen(TM) kernel in [.filename]#/boot/loader.conf# activates the Dom0. Xen(TM) also requires resources like CPU and memory from the host machine for itself and other DomU domains. How much CPU and memory depends on the individual requirements and hardware capabilities. In this example, 8 GB of memory and 4 virtual CPUs are made available for the Dom0. The serial console is also activated and logging options are defined. The following command is used for Xen 4.7 packages: [source,shell] .... # echo 'hw.pci.mcfg=0' >> /boot/loader.conf # echo 'if_tap_load="YES"' >> /boot/loader.conf # echo 'xen_kernel="/boot/xen"' >> /boot/loader.conf # echo 'xen_cmdline="dom0_mem=8192M dom0_max_vcpus=4 dom0pvh=1 console=com1,vga com1=115200,8n1 guest_loglvl=all loglvl=all"' >> /boot/loader.conf .... For Xen versions 4.11 and higher, the following command should be used instead: [source,shell] .... # echo 'if_tap_load="YES"' >> /boot/loader.conf # echo 'xen_kernel="/boot/xen"' >> /boot/loader.conf # echo 'xen_cmdline="dom0_mem=8192M dom0_max_vcpus=4 dom0=pvh console=com1,vga com1=115200,8n1 guest_loglvl=all loglvl=all"' >> /boot/loader.conf .... [TIP] ==== Log files that Xen(TM) creates for the DomU VMs are stored in [.filename]#/var/log/xen#. Please be sure to check the contents of that directory if experiencing issues. ==== Activate the xencommons service during system startup: [source,shell] .... # sysrc xencommons_enable=yes .... These settings are enough to start a Dom0-enabled system. However, it lacks network functionality for the DomU machines. To fix that, define a bridged interface with the main NIC of the system which the DomU VMs can use to connect to the network. Replace _em0_ with the host network interface name. [source,shell] .... # sysrc cloned_interfaces="bridge0" # sysrc ifconfig_bridge0="addm em0 SYNCDHCP" # sysrc ifconfig_em0="up" .... Restart the host to load the Xen(TM) kernel and start the Dom0. [source,shell] .... # reboot .... After successfully booting the Xen(TM) kernel and logging into the system again, the Xen(TM) management tool `xl` is used to show information about the domains. [source,shell] .... # xl list Name ID Mem VCPUs State Time(s) Domain-0 0 8192 4 r----- 962.0 .... The output confirms that the Dom0 (called `Domain-0`) has the ID `0` and is running. It also has the memory and virtual CPUs that were defined in [.filename]#/boot/loader.conf# earlier. More information can be found in the https://www.xenproject.org/help/documentation.html[Xen(TM) Documentation]. DomU guest VMs can now be created. [[virtualization-host-xen-domu-setup]] === Xen(TM) DomU Guest VM Configuration Unprivileged domains consist of a configuration file and virtual or physical hard disks. Virtual disk storage for the DomU can be files created by man:truncate[1] or ZFS volumes as described in crossref:zfs[zfs-zfs-volume,“Creating and Destroying Volumes”]. In this example, a 20 GB volume is used. A VM is created with the ZFS volume, a FreeBSD ISO image, 1 GB of RAM and two virtual CPUs. The ISO installation file is retrieved with man:fetch[1] and saved locally in a file called [.filename]#freebsd.iso#. [source,shell] .... # fetch ftp://ftp.freebsd.org/pub/FreeBSD/releases/ISO-IMAGES/12.0/FreeBSD-12.0-RELEASE-amd64-bootonly.iso -o freebsd.iso .... A ZFS volume of 20 GB called [.filename]#xendisk0# is created to serve as the disk space for the VM. [source,shell] .... # zfs create -V20G -o volmode=dev zroot/xendisk0 .... The new DomU guest VM is defined in a file. Some specific definitions like name, keymap, and VNC connection details are also defined. The following [.filename]#freebsd.cfg# contains a minimum DomU configuration for this example: [source,shell] .... # cat freebsd.cfg builder = "hvm" <.> name = "freebsd" <.> memory = 1024 <.> vcpus = 2 <.> vif = [ 'mac=00:16:3E:74:34:32,bridge=bridge0' ] <.> disk = [ '/dev/zvol/tank/xendisk0,raw,hda,rw', <.> '/root/freebsd.iso,raw,hdc:cdrom,r' <.> ] vnc = 1 <.> vnclisten = "0.0.0.0" serial = "pty" usbdevice = "tablet" .... These lines are explained in more detail: <.> This defines what kind of virtualization to use. `hvm` refers to hardware-assisted virtualization or hardware virtual machine. Guest operating systems can run unmodified on CPUs with virtualization extensions, providing nearly the same performance as running on physical hardware. `generic` is the default value and creates a PV domain. <.> Name of this virtual machine to distinguish it from others running on the same Dom0. Required. <.> Quantity of RAM in megabytes to make available to the VM. This amount is subtracted from the hypervisor's total available memory, not the memory of the Dom0. <.> Number of virtual CPUs available to the guest VM. For best performance, do not create guests with more virtual CPUs than the number of physical CPUs on the host. <.> Virtual network adapter. This is the bridge connected to the network interface of the host. The `mac` parameter is the MAC address set on the virtual network interface. This parameter is optional, if no MAC is provided Xen(TM) will generate a random one. <.> Full path to the disk, file, or ZFS volume of the disk storage for this VM. Options and multiple disk definitions are separated by commas. <.> Defines the Boot medium from which the initial operating system is installed. In this example, it is the ISO image downloaded earlier. Consult the Xen(TM) documentation for other kinds of devices and options to set. <.> Options controlling VNC connectivity to the serial console of the DomU. In order, these are: active VNC support, define IP address on which to listen, device node for the serial console, and the input method for precise positioning of the mouse and other input methods. `keymap` defines which keymap to use, and is `english` by default. After the file has been created with all the necessary options, the DomU is created by passing it to `xl create` as a parameter. [source,shell] .... # xl create freebsd.cfg .... [NOTE] ==== Each time the Dom0 is restarted, the configuration file must be passed to `xl create` again to re-create the DomU. By default, only the Dom0 is created after a reboot, not the individual VMs. The VMs can continue where they left off as they stored the operating system on the virtual disk. The virtual machine configuration can change over time (for example, when adding more memory). The virtual machine configuration files must be properly backed up and kept available to be able to re-create the guest VM when needed. ==== The output of `xl list` confirms that the DomU has been created. [source,shell] .... # xl list Name ID Mem VCPUs State Time(s) Domain-0 0 8192 4 r----- 1653.4 freebsd 1 1024 1 -b---- 663.9 .... To begin the installation of the base operating system, start the VNC client, directing it to the main network address of the host or to the IP address defined on the `vnclisten` line of [.filename]#freebsd.cfg#. After the operating system has been installed, shut down the DomU and disconnect the VNC viewer. Edit [.filename]#freebsd.cfg#, removing the line with the `cdrom` definition or commenting it out by inserting a `+#+` character at the beginning of the line. To load this new configuration, it is necessary to remove the old DomU with `xl destroy`, passing either the name or the id as the parameter. Afterwards, recreate it using the modified [.filename]*freebsd.cfg*. [source,shell] .... # xl destroy freebsd # xl create freebsd.cfg .... The machine can then be accessed again using the VNC viewer. This time, it will boot from the virtual disk where the operating system has been installed and can be used as a virtual machine. [[virtualization-host-xen-troubleshooting]] === Troubleshooting This section contains basic information in order to help troubleshoot issues found when using FreeBSD as a Xen(TM) host or guest. [[virtualization-host-xen-troubleshooting-host]] ==== Host Boot Troubleshooting Please note that the following troubleshooting tips are intended for Xen(TM) 4.11 or newer. If you are still using Xen(TM) 4.7 and having issues consider migrating to a newer version of Xen(TM). In order to troubleshoot host boot issues you will likely need a serial cable, or a debug USB cable. Verbose Xen(TM) boot output can be obtained by adding options to the `xen_cmdline` option found in [.filename]#loader.conf#. A couple of relevant debug options are: * `iommu=debug`: can be used to print additional diagnostic information about the iommu. * `dom0=verbose`: can be used to print additional diagnostic information about the dom0 build process. * `sync_console`: flag to force synchronous console output. Useful for debugging to avoid losing messages due to rate limiting. Never use this option in production environments since it can allow malicious guests to perform DoS attacks against Xen(TM) using the console. FreeBSD should also be booted in verbose mode in order to identify any issues. To activate verbose booting, run this command: [source,shell] .... # echo 'boot_verbose="YES"' >> /boot/loader.conf .... If none of these options help solving the problem, please send the serial boot log to mailto:freebsd-xen@FreeBSD.org[freebsd-xen@FreeBSD.org] and mailto:xen-devel@lists.xenproject.org[xen-devel@lists.xenproject.org] for further analysis. [[virtualization-host-xen-troubleshooting-guest]] ==== Guest Creation Troubleshooting Issues can also arise when creating guests, the following attempts to provide some help for those trying to diagnose guest creation issues. The most common cause of guest creation failures is the `xl` command spitting some error and exiting with a return code different than 0. If the error provided is not enough to help identify the issue, more verbose output can also be obtained from `xl` by using the `v` option repeatedly. [source,shell] .... # xl -vvv create freebsd.cfg Parsing config from freebsd.cfg libxl: debug: libxl_create.c:1693:do_domain_create: Domain 0:ao 0x800d750a0: create: how=0x0 callback=0x0 poller=0x800d6f0f0 libxl: debug: libxl_device.c:397:libxl__device_disk_set_backend: Disk vdev=xvda spec.backend=unknown libxl: debug: libxl_device.c:432:libxl__device_disk_set_backend: Disk vdev=xvda, using backend phy libxl: debug: libxl_create.c:1018:initiate_domain_create: Domain 1:running bootloader libxl: debug: libxl_bootloader.c:328:libxl__bootloader_run: Domain 1:not a PV/PVH domain, skipping bootloader libxl: debug: libxl_event.c:689:libxl__ev_xswatch_deregister: watch w=0x800d96b98: deregister unregistered domainbuilder: detail: xc_dom_allocate: cmdline="", features="" domainbuilder: detail: xc_dom_kernel_file: filename="/usr/local/lib/xen/boot/hvmloader" domainbuilder: detail: xc_dom_malloc_filemap : 326 kB libxl: debug: libxl_dom.c:988:libxl__load_hvm_firmware_module: Loading BIOS: /usr/local/share/seabios/bios.bin ... .... If the verbose output does not help diagnose the issue there are also QEMU and Xen(TM) toolstack logs in [.filename]#/var/log/xen#. Note that the name of the domain is appended to the log name, so if the domain is named `freebsd` you should find a [.filename]#/var/log/xen/xl-freebsd.log# and likely a [.filename]#/var/log/xen/qemu-dm-freebsd.log#. Both log files can contain useful information for debugging. If none of this helps solve the issue, please send the description of the issue you are facing and as much information as possible to mailto:freebsd-xen@FreeBSD.org[freebsd-xen@FreeBSD.org] and mailto:xen-devel@lists.xenproject.org[xen-devel@lists.xenproject.org] in order to get help.