Dieser Inhalt ist in der von Ihnen ausgewählten Sprache nicht verfügbar.
Deploying different types of servers
Setting up and configuring web servers and reverse proxies, network file services, database servers, mail transport agents, and printers
Abstract
Providing feedback on Red Hat documentation Link kopierenLink in die Zwischenablage kopiert!
We appreciate your feedback on our documentation. Let us know how we can improve it.
Submitting feedback through Jira (account required)
- Log in to the Jira website.
- Click Create in the top navigation bar.
- Enter a descriptive title in the Summary field.
- Enter your suggestion for improvement in the Description field. Include links to the relevant parts of the documentation.
- Click Create at the bottom of the dialogue.
Chapter 1. Setting up the Apache HTTP web server Link kopierenLink in die Zwischenablage kopiert!
1.1. Introduction to the Apache HTTP web server Link kopierenLink in die Zwischenablage kopiert!
A web server is a network service that serves content to a client over the web. This typically means web pages, but any other documents can be served as well. Web servers are also known as HTTP servers, as they use the hypertext transport protocol (HTTP).
The Apache HTTP Server, httpd, is an open source web server developed by the Apache Software Foundation.
If you are upgrading from a previous release of Red Hat Enterprise Linux, you have to update the httpd service configuration accordingly. This section reviews some of the newly added features, and guides you through the update of prior configuration files.
1.2. Notable changes in the Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
The Apache HTTP Server has been updated from version 2.4.6 in RHEL 7 to version 2.4.37 in RHEL 8. This updated version includes several new features, but maintains backwards compatibility with the RHEL 7 version at the level of configuration and Application Binary Interface (ABI) of external modules.
New features include:
-
HTTP/2support is now provided by themod_http2package, which is a part of thehttpdmodule. -
systemd socket activation is supported. See
httpd.socket(8)man page for more details.
Multiple new modules have been added:
-
mod_proxy_hcheck- a proxy health-check module -
mod_proxy_uwsgi- a Web Server Gateway Interface (WSGI) proxy -
mod_proxy_fdpass- provides support for the passing the socket of the client to another process -
mod_cache_socache- an HTTP cache using, for example, memcache backend -
mod_md- an ACME protocol SSL/TLS certificate service
-
The following modules now load by default:
-
mod_request -
mod_macro -
mod_watchdog
-
-
A new subpackage,
httpd-filesystem, has been added, which contains the basic directory layout for the Apache HTTP Server including the correct permissions for the directories. -
Instantiated service support,
httpd@.servicehas been introduced. See thehttpd.serviceman page for more information.
-
A new
httpd-init.servicereplaces the%post scriptto create a self-signedmod_sslkey pair.
-
Automated TLS certificate provisioning and renewal using the Automatic Certificate Management Environment (ACME) protocol is now supported with the
mod_mdpackage (for use with certificate providers such asLet’s Encrypt). -
The Apache HTTP Server now supports loading TLS certificates and private keys from hardware security tokens directly from
PKCS#11modules. As a result, amod_sslconfiguration can now usePKCS#11URLs to identify the TLS private key, and, optionally, the TLS certificate in theSSLCertificateKeyFileandSSLCertificateFiledirectives. A new
ListenFreedirective in the/etc/httpd/conf/httpd.conffile is now supported.Similarly to the
Listendirective,ListenFreeprovides information about IP addresses, ports, or IP address-and-port combinations that the server listens to. However, withListenFree, theIP_FREEBINDsocket option is enabled by default. Hence,httpdis allowed to bind to a nonlocal IP address or to an IP address that does not exist yet. This allowshttpdto listen on a socket without requiring the underlying network interface or the specified dynamic IP address to be up at the time whenhttpdis trying to bind to it.Note that the
ListenFreedirective is currently available only in RHEL 8.For more details on
ListenFree, see the following table:Expand Table 1.1. ListenFree directive’s syntax, status, and modules Syntax Status Modules ListenFree [IP-address:]portnumber [protocol]
MPM
event, worker, prefork, mpm_winnt, mpm_netware, mpmt_os2
Other notable changes include:
The following modules have been removed:
-
mod_file_cache mod_nssUse
mod_sslas a replacement. For details about migrating frommod_nss, see Section 1.14, “Exporting a private key and certificates from an NSS database to use them in an Apache web server configuration”.-
mod_perl
-
-
The default type of the DBM authentication database used by the Apache HTTP Server in RHEL 8 has been changed from
SDBMtodb5. -
The
mod_wsgimodule for the Apache HTTP Server has been updated to Python 3. WSGI applications are now supported only with Python 3, and must be migrated from Python 2. The multi-processing module (MPM) configured by default with the Apache HTTP Server has changed from a multi-process, forked model (known as
prefork) to a high-performance multi-threaded model,event.Any third-party modules that are not thread-safe need to be replaced or removed. To change the configured MPM, edit the
/etc/httpd/conf.modules.d/00-mpm.conffile. See thehttpd.service(8)man page for more information.- The minimum UID and GID allowed for users by suEXEC are now 1000 and 500, respectively (previously 100 and 100).
-
The
/etc/sysconfig/httpdfile is no longer a supported interface for setting environment variables for thehttpdservice. Thehttpd.service(8)man page has been added for the systemd service. -
Stopping the
httpdservice now uses a “graceful stop” by default. -
The
mod_auth_kerbmodule has been replaced by themod_auth_gssapimodule.
1.3. Updating the configuration Link kopierenLink in die Zwischenablage kopiert!
To update the configuration files from the Apache HTTP Server version used in Red Hat Enterprise Linux 7, choose one of the following options:
-
If
/etc/sysconfig/httpdis used to set environment variables, create a systemd drop-in file instead. - If any third-party modules are used, ensure they are compatible with a threaded MPM.
- If suexec is used, ensure user and group IDs meet the new minimums.
You can check the configuration for possible errors by using the following command:
apachectl configtest
# apachectl configtest
Syntax OK
1.4. The Apache configuration files Link kopierenLink in die Zwischenablage kopiert!
The httpd, by default, reads the configuration files after start. You can see the list of the locations of configuration files in the table below.
| Path | Description |
|---|---|
|
| The main configuration file. |
|
| An auxiliary directory for configuration files that are included in the main configuration file. |
|
| An auxiliary directory for configuration files which load installed dynamic modules packaged in Red Hat Enterprise Linux. In the default configuration, these configuration files are processed first. |
Although the default configuration is suitable for most situations, you can use also other configuration options. For any changes to take effect, restart the web server first.
To check the configuration for possible errors, type the following at a shell prompt:
apachectl configtest
# apachectl configtest
Syntax OK
To make the recovery from mistakes easier, make a copy of the original file before editing it.
1.5. Managing the httpd service Link kopierenLink in die Zwischenablage kopiert!
This section describes how to start, stop, and restart the httpd service.
Prerequisites
- The Apache HTTP Server is installed.
Procedure
To start the
httpdservice, enter:systemctl start httpd
# systemctl start httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow To stop the
httpdservice, enter:systemctl stop httpd
# systemctl stop httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow To restart the
httpdservice, enter:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
1.6. Setting up a single-instance Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
You can set up a single-instance Apache HTTP Server to serve static HTML content.
Follow the procedure if the web server should provide the same content for all domains associated with the server. If you want to provide different content for different domains, set up name-based virtual hosts. For details, see Configuring Apache name-based virtual hosts.
Procedure
Install the
httpdpackage:yum install httpd
# yum install httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you use
firewalld, open the TCP port80in the local firewall:firewall-cmd --permanent --add-port=80/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=80/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
httpdservice:systemctl enable --now httpd
# systemctl enable --now httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Add HTML files to the
/var/www/html/directory.NoteWhen adding content to
/var/www/html/, files and directories must be readable by the user under whichhttpdruns by default. The content owner can be either therootuser androotuser group, or another user or group of the administrator’s choice. If the content owner is therootuser androotuser group, the files must be readable by other users. The SELinux context for all the files and directories must behttpd_sys_content_t, which is applied by default to all content within the/var/wwwdirectory.
Verification
Connect with a web browser to
http://server_IP_or_host_name/.If the
/var/www/html/directory is empty or does not contain anindex.htmlorindex.htmfile, Apache displays theRed Hat Enterprise Linux Test Page. If/var/www/html/contains HTML files with a different name, you can load them by entering the URL to that file, such ashttp://server_IP_or_host_name/example.html.
1.7. Configuring Apache name-based virtual hosts Link kopierenLink in die Zwischenablage kopiert!
Name-based virtual hosts enable Apache to serve different content for different domains that resolve to the IP address of the server.
You can set up a virtual host for both the example.com and example.net domain with separate document root directories. Both virtual hosts serve static HTML content.
Prerequisites
Clients and the web server resolve the
example.comandexample.netdomain to the IP address of the web server.Note that you must manually add these entries to your DNS server.
Procedure
Install the
httpdpackage:yum install httpd
# yum install httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/httpd/conf/httpd.conffile:Append the following virtual host configuration for the
example.comdomain:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings configure the following:
-
All settings in the
<VirtualHost *:80>directive are specific for this virtual host. -
DocumentRootsets the path to the web content of the virtual host. ServerNamesets the domains for which this virtual host serves content.To set multiple domains, add the
ServerAliasparameter to the configuration and specify the additional domains separated with a space in this parameter.-
CustomLogsets the path to the access log of the virtual host. ErrorLogsets the path to the error log of the virtual host.NoteApache uses the first virtual host found in the configuration also for requests that do not match any domain set in the
ServerNameandServerAliasparameters. This also includes requests sent to the IP address of the server.
-
All settings in the
Append a similar virtual host configuration for the
example.netdomain:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create the document roots for both virtual hosts:
mkdir /var/www/example.com/ mkdir /var/www/example.net/
# mkdir /var/www/example.com/ # mkdir /var/www/example.net/Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you set paths in the
DocumentRootparameters that are not within/var/www/, set thehttpd_sys_content_tcontext on both document roots:semanage fcontext -a -t httpd_sys_content_t "/srv/example.com(/.*)?" restorecon -Rv /srv/example.com/ semanage fcontext -a -t httpd_sys_content_t "/srv/example.net(/.\*)?" restorecon -Rv /srv/example.net/
# semanage fcontext -a -t httpd_sys_content_t "/srv/example.com(/.*)?" # restorecon -Rv /srv/example.com/ # semanage fcontext -a -t httpd_sys_content_t "/srv/example.net(/.\*)?" # restorecon -Rv /srv/example.net/Copy to Clipboard Copied! Toggle word wrap Toggle overflow These commands set the
httpd_sys_content_tcontext on the/srv/example.com/and/srv/example.net/directory.Note that you must install the
policycoreutils-python-utilspackage to run therestoreconcommand.If you use
firewalld, open port80in the local firewall:firewall-cmd --permanent --add-port=80/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=80/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
httpdservice:systemctl enable --now httpd
# systemctl enable --now httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Create a different example file in each virtual host’s document root:
echo "vHost example.com" > /var/www/example.com/index.html echo "vHost example.net" > /var/www/example.net/index.html
# echo "vHost example.com" > /var/www/example.com/index.html # echo "vHost example.net" > /var/www/example.net/index.htmlCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Use a browser and connect to
http://example.com. The web server shows the example file from theexample.comvirtual host. -
Use a browser and connect to
http://example.net. The web server shows the example file from theexample.netvirtual host.
1.8. Configuring Kerberos authentication for the Apache HTTP web server Link kopierenLink in die Zwischenablage kopiert!
To perform Kerberos authentication in the Apache HTTP web server, RHEL 8 uses the mod_auth_gssapi Apache module. The Generic Security Services API (GSSAPI) is an interface for applications that make requests to use security libraries, such as Kerberos. The gssproxy service allows to implement privilege separation for the httpd server, which optimizes this process from the security point of view.
The mod_auth_gssapi module replaces the removed mod_auth_kerb module.
Prerequisites
-
The
httpdandgssproxypackages are installed. -
The Apache web server is set up and the
httpdservice is running.
1.8.1. Setting up GSS-Proxy in an IdM environment Link kopierenLink in die Zwischenablage kopiert!
This procedure describes how to set up GSS-Proxy to perform Kerberos authentication in the Apache HTTP web server.
Procedure
Enable access to the
keytabfile of HTTP/<SERVER_NAME>@realm principal by creating the service principal:ipa service-add HTTP/<SERVER_NAME>
# ipa service-add HTTP/<SERVER_NAME>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Retrieve the
keytabfor the principal stored in the/etc/gssproxy/http.keytabfile:ipa-getkeytab -s $(awk '/^server =/ {print $3}' /etc/ipa/default.conf) -k /etc/gssproxy/http.keytab -p HTTP/$(hostname -f)# ipa-getkeytab -s $(awk '/^server =/ {print $3}' /etc/ipa/default.conf) -k /etc/gssproxy/http.keytab -p HTTP/$(hostname -f)Copy to Clipboard Copied! Toggle word wrap Toggle overflow This step sets permissions to 400, thus only the
rootuser has access to thekeytabfile. Theapacheuser does not.Create the
/etc/gssproxy/80-httpd.conffile with the following content:[service/HTTP] mechs = krb5 cred_store = keytab:/etc/gssproxy/http.keytab cred_store = ccache:/var/lib/gssproxy/clients/krb5cc_%U euid = apache
[service/HTTP] mechs = krb5 cred_store = keytab:/etc/gssproxy/http.keytab cred_store = ccache:/var/lib/gssproxy/clients/krb5cc_%U euid = apacheCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart and enable the
gssproxyservice:systemctl restart gssproxy.service systemctl enable gssproxy.service
# systemctl restart gssproxy.service # systemctl enable gssproxy.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
1.9. Configuring TLS encryption on an Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
By default, Apache provides content to clients using an unencrypted HTTP connection. This section describes how to enable TLS encryption and configure frequently used encryption-related settings on an Apache HTTP Server.
Prerequisites
- The Apache HTTP Server is installed and running.
1.9.1. Adding TLS encryption to an Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
You can enable TLS encryption on an Apache HTTP Server for the example.com domain.
Prerequisites
- The Apache HTTP Server is installed and running.
The private key is stored in the
/etc/pki/tls/private/example.com.keyfile.For details about creating a private key and certificate signing request (CSR), as well as how to request a certificate from a certificate authority (CA), see your CA’s documentation. Alternatively, if your CA supports the ACME protocol, you can use the
mod_mdmodule to automate retrieving and provisioning TLS certificates.-
The TLS certificate is stored in the
/etc/pki/tls/certs/example.com.crtfile. If you use a different path, adapt the corresponding steps of the procedure. -
The CA certificate is stored in the
/etc/pki/tls/certs/ca.crtfile. If you use a different path, adapt the corresponding steps of the procedure. - Clients and the web server resolve the host name of the server to the IP address of the web server.
Procedure
Install the
mod_sslpackage:yum install mod_ssl
# yum install mod_sslCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/httpd/conf.d/ssl.conffile and add the following settings to the<VirtualHost _default_:443>directive:Set the server name:
ServerName example.com
ServerName example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow
The server name must match the entry set in the Common Name field of the certificate.
Optional: If the certificate contains additional host names in the
Subject Alt Names(SAN) field, you can configuremod_sslto provide TLS encryption also for these host names. To configure this, add theServerAliasesparameter with corresponding names:ServerAlias www.example.com server.example.com
ServerAlias www.example.com server.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the paths to the private key, the server certificate, and the CA certificate:
SSLCertificateKeyFile "/etc/pki/tls/private/example.com.key" SSLCertificateFile "/etc/pki/tls/certs/example.com.crt" SSLCACertificateFile "/etc/pki/tls/certs/ca.crt"
SSLCertificateKeyFile "/etc/pki/tls/private/example.com.key" SSLCertificateFile "/etc/pki/tls/certs/example.com.crt" SSLCACertificateFile "/etc/pki/tls/certs/ca.crt"Copy to Clipboard Copied! Toggle word wrap Toggle overflow For security reasons, configure that only the
rootuser can access the private key file:chown root:root /etc/pki/tls/private/example.com.key chmod 600 /etc/pki/tls/private/example.com.key
# chown root:root /etc/pki/tls/private/example.com.key # chmod 600 /etc/pki/tls/private/example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow WarningIf the private key was accessed by unauthorized users, revoke the certificate, create a new private key, and request a new certificate. Otherwise, the TLS connection is no longer secure.
If you use
firewalld, open port443in the local firewall:firewall-cmd --permanent --add-port=443/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=443/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
NoteIf you protected the private key file with a password, you must enter this password each time when the
httpdservice starts.
Verification
-
Use a browser and connect to
https://example.com.
1.9.2. Setting the supported TLS protocol versions on an Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
By default, the Apache HTTP Server on RHEL uses the system-wide crypto policy that defines safe default values, which are also compatible with recent browsers. For example, the DEFAULT policy defines that only the TLSv1.2 and TLSv1.3 protocol versions are enabled in apache.
You can manually configure which TLS protocol versions your Apache HTTP Server supports. Follow the procedure if your environment requires to enable only specific TLS protocol versions, for example:
-
If your environment requires that clients can also use the weak
TLS1(TLSv1.0) orTLS1.1protocol. -
If you want to configure that Apache only supports the
TLSv1.2orTLSv1.3protocol.
Prerequisites
- TLS encryption is enabled on the server as described in Adding TLS encryption to an Apache HTTP server.
Procedure
Edit the
/etc/httpd/conf/httpd.conffile, and add the following setting to the<VirtualHost>directive for which you want to set the TLS protocol version. For example, to enable only theTLSv1.3protocol:SSLProtocol -All TLSv1.3
SSLProtocol -All TLSv1.3Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use the following command to verify that the server supports
TLSv1.3:openssl s_client -connect example.com:443 -tls1_3
# openssl s_client -connect example.com:443 -tls1_3Copy to Clipboard Copied! Toggle word wrap Toggle overflow Use the following command to verify that the server does not support
TLSv1.2:openssl s_client -connect example.com:443 -tls1_2
# openssl s_client -connect example.com:443 -tls1_2Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the server does not support the protocol, the command returns an error:
140111600609088:error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version:ssl/record/rec_layer_s3.c:1543:SSL alert number 70
140111600609088:error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version:ssl/record/rec_layer_s3.c:1543:SSL alert number 70Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Optional: Repeat the command for other TLS protocol versions.
1.9.3. Setting the supported ciphers on an Apache HTTP Server Link kopierenLink in die Zwischenablage kopiert!
By default, the Apache HTTP Server uses the system-wide crypto policy that defines safe default values, which are also compatible with recent browsers. For the list of ciphers the system-wide crypto allows, see the /etc/crypto-policies/back-ends/openssl.config file.
You can manually configure which ciphers your Apache HTTP Server supports. Follow the procedure if your environment requires specific ciphers.
Prerequisites
- TLS encryption is enabled on the server as described in Adding TLS encryption to an Apache HTTP server.
Procedure
Edit the
/etc/httpd/conf/httpd.conffile, and add theSSLCipherSuiteparameter to the<VirtualHost>directive for which you want to set the TLS ciphers:SSLCipherSuite "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:!SHA1:!SHA256"
SSLCipherSuite "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:!SHA1:!SHA256"Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example enables only the
EECDH+AESGCM,EDH+AESGCM,AES256+EECDH, andAES256+EDHciphers and disables all ciphers which use theSHA1andSHA256message authentication code (MAC).Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To display the list of ciphers the Apache HTTP Server supports:
Install the
nmappackage:yum install nmap
# yum install nmapCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
nmaputility to display the supported ciphers:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.10. Configuring TLS client certificate authentication Link kopierenLink in die Zwischenablage kopiert!
Client certificate authentication enables administrators to allow only users who authenticate using a certificate to access resources on the web server. You can configure client certificate authentication for the /var/www/html/Example/ directory.
If the Apache HTTP Server uses the TLS 1.3 protocol, certain clients require additional configuration. For example, in Firefox, set the security.tls.enable_post_handshake_auth parameter in the about:config menu to true.
Prerequisites
- TLS encryption is enabled on the server as described in Adding TLS encryption to an Apache HTTP server.
Procedure
Edit the
/etc/httpd/conf/httpd.conffile and add the following settings to the<VirtualHost>directive for which you want to configure client authentication:<Directory "/var/www/html/Example/"> SSLVerifyClient require </Directory>
<Directory "/var/www/html/Example/"> SSLVerifyClient require </Directory>Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
SSLVerifyClient requiresetting defines that the server must successfully validate the client certificate before the client can access the content in the/var/www/html/Example/directory.Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use the
curlutility to access thehttps://example.com/Example/URL without client authentication:curl https://example.com/Example/
$ curl https://example.com/Example/ curl: (56) OpenSSL SSL_read: error:1409445C:SSL routines:ssl3_read_bytes:tlsv13 alert certificate required, errno 0Copy to Clipboard Copied! Toggle word wrap Toggle overflow The error indicates that the web server requires a client certificate authentication.
Pass the client private key and certificate, as well as the CA certificate to
curlto access the same URL with client authentication:curl --cacert ca.crt --key client.key --cert client.crt https://example.com/Example/
$ curl --cacert ca.crt --key client.key --cert client.crt https://example.com/Example/Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the request succeeds,
curldisplays theindex.htmlfile stored in the/var/www/html/Example/directory.
1.11. Securing web applications on a web server using ModSecurity Link kopierenLink in die Zwischenablage kopiert!
ModSecurity is an open source web application firewall (WAF) supported by various web servers such as Apache, Nginx, and IIS, which reduces security risks in web applications. ModSecurity provides customizable rule sets for configuring your server.
The mod_security-crs package contains the core rule set (CRS) with rules against cross-website scripting, bad user agents, SQL injection, Trojans, session hijacking, and other exploits.
1.11.1. Deploying the ModSecurity web-based application firewall for Apache Link kopierenLink in die Zwischenablage kopiert!
To reduce risks related to running web-based applications on your web server by deploying ModSecurity, install the mod_security and mod_security_crs packages for the Apache HTTP server. The mod_security_crs package provides the core rule set (CRS) for the ModSecurity web-based application firewall (WAF) module.
Procedure
Install the
mod_security,mod_security_crs, andhttpdpackages:yum install -y mod_security mod_security_crs httpd
# yum install -y mod_security mod_security_crs httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the
httpdserver:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Verify that the ModSecurity web-based application firewall is enabled on your Apache HTTP server:
httpd -M | grep security
# httpd -M | grep security security2_module (shared)Copy to Clipboard Copied! Toggle word wrap Toggle overflow Check that the
/etc/httpd/modsecurity.d/activated_rules/directory contains rules provided bymod_security_crs:ls /etc/httpd/modsecurity.d/activated_rules/
# ls /etc/httpd/modsecurity.d/activated_rules/ ... REQUEST-921-PROTOCOL-ATTACK.conf REQUEST-930-APPLICATION-ATTACK-LFI.conf ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.11.2. Adding a custom rule to ModSecurity Link kopierenLink in die Zwischenablage kopiert!
If the rules contained in the ModSecurity core rule set (CRS) do not fit your scenario and if you want to prevent additional possible attacks, you can add your custom rules to the rule set used by the ModSecurity web-based application firewall. The following example demonstrates the addition of a simple rule. For creating more complex rules, see the reference manual on the ModSecurity Wiki website.
Prerequisites
- ModSecurity for Apache is installed and enabled.
Procedure
Open the
/etc/httpd/conf.d/mod_security.conffile in a text editor of your choice, for example:vi /etc/httpd/conf.d/mod_security.conf
# vi /etc/httpd/conf.d/mod_security.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the following example rule after the line starting with
SecRuleEngine On:SecRule ARGS:data "@contains evil" "deny,status:403,msg:'param data contains evil data',id:1"
SecRule ARGS:data "@contains evil" "deny,status:403,msg:'param data contains evil data',id:1"Copy to Clipboard Copied! Toggle word wrap Toggle overflow The previous rule forbids the use of resources to the user if the
dataparameter contains theevilstring.- Save the changes, and quit the editor.
Restart the
httpdserver:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Create a
test.htmlpage:echo "mod_security test" > /var/www/html/test.html
# echo "mod_security test" > /var/www/html/test.htmlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
httpdserver:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow Request
test.htmlwithout malicious data in theGETvariable of the HTTP request:curl http://localhost/test.html?data=good
$ curl http://localhost/test.html?data=good mod_security testCopy to Clipboard Copied! Toggle word wrap Toggle overflow Request
test.htmlwith malicious data in theGETvariable of the HTTP request:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Check the
/var/log/httpd/error_logfile, and locate the log entry about denying access with theparam data containing an evil datamessage:[Wed May 25 08:01:31.036297 2022] [:error] [pid 5839:tid 139874434791168] [client ::1:45658] [client ::1] ModSecurity: Access denied with code 403 (phase 2). String match "evil" at ARGS:data. [file "/etc/httpd/conf.d/mod_security.conf"] [line "4"] [id "1"] [msg "param data contains evil data"] [hostname "localhost"] [uri "/test.html"] [unique_id "Yo4amwIdsBG3yZqSzh2GuwAAAIY"]
[Wed May 25 08:01:31.036297 2022] [:error] [pid 5839:tid 139874434791168] [client ::1:45658] [client ::1] ModSecurity: Access denied with code 403 (phase 2). String match "evil" at ARGS:data. [file "/etc/httpd/conf.d/mod_security.conf"] [line "4"] [id "1"] [msg "param data contains evil data"] [hostname "localhost"] [uri "/test.html"] [unique_id "Yo4amwIdsBG3yZqSzh2GuwAAAIY"]Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.12. Installing the Apache HTTP Server manual Link kopierenLink in die Zwischenablage kopiert!
You can install the Apache HTTP Server manual. This manual provides a detailed documentation of, for example:
- Configuration parameters and directives
- Performance tuning
- Authentication settings
- Modules
- Content caching
- Security tips
- Configuring TLS encryption
After installing the manual, you can display it using a web browser.
Prerequisites
- The Apache HTTP Server is installed and running.
Procedure
Install the
httpd-manualpackage:yum install httpd-manual
# yum install httpd-manualCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: By default, all clients connecting to the Apache HTTP Server can display the manual. To restrict access to a specific IP range, such as the
192.0.2.0/24subnet, edit the/etc/httpd/conf.d/manual.conffile and add theRequire ip 192.0.2.0/24setting to the<Directory "/usr/share/httpd/manual">directive:<Directory "/usr/share/httpd/manual"> ... Require ip 192.0.2.0/24 ... </Directory><Directory "/usr/share/httpd/manual"> ... Require ip 192.0.2.0/24 ... </Directory>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
To display the Apache HTTP Server manual, connect with a web browser to
http://host_name_or_IP_address/manual/
1.13. Working with Apache modules Link kopierenLink in die Zwischenablage kopiert!
The httpd service is a modular application, and you can extend it with a number of Dynamic Shared Objects (DSOs). Dynamic Shared Objects are modules that you can dynamically load or unload at runtime as necessary. You can find these modules in the /usr/lib64/httpd/modules/ directory.
1.13.1. Loading a DSO module Link kopierenLink in die Zwischenablage kopiert!
As an administrator, you can choose the functionality to include in the server by configuring which modules the server should load. To load a particular DSO module, use the LoadModule directive. Note that modules provided by a separate package often have their own configuration file in the /etc/httpd/conf.modules.d/ directory.
Prerequisites
-
You have installed the
httpdpackage.
Procedure
Search for the module name in the configuration files in the
/etc/httpd/conf.modules.d/directory:grep mod_ssl.so /etc/httpd/conf.modules.d/*
# grep mod_ssl.so /etc/httpd/conf.modules.d/*Copy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the configuration file in which the module name was found, and uncomment the
LoadModuledirective of the module:LoadModule ssl_module modules/mod_ssl.so
LoadModule ssl_module modules/mod_ssl.soCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the module was not found, for example, because a RHEL package does not provide the module, create a configuration file, such as
/etc/httpd/conf.modules.d/30-example.confwith the following directive:LoadModule ssl_module modules/<custom_module>.so
LoadModule ssl_module modules/<custom_module>.soCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
httpdservice:systemctl restart httpd
# systemctl restart httpdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
1.13.2. Compiling a custom Apache module Link kopierenLink in die Zwischenablage kopiert!
You can create your own module and build it with the help of the httpd-devel package, which contains the include files, the header files, and the APache eXtenSion (apxs) utility required to compile a module.
Prerequisites
-
You have the
httpd-develpackage installed.
Procedure
Build a custom module with the following command:
apxs -i -a -c module_name.c
# apxs -i -a -c module_name.cCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Load the module the same way as described in Loading a DSO module.
1.14. Exporting a private key and certificates from an NSS database to use them in an Apache web server configuration Link kopierenLink in die Zwischenablage kopiert!
RHEL 8 no longer provides the mod_nss module for the Apache web server, and Red Hat recommends using the mod_ssl module. If you store your private key and certificates in a Network Security Services (NSS) database, for example, because you migrated the web server from RHEL 7 to RHEL 8, follow this procedure to extract the key and certificates in Privacy Enhanced Mail (PEM) format. You can then use the files in the mod_ssl configuration as described in Configuring TLS encryption on an Apache HTTP server.
This procedure assumes that the NSS database is stored in /etc/httpd/alias/ and that you store the exported private key and certificates in the /etc/pki/tls/ directory.
Prerequisites
- The private key, the certificate, and the certificate authority (CA) certificate are stored in an NSS database.
Procedure
List the certificates in the NSS database:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow You need the nicknames of the certificates in the next steps.
To extract the private key, you must temporarily export the key to a PKCS #12 file:
Use the nickname of the certificate associated with the private key, to export the key to a PKCS #12 file:
pk12util -o /etc/pki/tls/private/export.p12 -d /etc/httpd/alias/ -n "Example Server Certificate"
# pk12util -o /etc/pki/tls/private/export.p12 -d /etc/httpd/alias/ -n "Example Server Certificate" Enter password for PKCS12 file: password Re-enter password: password pk12util: PKCS12 EXPORT SUCCESSFULCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that you must set a password on the PKCS #12 file. You need this password in the next step.
Export the private key from the PKCS #12 file:
openssl pkcs12 -in /etc/pki/tls/private/export.p12 -out /etc/pki/tls/private/server.key -nocerts -nodes
# openssl pkcs12 -in /etc/pki/tls/private/export.p12 -out /etc/pki/tls/private/server.key -nocerts -nodes Enter Import Password: password MAC verified OKCopy to Clipboard Copied! Toggle word wrap Toggle overflow Delete the temporary PKCS #12 file:
rm /etc/pki/tls/private/export.p12
# rm /etc/pki/tls/private/export.p12Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Set the permissions on
/etc/pki/tls/private/server.keyto ensure that only therootuser can access this file:chown root:root /etc/pki/tls/private/server.key chmod 0600 /etc/pki/tls/private/server.key
# chown root:root /etc/pki/tls/private/server.key # chmod 0600 /etc/pki/tls/private/server.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the nickname of the server certificate in the NSS database to export the CA certificate:
certutil -d /etc/httpd/alias/ -L -n "Example Server Certificate" -a -o /etc/pki/tls/certs/server.crt
# certutil -d /etc/httpd/alias/ -L -n "Example Server Certificate" -a -o /etc/pki/tls/certs/server.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the permissions on
/etc/pki/tls/certs/server.crtto ensure that only therootuser can access this file:chown root:root /etc/pki/tls/certs/server.crt chmod 0600 /etc/pki/tls/certs/server.crt
# chown root:root /etc/pki/tls/certs/server.crt # chmod 0600 /etc/pki/tls/certs/server.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the nickname of the CA certificate in the NSS database to export the CA certificate:
certutil -d /etc/httpd/alias/ -L -n "Example CA" -a -o /etc/pki/tls/certs/ca.crt
# certutil -d /etc/httpd/alias/ -L -n "Example CA" -a -o /etc/pki/tls/certs/ca.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Follow Configuring TLS encryption on an Apache HTTP server to configure the Apache web server, and:
-
Set the
SSLCertificateKeyFileparameter to/etc/pki/tls/private/server.key. -
Set the
SSLCertificateFileparameter to/etc/pki/tls/certs/server.crt. -
Set the
SSLCACertificateFileparameter to/etc/pki/tls/certs/ca.crt.
-
Set the
Chapter 2. Setting up and configuring NGINX Link kopierenLink in die Zwischenablage kopiert!
NGINX is a high performance and modular server that you can use, for example, as a:
- Web server
- Reverse proxy
- Load balancer
2.1. Installing and preparing NGINX Link kopierenLink in die Zwischenablage kopiert!
Red Hat uses Application Streams to provide different versions of NGINX. You can do the following:
- Select a stream and install NGINX
- Open the required ports in the firewall
-
Enable and start the
nginxservice
Using the default configuration, NGINX runs as a web server on port 80 and provides content from the /usr/share/nginx/html/ directory.
Prerequisites
- RHEL 8 is installed.
- The host is subscribed to the Red Hat Customer Portal.
-
The
firewalldservice is enabled and started
Procedure
Display the available NGINX module streams:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you want to install a different stream than the default, select the stream:
yum module enable nginx:stream_version
# yum module enable nginx:stream_versionCopy to Clipboard Copied! Toggle word wrap Toggle overflow Install the
nginxpackage:yum install nginx
# yum install nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow Open the ports on which NGINX should provide its service in the firewall. For example, to open the default ports for HTTP (port 80) and HTTPS (port 443) in
firewalld, enter:firewall-cmd --permanent --add-port={80/tcp,443/tcp} firewall-cmd --reload# firewall-cmd --permanent --add-port={80/tcp,443/tcp} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
nginxservice to start automatically when the system boots:systemctl enable nginx
# systemctl enable nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Start the
nginxservice:systemctl start nginx
# systemctl start nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you do not want to use the default configuration, skip this step, and configure NGINX accordingly before you start the service.
The PHP module requires a specific NGINX version. Using an incompatible version can cause conflicts when upgrading to a newer NGNIX stream. When using PHP 7.2 stream and NGNIX 1.24 stream, you can resolve this issue by enabling a newer PHP stream 7.4 before installing NGINX.
Verification
Use the
yumutility to verify that thenginxpackage is installed:yum list installed nginx
# yum list installed nginx Installed Packages nginx.x86_64 1:1.14.1-9.module+el8.0.0+4108+af250afe @rhel-8-for-x86_64-appstream-rpmsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Ensure that the ports on which NGINX should provide its service are opened in the firewalld:
firewall-cmd --list-ports
# firewall-cmd --list-ports 80/tcp 443/tcpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that the
nginxservice is enabled:systemctl is-enabled nginx
# systemctl is-enabled nginx enabledCopy to Clipboard Copied! Toggle word wrap Toggle overflow
2.2. Configuring NGINX as a web server that provides different content for different domains Link kopierenLink in die Zwischenablage kopiert!
By default, NGINX acts as a web server that provides the same content to clients for all domain names associated with the IP addresses of the server. This procedure explains how to configure NGINX:
-
To serve requests to the
example.comdomain with content from the/var/www/example.com/directory -
To serve requests to the
example.netdomain with content from the/var/www/example.net/directory -
To serve all other requests, for example, to the IP address of the server or to other domains associated with the IP address of the server, with content from the
/usr/share/nginx/html/directory
Prerequisites
- NGINX is installed
Clients and the web server resolve the
example.comandexample.netdomain to the IP address of the web server.Note that you must manually add these entries to your DNS server.
Procedure
Edit the
/etc/nginx/nginx.conffile:By default, the
/etc/nginx/nginx.conffile already contains a catch-all configuration. If you have deleted this part from the configuration, re-add the followingserverblock to thehttpblock in the/etc/nginx/nginx.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings configure the following:
-
The
listendirective define which IP address and ports the service listens. In this case, NGINX listens on port80on both all IPv4 and IPv6 addresses. Thedefault_serverparameter indicates that NGINX uses thisserverblock as the default for requests matching the IP addresses and ports. -
The
server_nameparameter defines the host names for which thisserverblock is responsible. Settingserver_nameto_configures NGINX to accept any host name for thisserverblock. -
The
rootdirective sets the path to the web content for thisserverblock.
-
The
Append a similar
serverblock for theexample.comdomain to thehttpblock:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
The
access_logdirective defines a separate access log file for this domain. -
The
error_logdirective defines a separate error log file for this domain.
-
The
Append a similar
serverblock for theexample.netdomain to thehttpblock:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Create the root directories for both domains:
mkdir -p /var/www/example.com/ mkdir -p /var/www/example.net/
# mkdir -p /var/www/example.com/ # mkdir -p /var/www/example.net/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set the
httpd_sys_content_tcontext on both root directories:semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?" restorecon -Rv /var/www/example.com/ semanage fcontext -a -t httpd_sys_content_t "/var/www/example.net(/.\*)?" restorecon -Rv /var/www/example.net/
# semanage fcontext -a -t httpd_sys_content_t "/var/www/example.com(/.*)?" # restorecon -Rv /var/www/example.com/ # semanage fcontext -a -t httpd_sys_content_t "/var/www/example.net(/.\*)?" # restorecon -Rv /var/www/example.net/Copy to Clipboard Copied! Toggle word wrap Toggle overflow These commands set the
httpd_sys_content_tcontext on the/var/www/example.com/and/var/www/example.net/directories.Note that you must install the
policycoreutils-python-utilspackage to run therestoreconcommands.Create the log directories for both domains:
mkdir /var/log/nginx/example.com/ mkdir /var/log/nginx/example.net/
# mkdir /var/log/nginx/example.com/ # mkdir /var/log/nginx/example.net/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
nginxservice:systemctl restart nginx
# systemctl restart nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Create a different example file in each virtual host’s document root:
echo "Content for example.com" > /var/www/example.com/index.html echo "Content for example.net" > /var/www/example.net/index.html echo "Catch All content" > /usr/share/nginx/html/index.html
# echo "Content for example.com" > /var/www/example.com/index.html # echo "Content for example.net" > /var/www/example.net/index.html # echo "Catch All content" > /usr/share/nginx/html/index.htmlCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Use a browser and connect to
http://example.com. The web server shows the example content from the/var/www/example.com/index.htmlfile. -
Use a browser and connect to
http://example.net. The web server shows the example content from the/var/www/example.net/index.htmlfile. -
Use a browser and connect to
http://IP_address_of_the_server. The web server shows the example content from the/usr/share/nginx/html/index.htmlfile.
2.3. Adding TLS encryption to an NGINX web server Link kopierenLink in die Zwischenablage kopiert!
You can enable TLS encryption on an NGINX web server for the example.com domain.
Prerequisites
- NGINX is installed.
The private key is stored in the
/etc/pki/tls/private/example.com.keyfile.For details about creating a private key and certificate signing request (CSR), as well as how to request a certificate from a certificate authority (CA), see your CA’s documentation.
-
The TLS certificate is stored in the
/etc/pki/tls/certs/example.com.crtfile. If you use a different path, adapt the corresponding steps of the procedure. - The CA certificate has been appended to the TLS certificate file of the server.
- Clients and the web server resolve the host name of the server to the IP address of the web server.
-
Port
443is open in the local firewall.
Procedure
Edit the
/etc/nginx/nginx.conffile, and add the followingserverblock to thehttpblock in the configuration:Copy to Clipboard Copied! Toggle word wrap Toggle overflow For security reasons, configure that only the
rootuser can access the private key file:chown root:root /etc/pki/tls/private/example.com.key chmod 600 /etc/pki/tls/private/example.com.key
# chown root:root /etc/pki/tls/private/example.com.key # chmod 600 /etc/pki/tls/private/example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow WarningIf the private key was accessed by unauthorized users, revoke the certificate, create a new private key, and request a new certificate. Otherwise, the TLS connection is no longer secure.
Restart the
nginxservice:systemctl restart nginx
# systemctl restart nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
Use a browser and connect to
https://example.com
2.4. Configuring NGINX as a reverse proxy for the HTTP traffic Link kopierenLink in die Zwischenablage kopiert!
You can configure the NGINX web server to act as a reverse proxy for HTTP traffic. For example, you can use this functionality to forward requests to a specific subdirectory on a remote server. From the client perspective, the client loads the content from the host it accesses. However, NGINX loads the actual content from the remote server and forwards it to the client.
This procedure explains how to forward traffic to the /example directory on the web server to the URL https://example.com.
Prerequisites
- NGINX is installed as described in Installing and preparing NGINX.
- Optional: TLS encryption is enabled on the reverse proxy.
Procedure
Edit the
/etc/nginx/nginx.conffile and add the following settings to theserverblock that should provide the reverse proxy:location /example { proxy_pass https://example.com; }location /example { proxy_pass https://example.com; }Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
locationblock defines that NGINX passes all requests in the/exampledirectory tohttps://example.com.Set the
httpd_can_network_connectSELinux boolean parameter to1to configure that SELinux allows NGINX to forward traffic:setsebool -P httpd_can_network_connect 1
# setsebool -P httpd_can_network_connect 1Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
nginxservice:systemctl restart nginx
# systemctl restart nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
Use a browser and connect to
http://host_name/exampleand the content ofhttps://example.comis shown.
2.5. Configuring NGINX as an HTTP load balancer Link kopierenLink in die Zwischenablage kopiert!
You can use the NGINX reverse proxy feature to load-balance traffic. This procedure describes how to configure NGINX as an HTTP load balancer that sends requests to different servers, based on which of them has the least number of active connections. If both servers are not available, the procedure also defines a third host for fallback reasons.
Prerequisites
- NGINX is installed as described in Installing and preparing NGINX.
Procedure
Edit the
/etc/nginx/nginx.conffile and add the following settings:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
least_conndirective in the host group namedbackenddefines that NGINX sends requests toserver1.example.comorserver2.example.com, depending on which host has the least number of active connections. NGINX usesserver3.example.comonly as a backup in case that the other two hosts are not available.With the
proxy_passdirective set tohttp://backend, NGINX acts as a reverse proxy and uses thebackendhost group to distribute requests based on the settings of this group.Instead of the
least_connload balancing method, you can specify:- No method to use round robin and distribute requests evenly across servers.
-
ip_hashto send requests from one client address to the same server based on a hash calculated from the first three octets of the IPv4 address or the whole IPv6 address of the client. -
hashto determine the server based on a user-defined key, which can be a string, a variable, or a combination of both. Theconsistentparameter configures that NGINX distributes requests across all servers based on the user-defined hashed key value. -
randomto send requests to a randomly selected server.
Restart the
nginxservice:systemctl restart nginx
# systemctl restart nginxCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Chapter 3. Using Samba as a server Link kopierenLink in die Zwischenablage kopiert!
Samba implements the Server Message Block (SMB) protocol in Red Hat Enterprise Linux. The SMB protocol is used to access resources on a server, such as file shares and shared printers. Additionally, Samba implements the Distributed Computing Environment Remote Procedure Call (DCE RPC) protocol used by Microsoft Windows.
You can run Samba as:
- An Active Directory (AD) or NT4 domain member
- A standalone server
An NT4 Primary Domain Controller (PDC) or Backup Domain Controller (BDC)
NoteRed Hat supports the PDC and BDC modes only in existing installations with Windows versions which support NT4 domains. Red Hat recommends not setting up a new Samba NT4 domain, because Microsoft operating systems later than Windows 7 and Windows Server 2008 R2 do not support NT4 domains.
Red Hat does not support running Samba as an AD domain controller (DC).
Independently of the installation mode, you can optionally share directories and printers. This enables Samba to act as a file and print server.
3.1. Understanding the different Samba services and modes Link kopierenLink in die Zwischenablage kopiert!
The samba package provides multiple services. Depending on your environment and the scenario you want to configure, you require one or more of these services and configure Samba in different modes.
3.1.1. The Samba services Link kopierenLink in die Zwischenablage kopiert!
Samba provides the following services:
smbdThis service provides file sharing and printing services using the SMB protocol. Additionally, the service is responsible for resource locking and for authenticating connecting users. For authenticating domain members,
smbdrequireswinbindd. Thesmbsystemd service starts and stops thesmbddaemon.To use the
smbdservice, install thesambapackage.nmbdThis service provides host name and IP resolution using the NetBIOS over IPv4 protocol. Additionally to the name resolution, the
nmbdservice enables browsing the SMB network to locate domains, work groups, hosts, file shares, and printers. For this, the service either reports this information directly to the broadcasting client or forwards it to a local or master browser. Thenmbsystemd service starts and stops thenmbddaemon.Note that modern SMB networks use DNS to resolve clients and IP addresses. For Kerberos a working DNS setup is required.
To use the
nmbdservice, install thesambapackage.winbinddThis service provides an interface for the Name Service Switch (NSS) to use AD or NT4 domain users and groups on the local system. This enables, for example, domain users to authenticate to services hosted on a Samba server or to other local services. The
winbindsystemd service starts and stops thewinbindddaemon.If you set up Samba as a domain member,
winbinddmust be started before thesmbdservice. Otherwise, domain users and groups are not available to the local system..To use the
winbinddservice, install thesamba-winbindpackage.ImportantRed Hat only supports running Samba as a server with the
winbinddservice to provide domain users and groups to the local system. Due to certain limitations, such as missing Windows access control list (ACL) support and NT LAN Manager (NTLM) fallback, SSSD is not supported.
3.1.2. The Samba security services Link kopierenLink in die Zwischenablage kopiert!
The security parameter in the [global] section in the /etc/samba/smb.conf file manages how Samba authenticates users that are connecting to the service. Depending on the mode you install Samba in, the parameter must be set to different values:
- On an AD domain member, set
security = ads In this mode, Samba uses Kerberos to authenticate AD users.
For details about setting up Samba as a domain member, see Setting up Samba as an AD domain member server.
- On a standalone server, set
security = user In this mode, Samba uses a local database to authenticate connecting users.
For details about setting up Samba as a standalone server, see Setting up Samba as a standalone server.
- On an NT4 PDC or BDC, set
security = user - In this mode, Samba authenticates users to a local or LDAP database.
- On an NT4 domain member, set
security = domain In this mode, Samba authenticates connecting users to an NT4 PDC or BDC. You cannot use this mode on AD domain members.
For details about setting up Samba as a domain member, see Setting up Samba as an AD domain member server.
3.1.3. Scenarios when Samba services and Samba client utilities load and reload their configuration Link kopierenLink in die Zwischenablage kopiert!
The following describes when Samba services and utilities load and reload their configuration:
Samba services reload their configuration:
- Automatically every 3 minutes
-
On manual request, for example, when you run the
smbcontrol all reload-configcommand.
- Samba client utilities read their configuration only when you start them.
Note that certain parameters, such as security require a restart of the smb service to take effect and a reload is not sufficient.
3.1.4. Editing the Samba configuration in a safe way Link kopierenLink in die Zwischenablage kopiert!
Samba services automatically reload their configuration every 3 minutes. To prevent that the services reload the changes before you have verified the configuration using the testparm utility, you can edit the Samba configuration in a safe way.
Prerequisites
- Samba is installed.
Procedure
Create a copy of the
/etc/samba/smb.conffile:cp /etc/samba/smb.conf /etc/samba/samba.conf.copy
# cp /etc/samba/smb.conf /etc/samba/samba.conf.copyCopy to Clipboard Copied! Toggle word wrap Toggle overflow - Edit the copied file and make the required changes.
Verify the configuration in the
/etc/samba/samba.conf.copyfile:testparm -s /etc/samba/samba.conf.copy
# testparm -s /etc/samba/samba.conf.copyCopy to Clipboard Copied! Toggle word wrap Toggle overflow If
testparmreports errors, fix them and run the command again.Override the
/etc/samba/smb.conffile with the new configuration:mv /etc/samba/samba.conf.copy /etc/samba/smb.conf
# mv /etc/samba/samba.conf.copy /etc/samba/smb.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow Wait until the Samba services automatically reload their configuration or manually reload the configuration:
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.2. Verifying the smb.conf file by using the testparm utility Link kopierenLink in die Zwischenablage kopiert!
The testparm utility verifies that the Samba configuration in the /etc/samba/smb.conf file is correct. The utility detects invalid parameters and values, but also incorrect settings, such as for ID mapping. If testparm reports no problem, the Samba services will successfully load the /etc/samba/smb.conf file. Note that testparm cannot verify that the configured services will be available or work as expected.
Red Hat recommends that you verify the /etc/samba/smb.conf file by using testparm after each modification of this file.
Prerequisites
- You installed Samba.
-
The
/etc/samba/smb.conffile exits.
Procedure
Run the
testparmutility as therootuser:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The previous example output reports a non-existent parameter and an incorrect ID mapping configuration.
-
If
testparmreports incorrect parameters, values, or other errors in the configuration, fix the problem and run the utility again.
3.3. Setting up Samba as a standalone server Link kopierenLink in die Zwischenablage kopiert!
You can set up Samba as a server that is not a member of a domain. In this installation mode, Samba authenticates users to a local database instead of to a central DC. Additionally, you can enable guest access to allow users to connect to one or multiple services without authentication.
3.3.1. Setting up the server configuration for the standalone server Link kopierenLink in die Zwischenablage kopiert!
You can set up the server configuration for a Samba standalone server.
Procedure
Install the
sambapackage:yum install samba
# yum install sambaCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/samba/smb.conffile and set the following parameters:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This configuration defines a standalone server named
Serverwithin theExample-WGwork group. Additionally, this configuration enables logging on a minimal level (1) and log files will be stored in the/var/log/samba/directory. Samba will expand the%mmacro in thelog fileparameter to the NetBIOS name of connecting clients. This enables individual log files for each client.Optional: Configure file or printer sharing. See:
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you set up shares that require authentication, create the user accounts.
For details, see Creating and enabling local user accounts.
Open the required ports and reload the firewall configuration by using the
firewall-cmdutility:firewall-cmd --permanent --add-service=samba firewall-cmd --reload
# firewall-cmd --permanent --add-service=samba # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
smbservice:systemctl enable --now smb
# systemctl enable --now smbCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.3.2. Creating and enabling local user accounts Link kopierenLink in die Zwischenablage kopiert!
To enable users to authenticate when they connect to a share, you must create the accounts on the Samba host both in the operating system and in the Samba database. Samba requires the operating system account to validate the Access Control Lists (ACL) on file system objects and the Samba account to authenticate connecting users.
If you use the passdb backend = tdbsam default setting, Samba stores user accounts in the /var/lib/samba/private/passdb.tdb database.
You can create a local Samba user named example.
Prerequisites
- Samba is installed and configured as a standalone server.
Procedure
Create the operating system account:
useradd -M -s /sbin/nologin example
# useradd -M -s /sbin/nologin exampleCopy to Clipboard Copied! Toggle word wrap Toggle overflow This command adds the
exampleaccount without creating a home directory. If the account is only used to authenticate to Samba, assign the/sbin/nologincommand as shell to prevent the account from logging in locally.Set a password to the operating system account to enable it:
passwd example
# passwd example Enter new UNIX password: password Retype new UNIX password: password passwd: password updated successfullyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Samba does not use the password set on the operating system account to authenticate. However, you need to set a password to enable the account. If an account is disabled, Samba denies access if this user connects.
Add the user to the Samba database and set a password to the account:
smbpasswd -a example
# smbpasswd -a example New SMB password: password Retype new SMB password: password Added user example.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Use this password to authenticate when using this account to connect to a Samba share.
Enable the Samba account:
smbpasswd -e example
# smbpasswd -e example Enabled user example.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.4. Understanding and configuring Samba ID mapping Link kopierenLink in die Zwischenablage kopiert!
Windows domains distinguish users and groups by unique Security Identifiers (SID). However, Linux requires unique UIDs and GIDs for each user and group. If you run Samba as a domain member, the winbindd service is responsible for providing information about domain users and groups to the operating system.
To enable the winbindd service to provide unique IDs for users and groups to Linux, you must configure ID mapping in the /etc/samba/smb.conf file for:
- The local database (default domain)
- The AD or NT4 domain the Samba server is a member of
- Each trusted domain from which users must be able to access resources on this Samba server
Samba provides different ID mapping back ends for specific configurations. The most frequently used back ends are:
| Back end | Use case |
|---|---|
|
|
The |
|
| AD domains only |
|
| AD and NT4 domains |
|
|
AD, NT4, and the |
3.4.1. Planning Samba ID ranges Link kopierenLink in die Zwischenablage kopiert!
Regardless of whether you store the Linux UIDs and GIDs in AD or if you configure Samba to generate them, each domain configuration requires a unique ID range that must not overlap with any of the other domains.
If you set overlapping ID ranges, Samba fails to work correctly.
Example 3.1. Unique ID Ranges
The following shows non-overlapping ID mapping ranges for the default (*), AD-DOM, and the TRUST-DOM domains.
You can only assign one range per domain. Therefore, leave enough space between the domains ranges. This enables you to extend the range later if your domain grows.
If you later assign a different range to a domain, the ownership of files and directories previously created by these users and groups will be lost.
3.4.2. The * default domain Link kopierenLink in die Zwischenablage kopiert!
In a domain environment, you add one ID mapping configuration for each of the following:
- The domain the Samba server is a member of
- Each trusted domain that should be able to access the Samba server
However, for all other objects, Samba assigns IDs from the default domain. This includes:
- Local Samba users and groups
-
Samba built-in accounts and groups, such as
BUILTIN\Administrators
You must configure the default domain as described to enable Samba to operate correctly.
The default domain back end must be writable to permanently store the assigned IDs.
For the default domain, you can use one of the following back ends:
tdbWhen you configure the default domain to use the
tdbback end, set an ID range that is big enough to include objects that will be created in the future and that are not part of a defined domain ID mapping configuration.For example, set the following in the
[global]section in the/etc/samba/smb.conffile:idmap config * : backend = tdb idmap config * : range = 10000-999999
idmap config * : backend = tdb idmap config * : range = 10000-999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow For further details, see Using the TDB ID mapping back end.
autoridWhen you configure the default domain to use the
autoridback end, adding additional ID mapping configurations for domains is optional.For example, set the following in the
[global]section in the/etc/samba/smb.conffile:idmap config * : backend = autorid idmap config * : range = 10000-999999
idmap config * : backend = autorid idmap config * : range = 10000-999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow For further details, see Using the autorid ID mapping back end.
3.4.3. Using the tdb ID mapping back end Link kopierenLink in die Zwischenablage kopiert!
The winbindd service uses the writable tdb ID mapping back end by default to store Security Identifier (SID), UID, and GID mapping tables. This includes local users, groups, and built-in principals.
Use this back end only for the * default domain. For example:
idmap config * : backend = tdb idmap config * : range = 10000-999999
idmap config * : backend = tdb
idmap config * : range = 10000-999999
3.4.4. Using the ad ID mapping back end Link kopierenLink in die Zwischenablage kopiert!
You can configure a Samba AD member to use the ad ID mapping back end.
The ad ID mapping back end implements a read-only API to read account and group information from AD. This provides the following benefits:
- All user and group settings are stored centrally in AD.
- User and group IDs are consistent on all Samba servers that use this back end.
- The IDs are not stored in a local database which can corrupt, and therefore file ownerships cannot be lost.
The ad ID mapping back end does not support Active Directory domains with one-way trusts. If you configure a domain member in an Active Directory with one-way trusts, use instead one of the following ID mapping back ends: tdb, rid, or autorid.
The ad back end reads the following attributes from AD:
| AD attribute name | Object type | Mapped to |
|---|---|---|
|
| User and group | User or group name, depending on the object |
|
| User | User ID (UID) |
|
| Group | Group ID (GID) |
|
| User | Path to the shell of the user |
|
| User | Path to the home directory of the user |
|
| User | Primary group ID |
[a]
Samba only reads this attribute if you set idmap config DOMAIN:unix_nss_info = yes.
[b]
Samba only reads this attribute if you set idmap config DOMAIN:unix_primary_group = yes.
| ||
Prerequisites
-
Both users and groups must have unique IDs set in AD, and the IDs must be within the range configured in the
/etc/samba/smb.conffile. Objects whose IDs are outside of the range will not be available on the Samba server. - Users and groups must have all required attributes set in AD. If required attributes are missing, the user or group will not be available on the Samba server. The required attributes depend on your configuration. .Prerequisites
- You installed Samba.
-
The Samba configuration, except ID mapping, exists in the
/etc/samba/smb.conffile.
Procedure
Edit the
[global]section in the/etc/samba/smb.conffile:Add an ID mapping configuration for the default domain (
*) if it does not exist. For example:idmap config * : backend = tdb idmap config * : range = 10000-999999
idmap config * : backend = tdb idmap config * : range = 10000-999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
adID mapping back end for the AD domain:idmap config DOMAIN : backend = ad
idmap config DOMAIN : backend = adCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the range of IDs that is assigned to users and groups in the AD domain. For example:
idmap config DOMAIN : range = 2000000-2999999
idmap config DOMAIN : range = 2000000-2999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantThe range must not overlap with any other domain configuration on this server. Additionally, the range must be set big enough to include all IDs assigned in the future. For further details, see Planning Samba ID ranges.
Set that Samba uses the RFC 2307 schema when reading attributes from AD:
idmap config DOMAIN : schema_mode = rfc2307
idmap config DOMAIN : schema_mode = rfc2307Copy to Clipboard Copied! Toggle word wrap Toggle overflow To enable Samba to read the login shell and the path to the users home directory from the corresponding AD attribute, set:
idmap config DOMAIN : unix_nss_info = yes
idmap config DOMAIN : unix_nss_info = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Alternatively, you can set a uniform domain-wide home directory path and login shell that is applied to all users. For example:
template shell = /bin/bash template homedir = /home/%U
template shell = /bin/bash template homedir = /home/%UCopy to Clipboard Copied! Toggle word wrap Toggle overflow By default, Samba uses the
primaryGroupIDattribute of a user object as the user’s primary group on Linux. Alternatively, you can configure Samba to use the value set in thegidNumberattribute instead:idmap config DOMAIN : unix_primary_group = yes
idmap config DOMAIN : unix_primary_group = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the Samba configuration:
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.4.5. Using the rid ID mapping back end Link kopierenLink in die Zwischenablage kopiert!
You can configure a Samba domain member to use the rid ID mapping back end.
Samba can use the relative identifier (RID) of a Windows SID to generate an ID on Red Hat Enterprise Linux.
The RID is the last part of a SID. For example, if the SID of a user is S-1-5-21-5421822485-1151247151-421485315-30014, then 30014 is the corresponding RID.
The rid ID mapping back end implements a read-only API to calculate account and group information based on an algorithmic mapping scheme for AD and NT4 domains. When you configure the back end, you must set the lowest and highest RID in the idmap config DOMAIN : range parameter. Samba will not map users or groups with a lower or higher RID than set in this parameter.
As a read-only back end, rid cannot assign new IDs, such as for BUILTIN groups. Therefore, do not use this back end for the * default domain.
Benefits of using the rid back end
- All domain users and groups that have an RID within the configured range are automatically available on the domain member.
- You do not need to manually assign IDs, home directories, and login shells.
Drawbacks of using the rid back end
- All domain users get the same login shell and home directory assigned. However, you can use variables.
-
User and group IDs are only the same across Samba domain members if all use the
ridback end with the same ID range settings. - You cannot exclude individual users or groups from being available on the domain member. Only users and groups outside of the configured range are excluded.
-
Based on the formulas the
winbinddservice uses to calculate the IDs, duplicate IDs can occur in multi-domain environments if objects in different domains have the same RID.
Prerequisites
- You installed Samba.
-
The Samba configuration, except ID mapping, exists in the
/etc/samba/smb.conffile.
Procedure
Edit the
[global]section in the/etc/samba/smb.conffile:Add an ID mapping configuration for the default domain (
*) if it does not exist. For example:idmap config * : backend = tdb idmap config * : range = 10000-999999
idmap config * : backend = tdb idmap config * : range = 10000-999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
ridID mapping back end for the domain:idmap config DOMAIN : backend = rid
idmap config DOMAIN : backend = ridCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set a range that is big enough to include all RIDs that will be assigned in the future. For example:
idmap config DOMAIN : range = 2000000-2999999
idmap config DOMAIN : range = 2000000-2999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow Samba ignores users and groups whose RIDs in this domain are not within the range.
ImportantThe range must not overlap with any other domain configuration on this server. Additionally, the range must be set big enough to include all IDs assigned in the future. For further details, see Planning Samba ID ranges.
Set a shell and home directory path that will be assigned to all mapped users. For example:
template shell = /bin/bash template homedir = /home/%U
template shell = /bin/bash template homedir = /home/%UCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the Samba configuration:
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.4.6. Using the autorid ID mapping back end Link kopierenLink in die Zwischenablage kopiert!
You can configure a Samba domain member to use the autorid ID mapping back end.
The autorid back end works similar to the rid ID mapping back end, but can automatically assign IDs for different domains. This enables you to use the autorid back end in the following situations:
-
Only for the
*default domain -
For the
*default domain and additional domains, without the need to create ID mapping configurations for each of the additional domains - Only for specific domains
If you use autorid for the default domain, adding additional ID mapping configuration for domains is optional.
Parts of this section were adopted from the idmap config autorid documentation published in the Samba Wiki. License: CC BY 4.0. Authors and contributors: See the history tab on the Wiki page.
Benefits of using the autorid back end
- All domain users and groups whose calculated UID and GID is within the configured range are automatically available on the domain member.
- You do not need to manually assign IDs, home directories, and login shells.
- No duplicate IDs, even if multiple objects in a multi-domain environment have the same RID.
Drawbacks
- User and group IDs are not the same across Samba domain members.
- All domain users get the same login shell and home directory assigned. However, you can use variables.
- You cannot exclude individual users or groups from being available on the domain member. Only users and groups whose calculated UID or GID is outside of the configured range are excluded.
Prerequisites
- You installed Samba.
-
The Samba configuration, except ID mapping, exists in the
/etc/samba/smb.conffile.
Procedure
Edit the
[global]section in the/etc/samba/smb.conffile:Enable the
autoridID mapping back end for the*default domain:idmap config * : backend = autorid
idmap config * : backend = autoridCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set a range that is big enough to assign IDs for all existing and future objects. For example:
idmap config * : range = 10000-999999
idmap config * : range = 10000-999999Copy to Clipboard Copied! Toggle word wrap Toggle overflow Samba ignores users and groups whose calculated IDs in this domain are not within the range.
WarningAfter you set the range and Samba starts using it, you can only increase the upper limit of the range. Any other change to the range can result in new ID assignments, and thus in losing file ownerships.
Optional: Set a range size. For example:
idmap config * : rangesize = 200000
idmap config * : rangesize = 200000Copy to Clipboard Copied! Toggle word wrap Toggle overflow Samba assigns this number of continuous IDs for each domain’s object until all IDs from the range set in the
idmap config * : rangeparameter are taken.NoteIf you set a rangesize, you need to adapt the range accordingly. The range needs to be a multiple of the rangesize.
Set a shell and home directory path that will be assigned to all mapped users. For example:
template shell = /bin/bash template homedir = /home/%U
template shell = /bin/bash template homedir = /home/%UCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Add additional ID mapping configuration for domains. If no configuration for an individual domain is available, Samba calculates the ID using the
autoridback end settings in the previously configured*default domain.ImportantThe range must not overlap with any other domain configuration on this server. Additionally, the range must be set big enough to include all IDs assigned in the future. For further details, see Planning Samba ID ranges.
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the Samba configuration:
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.5. Setting up Samba as an AD domain member server Link kopierenLink in die Zwischenablage kopiert!
If you are running an AD or NT4 domain, use Samba to add your Red Hat Enterprise Linux server as a member to the domain to gain the following:
- Access domain resources on other domain members
-
Authenticate domain users to local services, such as
sshd - Share directories and printers hosted on the server to act as a file and print server
3.5.1. Joining a RHEL system to an AD domain Link kopierenLink in die Zwischenablage kopiert!
Samba Winbind is an alternative to the System Security Services Daemon (SSSD) for connecting a Red Hat Enterprise Linux (RHEL) system with Active Directory (AD). You can join a RHEL system to an AD domain by using realmd to configure Samba Winbind.
Prerequisites
- The host uses a DNS server that can resolve the AD domain.
- The time on the host is synchronized with the time in AD and the time zone settings are correct.
Procedure
If your AD requires the deprecated RC4 encryption type for Kerberos authentication, enable support for these ciphers in RHEL:
update-crypto-policies --set DEFAULT:AD-SUPPORT
# update-crypto-policies --set DEFAULT:AD-SUPPORTCopy to Clipboard Copied! Toggle word wrap Toggle overflow Install the following packages:
yum install realmd oddjob-mkhomedir oddjob samba-winbind-clients \ samba-winbind samba-common-tools samba-winbind-krb5-locator krb5-workstation# yum install realmd oddjob-mkhomedir oddjob samba-winbind-clients \ samba-winbind samba-common-tools samba-winbind-krb5-locator krb5-workstationCopy to Clipboard Copied! Toggle word wrap Toggle overflow To share directories or printers on the domain member, install the
sambapackage:yum install samba
# yum install sambaCopy to Clipboard Copied! Toggle word wrap Toggle overflow Backup the existing
/etc/samba/smb.confSamba configuration file:mv /etc/samba/smb.conf /etc/samba/smb.conf.bak
# mv /etc/samba/smb.conf /etc/samba/smb.conf.bakCopy to Clipboard Copied! Toggle word wrap Toggle overflow Join the domain. For example, to join a domain named
ad.example.com:realm join --membership-software=samba --client-software=winbind ad.example.com
# realm join --membership-software=samba --client-software=winbind ad.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using the previous command, the
realmutility automatically:-
Creates a
/etc/samba/smb.conffile for a membership in thead.example.comdomain -
Adds the
winbindmodule for user and group lookups to the/etc/nsswitch.conffile -
Updates the Pluggable Authentication Module (PAM) configuration files in the
/etc/pam.d/directory -
Starts the
winbindservice and enables the service to start when the system boots
-
Creates a
Optional: Set an alternative ID mapping back end or customized ID mapping settings in the
/etc/samba/smb.conffile.For details, see Understanding and configuring Samba ID mapping.
Verify that the
winbindservice is running:systemctl status winbind
# systemctl status winbind ... Active: active (running) since Tue 2018-11-06 19:10:40 CET; 15s agoCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantTo enable Samba to query domain user and group information, the
winbindservice must be running before you startsmb.If you installed the
sambapackage to share directories and printers, enable and start thesmbservice:systemctl enable --now smb
# systemctl enable --now smbCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
If you are authenticating local logins to Active Directory, enable the
winbind_krb5_localauthplug-in. See Using the local authorization plug-in for MIT Kerberos.
Verification
Display an AD user’s details, such as the AD administrator account in the AD domain:
getent passwd "AD\administrator"
# getent passwd "AD\administrator" AD\administrator:*:10000:10000::/home/administrator@AD:/bin/bashCopy to Clipboard Copied! Toggle word wrap Toggle overflow Query the members of the domain users group in the AD domain:
getent group "AD\Domain Users"
# getent group "AD\Domain Users" AD\domain users:x:10000:user1,user2Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Verify that you can use domain users and groups when you set permissions on files and directories. For example, to set the owner of the
/srv/samba/example.txtfile toAD\administratorand the group toAD\Domain Users:chown "AD\administrator":"AD\Domain Users" /srv/samba/example.txt
# chown "AD\administrator":"AD\Domain Users" /srv/samba/example.txtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that Kerberos authentication works as expected:
On the AD domain member, obtain a ticket for the
administrator@AD.EXAMPLE.COMprincipal:kinit administrator@AD.EXAMPLE.COM
# kinit administrator@AD.EXAMPLE.COMCopy to Clipboard Copied! Toggle word wrap Toggle overflow Display the cached Kerberos ticket:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Display the available domains:
wbinfo --all-domains
# wbinfo --all-domains BUILTIN SAMBA-SERVER ADCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.5.2. Using the local authorization plug-in for MIT Kerberos Link kopierenLink in die Zwischenablage kopiert!
The winbind service provides Active Directory users to the domain member. In certain situations, administrators want to enable domain users to authenticate to local services, such as an SSH server, which are running on the domain member. When using Kerberos to authenticate the domain users, enable the winbind_krb5_localauth plug-in to correctly map Kerberos principals to Active Directory accounts through the winbind service.
For example, if the sAMAccountName attribute of an Active Directory user is set to EXAMPLE and the user tries to log with the user name lowercase, Kerberos returns the user name in upper case. As a consequence, the entries do not match and authentication fails.
Using the winbind_krb5_localauth plug-in, the account names are mapped correctly. Note that this only applies to GSSAPI authentication and not for getting the initial ticket granting ticket (TGT).
Prerequisites
- Samba is configured as a member of an Active Directory.
- Red Hat Enterprise Linux authenticates log in attempts against Active Directory.
-
The
winbindservice is running.
Procedure
Edit the /etc/krb5.conf file and add the following section:
[plugins]
localauth = {
module = winbind:/usr/lib64/samba/krb5/winbind_krb5_localauth.so
enable_only = winbind
}
[plugins]
localauth = {
module = winbind:/usr/lib64/samba/krb5/winbind_krb5_localauth.so
enable_only = winbind
}
3.6. Setting up Samba on an IdM domain member Link kopierenLink in die Zwischenablage kopiert!
You can set up Samba on a host that is joined to a Red Hat Identity Management (IdM) domain. Users from IdM and also, if available, from trusted Active Directory (AD) domains, can access shares and printer services provided by Samba.
Using Samba on an IdM domain member is an unsupported Technology Preview feature and contains certain limitations. For example, IdM trust controllers do not support the Active Directory Global Catalog service, and they do not support resolving IdM groups using the Distributed Computing Environment / Remote Procedure Calls (DCE/RPC) protocols. As a consequence, AD users can only access Samba shares and printers hosted on IdM clients when logged in to other IdM clients; AD users logged into a Windows machine cannot access Samba shares hosted on an IdM domain member.
Customers deploying Samba on IdM domain members are encouraged to provide feedback to Red Hat.
If users from AD domains need to access shares and printer services provided by Samba, ensure the AES encryption type is enabled is AD. For more information, see Enabling the AES encryption type in Active Directory using a GPO.
Prerequisites
- The host is joined as a client to the IdM domain.
- Both the IdM servers and the client must run on RHEL 8.1 or later.
3.6.1. Preparing the IdM domain for installing Samba on domain members Link kopierenLink in die Zwischenablage kopiert!
Before you can set up Samba on an IdM client, you must prepare the IdM domain using the ipa-adtrust-install utility on an IdM server.
Any system where you run the ipa-adtrust-install command automatically becomes an AD trust controller. However, you must run ipa-adtrust-install only once on an IdM server.
Prerequisites
- IdM server is installed.
- You have root privileges to install packages and restart IdM services.
Procedure
Install the required packages:
yum install ipa-server-trust-ad samba-client
[root@ipaserver ~]# yum install ipa-server-trust-ad samba-clientCopy to Clipboard Copied! Toggle word wrap Toggle overflow Authenticate as the IdM administrative user:
kinit admin
[root@ipaserver ~]# kinit adminCopy to Clipboard Copied! Toggle word wrap Toggle overflow Run the
ipa-adtrust-installutility:ipa-adtrust-install
[root@ipaserver ~]# ipa-adtrust-installCopy to Clipboard Copied! Toggle word wrap Toggle overflow The DNS service records are created automatically if IdM was installed with an integrated DNS server.
If you installed IdM without an integrated DNS server,
ipa-adtrust-installprints a list of service records that you must manually add to DNS before you can continue.The script prompts you that the
/etc/samba/smb.confalready exists and will be rewritten:WARNING: The smb.conf already exists. Running ipa-adtrust-install will break your existing Samba configuration. Do you wish to continue? [no]: yes
WARNING: The smb.conf already exists. Running ipa-adtrust-install will break your existing Samba configuration. Do you wish to continue? [no]: yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow The script prompts you to configure the
slapi-nisplug-in, a compatibility plug-in that allows older Linux clients to work with trusted users:Do you want to enable support for trusted domains in Schema Compatibility plugin? This will allow clients older than SSSD 1.9 and non-Linux clients to work with trusted users. Enable trusted domains support in slapi-nis? [no]: yes
Do you want to enable support for trusted domains in Schema Compatibility plugin? This will allow clients older than SSSD 1.9 and non-Linux clients to work with trusted users. Enable trusted domains support in slapi-nis? [no]: yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow When prompted, enter the NetBIOS name for the IdM domain or press Enter to accept the name suggested:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow You are prompted to run the SID generation task to create a SID for any existing users:
Do you want to run the ipa-sidgen task? [no]: yes
Do you want to run the ipa-sidgen task? [no]: yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow This is a resource-intensive task, so if you have a high number of users, you can run this at another time.
Optional: By default, the Dynamic RPC port range is defined as
49152-65535for Windows Server 2008 and later. If you need to define a different Dynamic RPC port range for your environment, configure Samba to use different ports and open those ports in your firewall settings. The following example sets the port range to55000-65000.net conf setparm global 'rpc server dynamic port range' 55000-65000 firewall-cmd --add-port=55000-65000/tcp firewall-cmd --runtime-to-permanent
[root@ipaserver ~]# net conf setparm global 'rpc server dynamic port range' 55000-65000 [root@ipaserver ~]# firewall-cmd --add-port=55000-65000/tcp [root@ipaserver ~]# firewall-cmd --runtime-to-permanentCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
ipaservice:ipactl restart
[root@ipaserver ~]# ipactl restartCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
smbclientutility to verify that Samba responds to Kerberos authentication from the IdM side:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.6.2. Installing and configuring a Samba server on an IdM client Link kopierenLink in die Zwischenablage kopiert!
You can install and configure Samba on a client enrolled in an IdM domain.
Prerequisites
- Both the IdM servers and the client must run on RHEL 8.1 or later.
- The IdM domain is prepared as described in Preparing the IdM domain for installing Samba on domain members.
- If IdM has a trust configured with AD, enable the AES encryption type for Kerberos. For example, use a group policy object (GPO) to enable the AES encryption type. For details, see Enabling AES encryption in Active Directory using a GPO.
Procedure
Install the
ipa-client-sambapackage:yum install ipa-client-samba
[root@idm_client]# yum install ipa-client-sambaCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
ipa-client-sambautility to prepare the client and create an initial Samba configuration:Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default,
ipa-client-sambaautomatically adds the[homes]section to the/etc/samba/smb.conffile that dynamically shares a user’s home directory when the user connects. If users do not have home directories on this server, or if you do not want to share them, remove the following lines from/etc/samba/smb.conf:[homes] read only = no[homes] read only = noCopy to Clipboard Copied! Toggle word wrap Toggle overflow Share directories and printers. For details, see:
Open the ports required for a Samba client in the local firewall:
firewall-cmd --permanent --add-service=samba-client firewall-cmd --reload
[root@idm_client]# firewall-cmd --permanent --add-service=samba-client [root@idm_client]# firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
smbandwinbindservices:systemctl enable --now smb winbind
[root@idm_client]# systemctl enable --now smb winbindCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Run the following verification step on a different IdM domain member that has the samba-client package installed:
List the shares on the Samba server using Kerberos authentication:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.6.3. Manually adding an ID mapping configuration if IdM trusts a new domain Link kopierenLink in die Zwischenablage kopiert!
Samba requires an ID mapping configuration for each domain from which users access resources. On an existing Samba server running on an IdM client, you must manually add an ID mapping configuration after the administrator added a new trust to an Active Directory (AD) domain.
Prerequisites
- You configured Samba on an IdM client. Afterward, a new trust was added to IdM.
- The DES and RC4 encryption types for Kerberos must be disabled in the trusted AD domain. For security reasons, RHEL 8 does not support these weak encryption types.
Procedure
Authenticate using the host’s keytab:
kinit -k
[root@idm_client]# kinit -kCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
ipa idrange-findcommand to display both the base ID and the ID range size of the new domain. For example, the following command displays the values for thead.example.comdomain:Copy to Clipboard Copied! Toggle word wrap Toggle overflow You need the values from the
ipabaseidandipaidrangesizeattributes in the next steps.To calculate the highest usable ID, use the following formula:
maximum_range = ipabaseid + ipaidrangesize - 1
maximum_range = ipabaseid + ipaidrangesize - 1Copy to Clipboard Copied! Toggle word wrap Toggle overflow With the values from the previous step, the highest usable ID for the
ad.example.comdomain is1918599999(1918400000 + 200000 - 1).Edit the
/etc/samba/smb.conffile, and add the ID mapping configuration for the domain to the[global]section:idmap config AD : range = 1918400000 - 1918599999 idmap config AD : backend = sss
idmap config AD : range = 1918400000 - 1918599999 idmap config AD : backend = sssCopy to Clipboard Copied! Toggle word wrap Toggle overflow Specify the value from
ipabaseidattribute as the lowest and the computed value from the previous step as the highest value of the range.Restart the
smbandwinbindservices:systemctl restart smb winbind
[root@idm_client]# systemctl restart smb winbindCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
List the shares on the Samba server using Kerberos authentication:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.13. Configuring Samba for macOS clients Link kopierenLink in die Zwischenablage kopiert!
The fruit virtual file system (VFS) Samba module provides enhanced compatibility with Apple server message block (SMB) clients.
3.15. Setting up Samba as a print server Link kopierenLink in die Zwischenablage kopiert!
If you set up Samba as a print server, clients in your network can use Samba to print. Additionally, Windows clients can, if configured, download the driver from the Samba server.
Parts of this section were adopted from the Setting up Samba as a Print Server documentation published in the Samba Wiki. License: CC BY 4.0. Authors and contributors: See the history tab on the Wiki page.
Prerequisites
Samba has been set up in one of the following modes:
3.15.1. Enabling print server support in Samba Link kopierenLink in die Zwischenablage kopiert!
By default, print server support is not enabled in Samba. To use Samba as a print server, you must configure Samba accordingly.
Print jobs and printer operations require remote procedure calls (RPCs). By default, Samba starts the rpcd_spoolss service on demand to manage RPCs. During the first RPC call, or when you update the printer list in CUPS, Samba retrieves the printer information from CUPS. This can require approximately 1 second per printer. Therefore, if you have more than 50 printers, tune the rpcd_spoolss settings.
Prerequisites
The printers are configured in a CUPS server.
For details about configuring printers in CUPS, see the documentation provided in the CUPS web console (https://printserver:631/help) on the print server.
Procedure
Edit the
/etc/samba/smb.conffile:Add the
[printers]section to enable the printing backend in Samba:[printers] comment = All Printers path = /var/tmp/ printable = yes create mask = 0600[printers] comment = All Printers path = /var/tmp/ printable = yes create mask = 0600Copy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantThe
[printers]share name is hard-coded and cannot be changed.If the CUPS server runs on a different host or port, specify the setting in the
[printers]section:cups server = printserver.example.com:631
cups server = printserver.example.com:631Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you have many printers, set the number of idle seconds to a higher value than the numbers of printers connected to CUPS. For example, if you have 100 printers, set in the
[global]section:rpcd_spoolss:idle_seconds = 200
rpcd_spoolss:idle_seconds = 200Copy to Clipboard Copied! Toggle word wrap Toggle overflow If this setting does not scale in your environment, also increase the number of
rpcd_spoolssworkers in the[global]section:rpcd_spoolss:num_workers = 10
rpcd_spoolss:num_workers = 10Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default,
rpcd_spoolssstarts 5 workers.
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Open the required ports and reload the firewall configuration using the
firewall-cmdutility:firewall-cmd --permanent --add-service=samba firewall-cmd --reload
# firewall-cmd --permanent --add-service=samba # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
smbservice:systemctl restart smb
# systemctl restart smbCopy to Clipboard Copied! Toggle word wrap Toggle overflow After restarting the service, Samba automatically shares all printers that are configured in the CUPS back end. If you want to manually share only specific printers, see Manually sharing specific printers.
Verification
Submit a print job. For example, to print a PDF file, enter:
smbclient -Uuser //sambaserver.example.com/printer_name -c "print example.pdf"
# smbclient -Uuser //sambaserver.example.com/printer_name -c "print example.pdf"Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.15.2. Manually sharing specific printers Link kopierenLink in die Zwischenablage kopiert!
If you configured Samba as a print server, by default, Samba shares all printers that are configured in the CUPS back end. The following procedure explains how to share only specific printers.
Prerequisites
- Samba is set up as a print server
Procedure
Edit the
/etc/samba/smb.conffile:In the
[global]section, disable automatic printer sharing by setting:load printers = no
load printers = noCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add a section for each printer you want to share. For example, to share the printer named
examplein the CUPS back end asExample-Printerin Samba, add the following section:[Example-Printer] path = /var/tmp/ printable = yes printer name = example[Example-Printer] path = /var/tmp/ printable = yes printer name = exampleCopy to Clipboard Copied! Toggle word wrap Toggle overflow You do not need individual spool directories for each printer. You can set the same spool directory in the
pathparameter for the printer as you set in the[printers]section.
Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the Samba configuration:
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.16. Setting up automatic printer driver downloads for Windows clients on Samba print servers Link kopierenLink in die Zwischenablage kopiert!
If you are running a Samba print server for Windows clients, you can upload drivers and preconfigure printers. If a user connects to a printer, Windows automatically downloads and installs the driver locally on the client. The user does not require local administrator permissions for the installation. Additionally, Windows applies preconfigured driver settings, such as the number of trays.
Parts of this section were adopted from the Setting up Automatic Printer Driver Downloads for Windows Clients documentation published in the Samba Wiki. License: CC BY 4.0. Authors and contributors: See the history tab on the Wiki page.
Prerequisites
- Samba is set up as a print server
3.16.1. Basic information about printer drivers Link kopierenLink in die Zwischenablage kopiert!
This section provides general information about printer drivers.
Supported driver model version
Samba only supports the printer driver model version 3 which is supported in Windows 2000 and later, and Windows Server 2000 and later. Samba does not support the driver model version 4, introduced in Windows 8 and Windows Server 2012. However, these and later Windows versions also support version 3 drivers.
Package-aware drivers
Samba does not support package-aware drivers.
Preparing a printer driver for being uploaded
Before you can upload a driver to a Samba print server:
- Unpack the driver if it is provided in a compressed format.
Some drivers require to start a setup application that installs the driver locally on a Windows host. In certain situations, the installer extracts the individual files into the operating system’s temporary folder during the setup runs. To use the driver files for uploading:
- Start the installer.
- Copy the files from the temporary folder to a new location.
- Cancel the installation.
Ask your printer manufacturer for drivers that support uploading to a print server.
Providing 32-bit and 64-bit drivers for a printer to a client
To provide the driver for a printer for both 32-bit and 64-bit Windows clients, you must upload a driver with exactly the same name for both architectures. For example, if you are uploading the 32-bit driver named Example PostScript and the 64-bit driver named Example PostScript (v1.0), the names do not match. Consequently, you can only assign one of the drivers to a printer and the driver will not be available for both architectures.
3.16.2. Enabling users to upload and preconfigure drivers Link kopierenLink in die Zwischenablage kopiert!
To be able to upload and preconfigure printer drivers, a user or a group needs to have the SePrintOperatorPrivilege privilege granted. A user must be added into the printadmin group. Red Hat Enterprise Linux automatically creates this group when you install the samba package. The printadmin group gets assigned the lowest available dynamic system GID that is lower than 1000.
Procedure
For example, to grant the
SePrintOperatorPrivilegeprivilege to theprintadmingroup:net rpc rights grant "printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator"
# net rpc rights grant "printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator" Enter DOMAIN\administrator's password: Successfully granted rights.Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteIn a domain environment, grant
SePrintOperatorPrivilegeto a domain group. This enables you to centrally manage the privilege by updating a user’s group membership.To list all users and groups having
SePrintOperatorPrivilegegranted:net rpc rights list privileges SePrintOperatorPrivilege -U "DOMAIN\administrator"
# net rpc rights list privileges SePrintOperatorPrivilege -U "DOMAIN\administrator" Enter administrator's password: SePrintOperatorPrivilege: BUILTIN\Administrators DOMAIN\printadminCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.16.4. Creating a GPO to enable clients to trust the Samba print server Link kopierenLink in die Zwischenablage kopiert!
For security reasons, recent Windows operating systems prevent clients from downloading non-package-aware printer drivers from an untrusted server. If your print server is a member in an AD, you can create a Group Policy Object (GPO) in your domain to trust the Samba server.
Prerequisites
- The Samba print server is a member of an AD domain.
- The Windows computer you are using to create the GPO must have the Windows Remote Server Administration Tools (RSAT) installed. For details, see the Windows documentation.
Procedure
-
Log into a Windows computer using an account that is allowed to edit group policies, such as the AD domain
Administratoruser. -
Open the
Group Policy Management Console. Right-click to your AD domain and select
Create a GPO in this domain, and Link it here.-
Enter a name for the GPO, such as
Legacy Printer Driver Policyand clickOK. The new GPO will be displayed under the domain entry. -
Right-click to the newly-created GPO and select
Editto open theGroup Policy Management Editor. Navigate to → → → .
On the right side of the window, double-click
Point and Print Restrictionto edit the policy:Enable the policy and set the following options:
-
Select
Users can only point and print to these serversand enter the fully-qualified domain name (FQDN) of the Samba print server to the field next to this option. In both check boxes under
Security Prompts, selectDo not show warning or elevation prompt.
-
Select
- Click OK.
Double-click
Package Point and Print - Approved serversto edit the policy:-
Enable the policy and click the
Showbutton. Enter the FQDN of the Samba print server.
-
Close both the
Show Contentsand the policy’s properties window by clickingOK.
-
Enable the policy and click the
-
Close the
Group Policy Management Editor. -
Close the
Group Policy Management Console.
After the Windows domain members applied the group policy, printer drivers are automatically downloaded from the Samba server when a user connects to a printer.
3.16.5. Uploading drivers and preconfiguring printers Link kopierenLink in die Zwischenablage kopiert!
Use the Print Management application on a Windows client to upload drivers and preconfigure printers hosted on the Samba print server. For further details, see the Windows documentation.
3.17. Running Samba on a server with FIPS mode enabled Link kopierenLink in die Zwischenablage kopiert!
This section provides an overview of the limitations of running Samba with FIPS mode enabled. It also provides the procedure for enabling FIPS mode on a Red Hat Enterprise Linux host running Samba.
3.17.1. Limitations of using Samba in FIPS mode Link kopierenLink in die Zwischenablage kopiert!
The following Samba modes and features work in FIPS mode under the indicated conditions:
- Samba as a domain member only in Active Directory (AD) or Red Hat Enterprise Linux Identity Management (IdM) environments with Kerberos authentication that uses AES ciphers.
- Samba as a file server on an Active Directory domain member. However, this requires that clients use Kerberos to authenticate to the server.
Due to the increased security of FIPS, the following Samba features and modes do not work if FIPS mode is enabled:
- NT LAN Manager (NTLM) authentication because RC4 ciphers are blocked
- The server message block version 1 (SMB1) protocol
- The stand-alone file server mode because it uses NTLM authentication
- NT4-style domain controllers
- NT4-style domain members. Note that Red Hat continues supporting the primary domain controller (PDC) functionality IdM uses in the background.
- Password changes against the Samba server. You can only perform password changes using Kerberos against an Active Directory domain controller.
The following feature is not tested in FIPS mode and, therefore, is not supported by Red Hat:
- Running Samba as a print server
3.17.2. Using Samba in FIPS mode Link kopierenLink in die Zwischenablage kopiert!
You can enable the FIPS mode on a RHEL host that runs Samba.
Prerequisites
- Samba is configured on the Red Hat Enterprise Linux host.
- Samba runs in a mode that is supported in FIPS mode.
Procedure
Enable the FIPS mode on RHEL:
fips-mode-setup --enable
# fips-mode-setup --enableCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reboot the server:
reboot
# rebootCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
testparmutility to verify the configuration:testparm -s
# testparm -sCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays any errors or incompatibilities, fix them to ensure that Samba works correctly.
3.18. Tuning the performance of a Samba server Link kopierenLink in die Zwischenablage kopiert!
Learn what settings can improve the performance of Samba in certain situations, and which settings can have a negative performance impact.
Parts of this section were adopted from the Performance Tuning documentation published in the Samba Wiki. License: CC BY 4.0. Authors and contributors: See the history tab on the Wiki page.
Prerequisites
- Samba is set up as a file or print server
3.18.1. Setting the SMB protocol version Link kopierenLink in die Zwischenablage kopiert!
Each new SMB version adds features and improves the performance of the protocol. The recent Windows and Windows Server operating systems always supports the latest protocol version. If Samba also uses the latest protocol version, Windows clients connecting to Samba benefit from the performance improvements. In Samba, the default value of the server max protocol is set to the latest supported stable SMB protocol version.
To always have the latest stable SMB protocol version enabled, do not set the server max protocol parameter. If you set the parameter manually, you will need to modify the setting with each new version of the SMB protocol, to have the latest protocol version enabled.
The following procedure explains how to use the default value in the server max protocol parameter.
Procedure
-
Remove the
server max protocolparameter from the[global]section in the/etc/samba/smb.conffile. Reload the Samba configuration
smbcontrol all reload-config
# smbcontrol all reload-configCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.18.3. Settings that can have a negative performance impact Link kopierenLink in die Zwischenablage kopiert!
By default, the kernel in Red Hat Enterprise Linux is tuned for high network performance. For example, the kernel uses an auto-tuning mechanism for buffer sizes. Setting the socket options parameter in the /etc/samba/smb.conf file overrides these kernel settings. As a result, setting this parameter decreases the Samba network performance in most cases.
To use the optimized settings from the Kernel, remove the socket options parameter from the [global] section in the /etc/samba/smb.conf.
3.19. Configuring Samba to be compatible with clients that require an SMB version lower than the default Link kopierenLink in die Zwischenablage kopiert!
Samba uses a reasonable and secure default value for the minimum server message block (SMB) version it supports. However, if you have clients that require an older SMB version, you can configure Samba to support it.
3.19.1. Setting the minimum SMB protocol version supported by a Samba server Link kopierenLink in die Zwischenablage kopiert!
In Samba, the server min protocol parameter in the /etc/samba/smb.conf file defines the minimum server message block (SMB) protocol version the Samba server supports. You can change the minimum SMB protocol version.
By default, Samba on RHEL 8.2 and later supports only SMB2 and newer protocol versions. Red Hat recommends to not use the deprecated SMB1 protocol. However, if your environment requires SMB1, you can manually set the server min protocol parameter to NT1 to re-enable SMB1.
Prerequisites
- Samba is installed and configured.
Procedure
Edit the
/etc/samba/smb.conffile, add theserver min protocolparameter, and set the parameter to the minimum SMB protocol version the server should support. For example, to set the minimum SMB protocol version toSMB3, add:server min protocol = SMB3
server min protocol = SMB3Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
smbservice:systemctl restart smb
# systemctl restart smbCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.20. Frequently used Samba command-line utilities Link kopierenLink in die Zwischenablage kopiert!
This chapter describes frequently used commands when working with a Samba server.
3.20.1. Using the net ads join and net rpc join commands Link kopierenLink in die Zwischenablage kopiert!
Using the join subcommand of the net utility, you can join Samba to an AD or NT4 domain. To join the domain, you must create the /etc/samba/smb.conf file manually, and optionally update additional configurations, such as PAM.
Red Hat recommends using the realm utility to join a domain. The realm utility automatically updates all involved configuration files.
Procedure
Manually create the
/etc/samba/smb.conffile with the following settings:For an AD domain member:
[global] workgroup = domain_name security = ads passdb backend = tdbsam realm = AD_REALM
[global] workgroup = domain_name security = ads passdb backend = tdbsam realm = AD_REALMCopy to Clipboard Copied! Toggle word wrap Toggle overflow For an NT4 domain member:
[global] workgroup = domain_name security = user passdb backend = tdbsam
[global] workgroup = domain_name security = user passdb backend = tdbsamCopy to Clipboard Copied! Toggle word wrap Toggle overflow
-
Add an ID mapping configuration for the
*default domain and for the domain you want to join to the[global] section in the/etc/samba/smb.conffile. Verify the
/etc/samba/smb.conffile:testparm
# testparmCopy to Clipboard Copied! Toggle word wrap Toggle overflow Join the domain as the domain administrator:
To join an AD domain:
net ads join -U "DOMAIN\administrator"
# net ads join -U "DOMAIN\administrator"Copy to Clipboard Copied! Toggle word wrap Toggle overflow To join an NT4 domain:
net rpc join -U "DOMAIN\administrator"
# net rpc join -U "DOMAIN\administrator"Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Append the
winbindsource to thepasswdandgroupdatabase entry in the/etc/nsswitch.conffile:passwd: files winbind group: files winbind
passwd: files winbind group: files winbindCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
winbindservice:systemctl enable --now winbind
# systemctl enable --now winbindCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Configure PAM using the
authselectutility.For details, see the
authselect(8)man page on your system.Optional: For AD environments, configure the Kerberos client.
For details, see the documentation of your Kerberos client.
3.20.2. Using the net rpc rights command Link kopierenLink in die Zwischenablage kopiert!
In Windows, you can assign privileges to accounts and groups to perform special operations, such as setting ACLs on a share or upload printer drivers. On a Samba server, you can use the net rpc rights command to manage privileges.
Listing privileges you can set
To list all available privileges and their owners, use the net rpc rights list command. For example:
Granting privileges
To grant a privilege to an account or group, use the net rpc rights grant command.
For example, grant the SePrintOperatorPrivilege privilege to the DOMAIN\printadmin group:
net rpc rights grant "DOMAIN\printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator"
# net rpc rights grant "DOMAIN\printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator"
Enter DOMAIN\administrator's password:
Successfully granted rights.
Revoking privileges
To revoke a privilege from an account or group, use the net rpc rights revoke command.
For example, to revoke the SePrintOperatorPrivilege privilege from the DOMAIN\printadmin group:
net rpc rights remoke "DOMAIN\printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator"
# net rpc rights remoke "DOMAIN\printadmin" SePrintOperatorPrivilege -U "DOMAIN\administrator"
Enter DOMAIN\administrator's password:
Successfully revoked rights.
3.20.4. Using the net user command Link kopierenLink in die Zwischenablage kopiert!
The net user command enables you to perform the following actions on an AD DC or NT4 PDC:
- List all user accounts
- Add users
- Remove Users
Specifying a connection method, such as ads for AD domains or rpc for NT4 domains, is only required when you list domain user accounts. Other user-related subcommands can auto-detect the connection method.
Pass the -U user_name parameter to the command to specify a user that is allowed to perform the requested action.
Listing domain user accounts
To list all users in an AD domain:
net ads user -U "DOMAIN\administrator"
# net ads user -U "DOMAIN\administrator"
To list all users in an NT4 domain:
net rpc user -U "DOMAIN\administrator"
# net rpc user -U "DOMAIN\administrator"
Adding a user account to the domain
On a Samba domain member, you can use the net user add command to add a user account to the domain.
For example, add the user account to the domain:
Add the account:
net user add user password -U "DOMAIN\administrator"
# net user add user password -U "DOMAIN\administrator" User user addedCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Use the remote procedure call (RPC) shell to enable the account on the AD DC or NT4 PDC. For example:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Deleting a user account from the domain
On a Samba domain member, you can use the net user delete command to remove a user account from the domain.
For example, to remove the user account from the domain:
net user delete user -U "DOMAIN\administrator"
# net user delete user -U "DOMAIN\administrator"
User user deleted
3.20.5. Using the rpcclient utility Link kopierenLink in die Zwischenablage kopiert!
The rpcclient utility enables you to manually execute client-side Microsoft Remote Procedure Call (MS-RPC) functions on a local or remote SMB server. However, most of the features are integrated into separate utilities provided by Samba. Use rpcclient only for testing MS-PRC functions.
Prerequisites
-
The
samba-clientpackage is installed.
Examples
For example, you can use the rpcclient utility to:
Manage the printer Spool Subsystem (SPOOLSS).
Example 3.7. Assigning a Driver to a Printer
rpcclient server_name -U "DOMAIN\administrator" -c 'setdriver "printer_name" "driver_name"'
# rpcclient server_name -U "DOMAIN\administrator" -c 'setdriver "printer_name" "driver_name"' Enter DOMAIN\administrators password: Successfully set printer_name to driver driver_name.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Retrieve information about an SMB server.
Example 3.8. Listing all File Shares and Shared Printers
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Perform actions using the Security Account Manager Remote (SAMR) protocol.
Example 3.9. Listing Users on an SMB Server
rpcclient server_name -U "DOMAIN\administrator" -c 'enumdomusers'
# rpcclient server_name -U "DOMAIN\administrator" -c 'enumdomusers' Enter DOMAIN\administrators password: user:[user1] rid:[0x3e8] user:[user2] rid:[0x3e9]Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you run the command against a standalone server or a domain member, it lists the users in the local database. Running the command against an AD DC or NT4 PDC lists the domain users.
3.20.6. Using the samba-regedit application Link kopierenLink in die Zwischenablage kopiert!
Certain settings, such as printer configurations, are stored in the registry on the Samba server. You can use the ncurses-based samba-regedit application to edit the registry of a Samba server.
Prerequisites
-
The
samba-clientpackage is installed.
Procedure
To start the application, enter:
samba-regedit
# samba-regedit
Use the following keys:
- Cursor up and cursor down: Navigate through the registry tree and the values.
- Enter: Opens a key or edits a value.
-
Tab: Switches between the
KeyandValuepane. - Ctrl+C: Closes the application.
3.20.7. Using the smbcontrol utility Link kopierenLink in die Zwischenablage kopiert!
The smbcontrol utility enables you to send command messages to the smbd, nmbd, winbindd, or all of these services. These control messages instruct the service, for example, to reload its configuration.
Prerequisites
-
The
samba-common-toolspackage is installed.
Procedure
-
Reload the configuration of the
smbd,nmbd,winbinddservices by sending thereload-configmessage type to thealldestination:
smbcontrol all reload-config
# smbcontrol all reload-config
3.20.8. Using the smbpasswd utility Link kopierenLink in die Zwischenablage kopiert!
The smbpasswd utility manages user accounts and passwords in the local Samba database.
Prerequisites
-
The
samba-common-toolspackage is installed.
Procedure
If you run the command as a user,
smbpasswdchanges the Samba password of the user who run the command. For example:smbpasswd
[user@server ~]$ smbpasswd New SMB password: password Retype new SMB password: passwordCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run
smbpasswdas therootuser, you can use the utility, for example, to:Create a new user:
smbpasswd -a user_name
[root@server ~]# smbpasswd -a user_name New SMB password: password Retype new SMB password: password Added user user_name.Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteBefore you can add a user to the Samba database, you must create the account in the local operating system. See the Adding a new user from the command line section in the Configuring basic system settings guide.
Enable a Samba user:
smbpasswd -e user_name
[root@server ~]# smbpasswd -e user_name Enabled user user_name.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Disable a Samba user:
smbpasswd -x user_name
[root@server ~]# smbpasswd -x user_name Disabled user user_nameCopy to Clipboard Copied! Toggle word wrap Toggle overflow Delete a user:
smbpasswd -x user_name
[root@server ~]# smbpasswd -x user_name Deleted user user_name.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.20.9. Using the smbstatus utility Link kopierenLink in die Zwischenablage kopiert!
The smbstatus utility reports on:
-
Connections per PID of each
smbddaemon to the Samba server. This report includes the user name, primary group, SMB protocol version, encryption, and signing information. -
Connections per Samba share. This report includes the PID of the
smbddaemon, the IP of the connecting machine, the time stamp when the connection was established, encryption, and signing information. - A list of locked files. The report entries include further details, such as opportunistic lock (oplock) types
Prerequisites
-
The
sambapackage is installed. -
The
smbdservice is running.
Procedure
3.20.10. Using the smbtar utility Link kopierenLink in die Zwischenablage kopiert!
The smbtar utility backs up the content of an SMB share or a subdirectory of it and stores the content in a tar archive. Alternatively, you can write the content to a tape device.
Prerequisites
-
The
samba-clientpackage is installed.
Procedure
Use the following command to back up the content of the
demodirectory on the//server/example/share and store the content in the/root/example.tararchive:smbtar -s server -x example -u user_name -p password -t /root/example.tar
# smbtar -s server -x example -u user_name -p password -t /root/example.tarCopy to Clipboard Copied! Toggle word wrap Toggle overflow
3.20.11. Using the wbinfo utility Link kopierenLink in die Zwischenablage kopiert!
The wbinfo utility queries and returns information created and used by the winbindd service.
Prerequisites
-
The
samba-winbind-clientspackage is installed.
Procedure
You can use wbinfo, for example, to:
List domain users:
wbinfo -u
# wbinfo -u AD\administrator AD\guest ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow List domain groups:
wbinfo -g
# wbinfo -g AD\domain computers AD\domain admins AD\domain users ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow Display the SID of a user:
wbinfo --name-to-sid="AD\administrator"
# wbinfo --name-to-sid="AD\administrator" S-1-5-21-1762709870-351891212-3141221786-500 SID_USER (1)Copy to Clipboard Copied! Toggle word wrap Toggle overflow Display information about domains and trusts:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Chapter 4. Setting up and configuring a BIND DNS server Link kopierenLink in die Zwischenablage kopiert!
BIND is a feature-rich DNS server that is fully compliant with the Internet Engineering Task Force (IETF) DNS standards and draft standards. For example, administrators frequently use BIND as:
- Caching DNS server in the local network
- Authoritative DNS server for zones
- Secondary server to provide high availability for zones
4.1. Considerations about protecting BIND with SELinux or running it in a change-root environment Link kopierenLink in die Zwischenablage kopiert!
To secure a BIND installation, you can:
Run the
namedservice without a change-root environment. In this case, SELinux inenforcingmode prevents exploitation of known BIND security vulnerabilities. By default, Red Hat Enterprise Linux uses SELinux inenforcingmode.ImportantRunning BIND on RHEL with SELinux in
enforcingmode is more secure than running BIND in a change-root environment.Run the
named-chrootservice in a change-root environment.Using the change-root feature, administrators can define that the root directory of a process and its sub-processes is different to the
/directory. When you start thenamed-chrootservice, BIND switches its root directory to/var/named/chroot/. As a consequence, the service usesmount --bindcommands to make the files and directories listed in/etc/named-chroot.filesavailable in/var/named/chroot/, and the process has no access to files outside of/var/named/chroot/.
If you decide to use BIND:
-
In normal mode, use the
namedservice. -
In a change-root environment, use the
named-chrootservice. This requires that you install, additionally, thenamed-chrootpackage.
4.2. The BIND Administrator Reference Manual Link kopierenLink in die Zwischenablage kopiert!
The comprehensive BIND Administrator Reference Manual, that is included in the bind package, provides:
- Configuration examples
- Documentation on advanced features
- A configuration reference
- Security considerations
To display the BIND Administrator Reference Manual on a host that has the bind package installed, open the /usr/share/doc/bind/Bv9ARM.html file in a browser.
4.3. Configuring BIND as a caching DNS server Link kopierenLink in die Zwischenablage kopiert!
By default, the BIND DNS server resolves and caches successful and failed lookups. The service then answers requests to the same records from its cache. This significantly improves the speed of DNS lookups.
Prerequisites
- The IP address of the server is static.
Procedure
Install the
bindandbind-utilspackages:yum install bind bind-utils
# yum install bind bind-utilsCopy to Clipboard Copied! Toggle word wrap Toggle overflow These packages provide BIND 9.11. If you require BIND 9.16, install the
bind9.16andbind9.16-utilspackages.If you want to run BIND in a change-root environment install the
bind-chrootpackage:yum install bind-chroot
# yum install bind-chrootCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that running BIND on a host with SELinux in
enforcingmode, which is default, is more secure.Edit the
/etc/named.conffile, and make the following changes in theoptionsstatement:Update the
listen-onandlisten-on-v6statements to specify on which IPv4 and IPv6 interfaces BIND should listen:listen-on port 53 { 127.0.0.1; 192.0.2.1; }; listen-on-v6 port 53 { ::1; 2001:db8:1::1; };listen-on port 53 { 127.0.0.1; 192.0.2.1; }; listen-on-v6 port 53 { ::1; 2001:db8:1::1; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Update the
allow-querystatement to configure from which IP addresses and ranges clients can query this DNS server:allow-query { localhost; 192.0.2.0/24; 2001:db8:1::/64; };allow-query { localhost; 192.0.2.0/24; 2001:db8:1::/64; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add an
allow-recursionstatement to define from which IP addresses and ranges BIND accepts recursive queries:allow-recursion { localhost; 192.0.2.0/24; 2001:db8:1::/64; };allow-recursion { localhost; 192.0.2.0/24; 2001:db8:1::/64; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow WarningDo not allow recursion on public IP addresses of the server. Otherwise, the server can become part of large-scale DNS amplification attacks.
By default, BIND resolves queries by recursively querying from the root servers to an authoritative DNS server. Alternatively, you can configure BIND to forward queries to other DNS servers, such as the ones of your provider. In this case, add a
forwardersstatement with the list of IP addresses of the DNS servers that BIND should forward queries to:forwarders { 198.51.100.1; 203.0.113.5; };forwarders { 198.51.100.1; 203.0.113.5; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow As a fall-back behavior, BIND resolves queries recursively if the forwarder servers do not respond. To disable this behavior, add a
forward only;statement.
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Update the
firewalldrules to allow incoming DNS traffic:firewall-cmd --permanent --add-service=dns firewall-cmd --reload
# firewall-cmd --permanent --add-service=dns # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start and enable BIND:
systemctl enable --now named
# systemctl enable --now namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you want to run BIND in a change-root environment, use the
systemctl enable --now named-chrootcommand to enable and start the service.
Verification
Use the newly set up DNS server to resolve a domain:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.After querying a record for the first time, BIND adds the entry to its cache.
Repeat the previous query:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Because of the cached entry, further requests for the same record are significantly faster until the entry expires.
4.4. Configuring logging on a BIND DNS server Link kopierenLink in die Zwischenablage kopiert!
The configuration in the default /etc/named.conf file, as provided by the bind package, uses the default_debug channel and logs messages to the /var/named/data/named.run file. The default_debug channel only logs entries when the server’s debug level is non-zero.
Using different channels and categories, you can configure BIND to write different events with a defined severity to separate files.
Prerequisites
- BIND is already configured, for example, as a caching name server.
-
The
namedornamed-chrootservice is running.
Procedure
Edit the
/etc/named.conffile, and addcategoryandchannelphrases to theloggingstatement, for example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this example configuration, BIND logs messages related to zone transfers to
/var/named/log/transfer.log. BIND creates up to10versions of the log file and rotates them if they reach a maximum size of50MB.The
categoryphrase defines to which channels BIND sends messages of a category.The
channelphrase defines the destination of log messages including the number of versions, the maximum file size, and the severity level BIND should log to a channel. Additional settings, such as enabling logging the time stamp, category, and severity of an event are optional, but useful for debugging purposes.Create the log directory if it does not exist, and grant write permissions to the
nameduser on this directory:mkdir /var/named/log/ chown named:named /var/named/log/ chmod 700 /var/named/log/
# mkdir /var/named/log/ # chown named:named /var/named/log/ # chmod 700 /var/named/log/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Restart BIND:
systemctl restart named
# systemctl restart namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl restart named-chrootcommand to restart the service.
Verification
Display the content of the log file:
cat /var/named/log/transfer.log ... 06-Jul-2022 15:08:51.261 xfer-out: info: client @0x7fecbc0b0700 192.0.2.2#36121/key example-transfer-key (example.com): transfer of 'example.com/IN': AXFR started: TSIG example-transfer-key (serial 2022070603) 06-Jul-2022 15:08:51.261 xfer-out: info: client @0x7fecbc0b0700 192.0.2.2#36121/key example-transfer-key (example.com): transfer of 'example.com/IN': AXFR ended
# cat /var/named/log/transfer.log ... 06-Jul-2022 15:08:51.261 xfer-out: info: client @0x7fecbc0b0700 192.0.2.2#36121/key example-transfer-key (example.com): transfer of 'example.com/IN': AXFR started: TSIG example-transfer-key (serial 2022070603) 06-Jul-2022 15:08:51.261 xfer-out: info: client @0x7fecbc0b0700 192.0.2.2#36121/key example-transfer-key (example.com): transfer of 'example.com/IN': AXFR endedCopy to Clipboard Copied! Toggle word wrap Toggle overflow
4.5. Writing BIND ACLs Link kopierenLink in die Zwischenablage kopiert!
Controlling access to certain features of BIND can prevent unauthorized access and attacks, such as denial of service (DoS). BIND access control list (acl) statements are lists of IP addresses and ranges. Each ACL has a nickname that you can use in several statements, such as allow-query, to refer to the specified IP addresses and ranges.
BIND uses only the first matching entry in an ACL. For example, if you define an ACL { 192.0.2/24; !192.0.2.1; } and the host with IP address 192.0.2.1 connects, access is granted even if the second entry excludes this address.
BIND has the following built-in ACLs:
-
none: Matches no hosts. -
any: Matches all hosts. -
localhost: Matches the loopback addresses127.0.0.1and::1, as well as the IP addresses of all interfaces on the server that runs BIND. -
localnets: Matches the loopback addresses127.0.0.1and::1, as well as all subnets the server that runs BIND is directly connected to.
Prerequisites
- BIND is already configured, for example, as a caching name server.
-
The
namedornamed-chrootservice is running.
Procedure
Edit the
/etc/named.conffile and make the following changes:Add
aclstatements to the file. For example, to create an ACL namedinternal-networksfor127.0.0.1,192.0.2.0/24, and2001:db8:1::/64, enter:acl internal-networks { 127.0.0.1; 192.0.2.0/24; 2001:db8:1::/64; }; acl dmz-networks { 198.51.100.0/24; 2001:db8:2::/64; };acl internal-networks { 127.0.0.1; 192.0.2.0/24; 2001:db8:1::/64; }; acl dmz-networks { 198.51.100.0/24; 2001:db8:2::/64; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Use the ACL’s nickname in statements that support them, for example:
allow-query { internal-networks; dmz-networks; }; allow-recursion { internal-networks; };allow-query { internal-networks; dmz-networks; }; allow-recursion { internal-networks; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
Verification
Execute an action that triggers a feature which uses the configured ACL. For example, the ACL in this procedure allows only recursive queries from the defined IP addresses. In this case, enter the following command on a host that is not within the ACL’s definition to attempt resolving an external domain:
dig +short @192.0.2.1 www.example.com
# dig +short @192.0.2.1 www.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command returns no output, BIND denied access, and the ACL works. For a verbose output on the client, use the command without
+shortoption:dig @192.0.2.1 www.example.com
# dig @192.0.2.1 www.example.com ... ;; WARNING: recursion requested but not available ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
4.6. Configuring zones on a BIND DNS server Link kopierenLink in die Zwischenablage kopiert!
A DNS zone is a database with resource records for a specific sub-tree in the domain space. For example, if you are responsible for the example.com domain, you can set up a zone for it in BIND. As a result, clients can, resolve www.example.com to the IP address configured in this zone.
4.6.1. The SOA record in zone files Link kopierenLink in die Zwischenablage kopiert!
The start of authority (SOA) record is a required record in a DNS zone. This record is important, for example, if multiple DNS servers are authoritative for a zone but also to DNS resolvers.
A SOA record in BIND has the following syntax:
name class type mname rname serial refresh retry expire minimum
name class type mname rname serial refresh retry expire minimum
For better readability, administrators typically split the record in zone files into multiple lines with comments that start with a semicolon (;). Note that, if you split a SOA record, parentheses keep the record together:
Note the trailing dot at the end of the fully-qualified domain names (FQDNs). FQDNs consist of multiple domain labels, separated by dots. Because the DNS root has an empty label, FQDNs end with a dot. Therefore, BIND appends the zone name to names without a trailing dot. A hostname without a trailing dot, for example, ns1.example.com would be expanded to ns1.example.com.example.com., which is not the correct address of the primary name server.
These are the fields in a SOA record:
-
name: The name of the zone, the so-calledorigin. If you set this field to@, BIND expands it to the zone name defined in/etc/named.conf. -
class: In SOA records, you must set this field always to Internet (IN). -
type: In SOA records, you must set this field always toSOA. -
mname(master name): The hostname of the primary name server of this zone. -
rname(responsible name): The email address of who is responsible for this zone. Note that the format is different. You must replace the at sign (@) with a dot (.). serial: The version number of this zone file. Secondary name servers only update their copies of the zone if the serial number on the primary server is higher.The format can be any numeric value. A commonly-used format is
<year><month><day><two-digit-number>. With this format, you can, theoretically, change the zone file up to a hundred times per day.-
refresh: The amount of time secondary servers should wait before checking the primary server if the zone was updated. -
retry: The amount of time after that a secondary server retries to query the primary server after a failed attempt. -
expire: The amount of time after that a secondary server stops querying the primary server, if all previous attempts failed. -
minimum: RFC 2308 changed the meaning of this field to the negative caching time. Compliant resolvers use it to determine how long to cacheNXDOMAINname errors.
A numeric value in the refresh, retry, expire, and minimum fields define a time in seconds. However, for better readability, use time suffixes, such as m for minute, h for hours, and d for days. For example, 3h stands for 3 hours.
4.6.2. Setting up a forward zone on a BIND primary server Link kopierenLink in die Zwischenablage kopiert!
Forward zones map names to IP addresses and other information. For example, if you are responsible for the domain example.com, you can set up a forward zone in BIND to resolve names, such as www.example.com.
Prerequisites
- BIND is already configured, for example, as a caching name server.
-
The
namedornamed-chrootservice is running.
Procedure
Add a zone definition to the
/etc/named.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings define:
-
This server as the primary server (
type master) for theexample.comzone. -
The
/var/named/example.com.zonefile is the zone file. If you set a relative path, as in this example, this path is relative to the directory you set indirectoryin theoptionsstatement. - Any host can query this zone. Alternatively, specify IP ranges or BIND access control list (ACL) nicknames to limit the access.
- No host can transfer the zone. Allow zone transfers only when you set up secondary servers and only for the IP addresses of the secondary servers.
-
This server as the primary server (
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Create the
/var/named/example.com.zonefile, for example, with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This zone file:
-
Sets the default time-to-live (TTL) value for resource records to 8 hours. Without a time suffix, such as
hfor hour, BIND interprets the value as seconds. - Contains the required SOA resource record with details about the zone.
-
Sets
ns1.example.comas an authoritative DNS server for this zone. To be functional, a zone requires at least one name server (NS) record. However, to be compliant with RFC 1912, you require at least two name servers. -
Sets
mail.example.comas the mail exchanger (MX) of theexample.comdomain. The numeric value in front of the host name is the priority of the record. Entries with a lower value have a higher priority. -
Sets the IPv4 and IPv6 addresses of
www.example.com,mail.example.com, andns1.example.com.
-
Sets the default time-to-live (TTL) value for resource records to 8 hours. Without a time suffix, such as
Set secure permissions on the zone file that allow only the
namedgroup to read it:chown root:named /var/named/example.com.zone chmod 640 /var/named/example.com.zone
# chown root:named /var/named/example.com.zone # chmod 640 /var/named/example.com.zoneCopy to Clipboard Copied! Toggle word wrap Toggle overflow Verify the syntax of the
/var/named/example.com.zonefile:named-checkzone example.com /var/named/example.com.zone
# named-checkzone example.com /var/named/example.com.zone zone example.com/IN: loaded serial 2022070601 OKCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
Verification
Query different records from the
example.comzone, and verify that the output matches the records you have configured in the zone file:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.
4.6.3. Setting up a reverse zone on a BIND primary server Link kopierenLink in die Zwischenablage kopiert!
Reverse zones map IP addresses to names. For example, if you are responsible for IP range 192.0.2.0/24, you can set up a reverse zone in BIND to resolve IP addresses from this range to hostnames.
If you create a reverse zone for whole classful networks, name the zone accordingly. For example, for the class C network 192.0.2.0/24, the name of the zone is 2.0.192.in-addr.arpa. If you want to create a reverse zone for a different network size, for example 192.0.2.0/28, the name of the zone is 28-2.0.192.in-addr.arpa.
Prerequisites
- BIND is already configured, for example, as a caching name server.
-
The
namedornamed-chrootservice is running.
Procedure
Add a zone definition to the
/etc/named.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings define:
-
This server as the primary server (
type master) for the2.0.192.in-addr.arpareverse zone. -
The
/var/named/2.0.192.in-addr.arpa.zonefile is the zone file. If you set a relative path, as in this example, this path is relative to the directory you set indirectoryin theoptionsstatement. - Any host can query this zone. Alternatively, specify IP ranges or BIND access control list (ACL) nicknames to limit the access.
- No host can transfer the zone. Allow zone transfers only when you set up secondary servers and only for the IP addresses of the secondary servers.
-
This server as the primary server (
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Create the
/var/named/2.0.192.in-addr.arpa.zonefile, for example, with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This zone file:
-
Sets the default time-to-live (TTL) value for resource records to 8 hours. Without a time suffix, such as
hfor hour, BIND interprets the value as seconds. - Contains the required SOA resource record with details about the zone.
-
Sets
ns1.example.comas an authoritative DNS server for this reverse zone. To be functional, a zone requires at least one name server (NS) record. However, to be compliant with RFC 1912, you require at least two name servers. -
Sets the pointer (
PTR) record for the192.0.2.1and192.0.2.30addresses.
-
Sets the default time-to-live (TTL) value for resource records to 8 hours. Without a time suffix, such as
Set secure permissions on the zone file that only allow the
namedgroup to read it:chown root:named /var/named/2.0.192.in-addr.arpa.zone chmod 640 /var/named/2.0.192.in-addr.arpa.zone
# chown root:named /var/named/2.0.192.in-addr.arpa.zone # chmod 640 /var/named/2.0.192.in-addr.arpa.zoneCopy to Clipboard Copied! Toggle word wrap Toggle overflow Verify the syntax of the
/var/named/2.0.192.in-addr.arpa.zonefile:named-checkzone 2.0.192.in-addr.arpa /var/named/2.0.192.in-addr.arpa.zone
# named-checkzone 2.0.192.in-addr.arpa /var/named/2.0.192.in-addr.arpa.zone zone 2.0.192.in-addr.arpa/IN: loaded serial 2022070601 OKCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
Verification
Query different records from the reverse zone, and verify that the output matches the records you have configured in the zone file:
dig +short @localhost -x 192.0.2.1 dig +short @localhost -x 192.0.2.30
# dig +short @localhost -x 192.0.2.1 ns1.example.com. # dig +short @localhost -x 192.0.2.30 www.example.com.Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.
4.6.4. Updating a BIND zone file Link kopierenLink in die Zwischenablage kopiert!
In certain situations, for example if an IP address of a server changes, you must update a zone file. If multiple DNS servers are responsible for a zone, perform this procedure only on the primary server. Other DNS servers that store a copy of the zone will receive the update through a zone transfer.
Prerequisites
- The zone is configured.
-
The
namedornamed-chrootservice is running.
Procedure
Optional: Identify the path to the zone file in the
/etc/named.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow You find the path to the zone file in the
filestatement in the zone’s definition. A relative path is relative to the directory set indirectoryin theoptionsstatement.Edit the zone file:
- Make the required changes.
Increment the serial number in the start of authority (SOA) record.
ImportantIf the serial number is equal to or lower than the previous value, secondary servers will not update their copy of the zone.
Verify the syntax of the zone file:
named-checkzone example.com /var/named/example.com.zone
# named-checkzone example.com /var/named/example.com.zone zone example.com/IN: loaded serial 2022062802 OKCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
Verification
Query the record you have added, modified, or removed, for example:
dig +short @localhost A ns2.example.com
# dig +short @localhost A ns2.example.com 192.0.2.2Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.
4.6.5. DNSSEC zone signing using the automated key generation and zone maintenance features Link kopierenLink in die Zwischenablage kopiert!
You can sign zones with domain name system security extensions (DNSSEC) to ensure authentication and data integrity. Such zones contain additional resource records. Clients can use them to verify the authenticity of the zone information.
If you enable the DNSSEC policy feature for a zone, BIND performs the following actions automatically:
- Creates the keys
- Signs the zone
- Maintains the zone, including re-signing and periodically replacing the keys.
To enable external DNS servers to verify the authenticity of a zone, you must add the public key of the zone to the parent zone. Contact your domain provider or registry for further details on how to accomplish this.
This procedure uses the built-in default DNSSEC policy in BIND. This policy uses single ECDSAP256SHA key signatures. Alternatively, create your own policy to use custom keys, algorithms, and timings.
Prerequisites
-
BIND 9.16 or later is installed. To meet this requirement, install the
bind9.16package instead ofbind. - The zone for which you want to enable DNSSEC is configured.
-
The
namedornamed-chrootservice is running. - The server synchronizes the time with a time server. An accurate system time is important for DNSSEC validation.
Procedure
Edit the
/etc/named.conffile, and adddnssec-policy default;to the zone for which you want to enable DNSSEC:zone "example.com" { ... dnssec-policy default; };zone "example.com" { ... dnssec-policy default; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.BIND stores the public key in the
/var/named/K<zone_name>.+<algorithm>+<key_ID>.keyfile. Use this file to display the public key of the zone in the format that the parent zone requires:DS record format:
dnssec-dsfromkey /var/named/Kexample.com.+013+61141.key
# dnssec-dsfromkey /var/named/Kexample.com.+013+61141.key example.com. IN DS 61141 13 2 3E184188CF6D2521EDFDC3F07CFEE8D0195AACBD85E68BAE0620F638B4B1B027Copy to Clipboard Copied! Toggle word wrap Toggle overflow DNSKEY format:
grep DNSKEY /var/named/Kexample.com.+013+61141.key
# grep DNSKEY /var/named/Kexample.com.+013+61141.key example.com. 3600 IN DNSKEY 257 3 13 sjzT3jNEp120aSO4mPEHHSkReHUf7AABNnT8hNRTzD5cKMQSjDJin2I3 5CaKVcWO1pm+HltxUEt+X9dfp8OZkg==Copy to Clipboard Copied! Toggle word wrap Toggle overflow
- Request to add the public key of the zone to the parent zone. Contact your domain provider or registry for further details on how to accomplish this.
Verification
Query your own DNS server for a record from the zone for which you enabled DNSSEC signing:
dig +dnssec +short @localhost A www.example.com
# dig +dnssec +short @localhost A www.example.com 192.0.2.30 A 13 3 28800 20220718081258 20220705120353 61141 example.com. e7Cfh6GuOBMAWsgsHSVTPh+JJSOI/Y6zctzIuqIU1JqEgOOAfL/Qz474 M0sgi54m1Kmnr2ANBKJN9uvOs5eXYw==Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.After the public key has been added to the parent zone and propagated to other servers, verify that the server sets the authenticated data (
ad) flag on queries to the signed zone:dig @localhost example.com +dnssec
# dig @localhost example.com +dnssec ... ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1 ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
4.7. Configuring zone transfers among BIND DNS servers Link kopierenLink in die Zwischenablage kopiert!
Zone transfers ensure that all DNS servers that have a copy of the zone use up-to-date data.
Prerequisites
- On the future primary server, the zone for which you want to set up zone transfers is already configured.
- On the future secondary server, BIND is already configured, for example, as a caching name server.
-
On both servers, the
namedornamed-chrootservice is running.
Procedure
On the existing primary server:
Create a shared key, and append it to the
/etc/named.conffile:tsig-keygen example-transfer-key | tee -a /etc/named.conf
# tsig-keygen example-transfer-key | tee -a /etc/named.conf key "example-transfer-key" { algorithm hmac-sha256; secret "q7ANbnyliDMuvWgnKOxMLi313JGcTZB5ydMW5CyUGXQ="; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow This command displays the output of the
tsig-keygencommand and automatically appends it to/etc/named.conf.You will require the output of the command later on the secondary server as well.
Edit the zone definition in the
/etc/named.conffile:In the
allow-transferstatement, define that servers must provide the key specified in theexample-transfer-keystatement to transfer a zone:zone "example.com" { ... allow-transfer { key example-transfer-key; }; };zone "example.com" { ... allow-transfer { key example-transfer-key; }; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Alternatively, use BIND access control list (ACL) nicknames in the
allow-transferstatement.By default, after a zone has been updated, BIND notifies all name servers which have a name server (
NS) record in this zone. If you do not plan to add anNSrecord for the secondary server to the zone, you can, configure that BIND notifies this server anyway. For that, add thealso-notifystatement with the IP addresses of this secondary server to the zone:zone "example.com" { ... also-notify { 192.0.2.2; 2001:db8:1::2; }; };zone "example.com" { ... also-notify { 192.0.2.2; 2001:db8:1::2; }; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
On the future secondary server:
Edit the
/etc/named.conffile as follows:Add the same key definition as on the primary server:
key "example-transfer-key" { algorithm hmac-sha256; secret "q7ANbnyliDMuvWgnKOxMLi313JGcTZB5ydMW5CyUGXQ="; };key "example-transfer-key" { algorithm hmac-sha256; secret "q7ANbnyliDMuvWgnKOxMLi313JGcTZB5ydMW5CyUGXQ="; };Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add the zone definition to the
/etc/named.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings state:
-
This server is a secondary server (
type slave) for theexample.comzone. -
The
/var/named/slaves/example.com.zonefile is the zone file. If you set a relative path, as in this example, this path is relative to the directory you set indirectoryin theoptionsstatement. To separate zone files for which this server is secondary from primary ones, you can store them, for example, in the/var/named/slaves/directory. - Any host can query this zone. Alternatively, specify IP ranges or ACL nicknames to limit the access.
- No host can transfer the zone from this server.
-
The IP addresses of the primary server of this zone are
192.0.2.1and2001:db8:1::2. Alternatively, you can specify ACL nicknames. This secondary server will use the key namedexample-transfer-keyto authenticate to the primary server.
-
This server is a secondary server (
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
-
Optional: Modify the zone file on the primary server and add an
NSrecord for the new secondary server.
Verification
On the secondary server:
Display the
systemdjournal entries of thenamedservice:Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
journalctl -u named-chrootcommand to display the journal entries.Verify that BIND created the zone file:
ls -l /var/named/slaves/
# ls -l /var/named/slaves/ total 4 -rw-r--r--. 1 named named 2736 Jul 6 15:08 example.com.zoneCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that, by default, secondary servers store zone files in a binary raw format.
Query a record of the transferred zone from the secondary server:
dig +short @192.0.2.2 AAAA www.example.com
# dig +short @192.0.2.2 AAAA www.example.com 2001:db8:1::30Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that the secondary server you set up in this procedure listens on IP address
192.0.2.2.
4.8. Configuring response policy zones in BIND to override DNS records Link kopierenLink in die Zwischenablage kopiert!
Using DNS blocking and filtering, administrators can rewrite a DNS response to block access to certain domains or hosts. In BIND, response policy zones (RPZs) provide this feature. You can configure different actions for blocked entries, such as returning an NXDOMAIN error or not responding to the query.
If you have multiple DNS servers in your environment, use this procedure to configure the RPZ on the primary server, and later configure zone transfers to make the RPZ available on your secondary servers.
Prerequisites
- BIND is already configured, for example, as a caching name server.
-
The
namedornamed-chrootservice is running.
Procedure
Edit the
/etc/named.conffile, and make the following changes:Add a
response-policydefinition to theoptionsstatement:Copy to Clipboard Copied! Toggle word wrap Toggle overflow You can set a custom name for the RPZ in the
zonestatement inresponse-policy. However, you must use the same name in the zone definition in the next step.Add a
zonedefinition for the RPZ you set in the previous step:Copy to Clipboard Copied! Toggle word wrap Toggle overflow These settings state:
-
This server is the primary server (
type master) for the RPZ namedrpz.local. -
The
/var/named/rpz.localfile is the zone file. If you set a relative path, as in this example, this path is relative to the directory you set indirectoryin theoptionsstatement. -
Any hosts defined in
allow-querycan query this RPZ. Alternatively, specify IP ranges or BIND access control list (ACL) nicknames to limit the access. - No host can transfer the zone. Allow zone transfers only when you set up secondary servers and only for the IP addresses of the secondary servers.
-
This server is the primary server (
Verify the syntax of the
/etc/named.conffile:named-checkconf
# named-checkconfCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the command displays no output, the syntax is correct.
Create the
/var/named/rpz.localfile, for example, with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow This zone file:
-
Sets the default time-to-live (TTL) value for resource records to 10 minutes. Without a time suffix, such as
hfor hour, BIND interprets the value as seconds. - Contains the required start of authority (SOA) resource record with details about the zone.
-
Sets
ns1.example.comas an authoritative DNS server for this zone. To be functional, a zone requires at least one name server (NS) record. However, to be compliant with RFC 1912, you require at least two name servers. -
Return an
NXDOMAINerror for queries toexample.organd hosts in this domain. -
Drop queries to
example.netand hosts in this domain.
For a full list of actions and examples, see IETF draft: DNS Response Policy Zones (RPZ).
-
Sets the default time-to-live (TTL) value for resource records to 10 minutes. Without a time suffix, such as
Verify the syntax of the
/var/named/rpz.localfile:named-checkzone rpz.local /var/named/rpz.local
# named-checkzone rpz.local /var/named/rpz.local zone rpz.local/IN: loaded serial 2022070601 OKCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload BIND:
systemctl reload named
# systemctl reload namedCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run BIND in a change-root environment, use the
systemctl reload named-chrootcommand to reload the service.
Verification
Attempt to resolve a host in
example.org, that is configured in the RPZ to return anNXDOMAINerror:dig @localhost www.example.org
# dig @localhost www.example.org ... ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 30286 ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow This example assumes that BIND runs on the same host and responds to queries on the
localhostinterface.Attempt to resolve a host in the
example.netdomain, that is configured in the RPZ to drop queries:dig @localhost www.example.net
# dig @localhost www.example.net ... ;; connection timed out; no servers could be reached ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
4.9. Bind Migration from RHEL 7 to RHEL 8 Link kopierenLink in die Zwischenablage kopiert!
To migrate the BIND from RHEL 7 to RHEL 8 you need to adjust the bind configuration in the following ways :
-
Remove the
dnssec-lookaside autoconfiguration option. -
BINDwill listen on any configured IPv6 addresses by default because the default value for thelisten-on-v6configuration option has been changed toanyfromnone. -
Multiple zones cannot share the same zone file when updates to its zone are allowed. If you need to use the same file in multiple zone definitions, ensure that allow-updates uses only
none. Do not use non-emptyupdate-policyor enableinline-signing, otherwise usein-viewclause to share the zone.
Updated command-line options, default behavior and output formats :
-
The number of UDP listeners employed per interface has been changed to be a function of the number of processors. You can override it by using the
-Uargument toBIND. -
The XML format used in the
statistics-channelhas been changed. -
The
rndc flushtreeoption now flushesDNSSECvalidation failures as well as specific name records. -
You must use the
/etc/named.root.keyfile instead of the/etc/named.iscdlv.keyfile. The/etc/named.iscdlv.keyfile is not available anymore. - The querylog format has been changed to include a memory address of the client object. It can be helpful in debugging.
-
The
namedanddigutility now send aDNS COOKIE(RFC 7873) by default, which might break on restrictive firewall or intrusion detection system. You can change this behaviour by using thesend-cookieconfiguration option. -
The
digutility can display theExtended DNS Errors(EDE, RFC 8914) in a text format.
4.10. Recording DNS queries by using dnstap Link kopierenLink in die Zwischenablage kopiert!
As a network administrator, you can record Domain Name System (DNS) details to analyze DNS traffic patterns, monitor DNS server performance, and troubleshoot DNS issues. If you want an advanced way to monitor and log details of incoming name queries, use the dnstap interface that records sent messages from the named service. You can capture and record DNS queries to collect information about websites or IP addresses.
Prerequisites
-
The
bind-9.11.26-2package or a later version is installed.
If you already have a BIND version installed and running, adding a new version of BIND will overwrite the existing version.
Procedure
Enable
dnstapand the target file by editing the/etc/named.conffile in theoptionsblock:Copy to Clipboard Copied! Toggle word wrap Toggle overflow To specify which types of DNS traffic you want to log, add
dnstapfilters to thednstapblock in the/etc/named.conffile. You can use the following filters:-
auth- Authoritative zone response or answer. -
client- Internal client query or answer. -
forwarder- Forwarded query or response from it. -
resolver- Iterative resolution query or response. -
update- Dynamic zone update requests. -
all- Any from the above options. queryorresponse- If you do not specify aqueryor aresponsekeyword,dnstaprecords both.NoteThe
dnstapfilter contains multiple definitions delimited by a;in thednstap {}block with the following syntax:dnstap { ( all | auth | client | forwarder | resolver | update ) [ ( query | response ) ]; … };
-
To apply your changes, restart the
namedservice:systemctl restart named.service
# systemctl restart named.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure a periodic rollout for active logs
In the following example, the
cronscheduler runs the content of the user-edited script once a day. Therolloption with the value3specifies thatdnstapcan create up to three backup log files. The value3overrides theversionparameter of thednstap-outputvariable, and limits the number of backup log files to three. Additionally, the binary log file is moved to another directory and renamed, and it never reaches the.2suffix, even if three backup log files already exist. You can skip this step if automatic rolling of binary logs based on size limit is sufficient.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Handle and analyze logs in a human-readable format by using the
dnstap-readutility:In the following example, the
dnstap-readutility prints the output in theYAMLfile format.Example: dnstap-read -p /var/named/data/dnstap.bin
Example: dnstap-read -p /var/named/data/dnstap.binCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Chapter 5. Deploying an NFS server Link kopierenLink in die Zwischenablage kopiert!
By using the Network File System (NFS) protocol, remote users can mount shared directories over a network and use them as they were mounted locally. This enables you to consolidate resources onto centralized servers on the network.
5.1. Key features of minor NFSv4 versions Link kopierenLink in die Zwischenablage kopiert!
Each minor NFSv4 version brings enhancements aimed at improving performance and security. Use these improvements to utilize the full potential of NFSv4, ensuring efficient and reliable file sharing across networks.
Key features of NFSv4.2
- Server-side copy
- Server-side copy is a capability of the NFS server to copy files on the server without transferring the data back and forth over the network.
- Sparse files
- Enables files to have one or more empty spaces, or gaps, which are unallocated or uninitialized data blocks consisting only of zeros. This enables applications to map out the location of holes in the sparse file.
- Space reservation
- Clients can reserve or allocate space on the storage server before writing data. This prevents the server from running out of space.
- Labeled NFS
- Enforces data access rights and enables SELinux labels between a client and a server for individual files on an NFS file system.
- Layout enhancements
- Provides functionality to enable Parallel NFS (pNFS) servers to collect better performance statistics.
Key features of NFSv4.1
- Client-side support for pNFS
- The support of high-speed I/O to clustered servers enables you to store data on multiple machines, to provide direct access to data, and synchronization of updates to metadata.
- Sessions
- Sessions maintain the server’s state relative to the connections belonging to a client. These sessions provide improved performance and efficiency by reducing the overhead associated with establishing and terminating connections for each Remote Procedure Call (RPC) operation.
Key features of NFSv4.0
- RPC and security
-
The
RPCSEC_GSSframework enhances RPC security. The NFSv4 protocol introduces a new operation for in-band security negotiation. This enables clients to query server policies for accessing file system resources securely. - Procedure and operation structure
-
NFS 4.0 introduces the
COMPOUNDprocedure, which enables clients to merge multiple operations into a single request to reduce RPCs. - File system model
NFS 4.0 retains the hierarchical file system model, treating files as byte streams and encoding names with UTF-8 for internationalization.
File handle types
With volatile file handles, servers can adjust to file system changes and enable clients to adapt as needed without requiring permanent file handles.
Attribute types
The file attribute structure includes required, recommended, and named attributes, each serving distinct purposes. Required attributes, derived from NFSv3, are essential for distinguishing file types, while recommended attributes, such as ACLs, provide enhanced access control.
Multi-server namespace
Namespaces span across multiple servers, simplify file system transfers based on attributes, support referrals, redundancy, and seamless server migration.
- OPEN and CLOSE operations
- These operations can combine file lookup, creation, and semantic sharing at a single point and make the file access management more efficient.
- File locking
- File locking is part of the protocol, eliminating the need for RPC callbacks. File lock state is managed by the server under a lease-based model, where failure to renew the lease may result in state release by the server.
- Client caching and delegation
- Caching resembles previous versions, with client-determined timeouts for attribute and directory caching. Delegations in NFS 4.0 allow the server to assign certain responsibilities to the client, guaranteeing specific file sharing semantics and enabling local file operations without immediate server interaction.
5.2. The AUTH_SYS authentication method Link kopierenLink in die Zwischenablage kopiert!
The AUTH_SYS method, which is also known as AUTH_UNIX, is a client authentication mechanism. With AUTH_SYS, the client sends the User ID (UID) and Group ID (GID) of the user to the server to verify its identity and permissions when accessing files. It is considered less secure as it relies on the client-provided information, making it susceptible to unauthorized access if misconfigured.
Mapping mechanisms ensure that NFS clients can access files with the appropriate permissions on the server, even if the UID and GID assignments differ between systems. UIDs and GIDs are mapped between NFS client and server by the following mechanisms:
- Direct mapping
UIDs and GIDs are directly mapped by NFS servers and clients between local and remote systems. This requires consistent UID and GID assignments across all systems participating in NFS file sharing. For example, a user with UID 1000 on a client can only access the files on a share that a user with UID 1000 on the server has access to.
For a simplified ID management in an NFS environment, administrators often rely on centralized services, such as LDAP or Network Information Service (NIS) to manage UID and GID mappings across multiple systems.
- User and Group ID mapping
-
NFS servers and clients can use the
idmapdservice to translate UIDs and GIDs between different systems for consistent identification and permission assignment.
5.3. The AUTH_GSS authentication method Link kopierenLink in die Zwischenablage kopiert!
Kerberos is a network authentication protocol that allows secure authentication for clients and servers over a non-secure network. It uses symmetric key cryptography and requires a trusted Key Distribution Center (KDC) to authenticate users and services.
Unlike AUTH_SYS, with the RPCSEC_GSS Kerberos mechanism, the server does not depend on the client to correctly represent which user is accessing the file. Instead, cryptography is used to authenticate users to the server, which prevents a malicious client from impersonating a user without having that user’s Kerberos credentials.
In the /etc/exports file, the sec option defines one or multiple methods of Kerberos security that the share should provide, and clients can mount the share with one of these methods. The sec option supports the following values:
-
sys: no cryptographic protection (default) -
krb5: authentication only -
krb5i: authentication and integrity protection -
krb5p: authentication, integrity checking, and traffic encryption
Note that the more cryptographic functionality a method provides, the lower is the performance.
5.4. File permissions on exported file systems Link kopierenLink in die Zwischenablage kopiert!
File permissions on exported file systems determine access rights to files and directories for clients accessing them over NFS.
Once the NFS file system is mounted by a remote host, the only protection each shared file has is its file system permissions. If two users that share the same User ID (UID) value mount the same NFS file system on different client systems, they can modify each other’s files.
NFS treats the root user on the client as equivalent to the root user on the server. However, by default, the NFS server maps root to the nobody account when accessing an NFS share. The root_squash option controls this behavior.
5.5. Services required on an NFS server Link kopierenLink in die Zwischenablage kopiert!
Red Hat Enterprise Linux (RHEL) uses a combination of a kernel module and user-space processes to provide NFS file shares:
| Service name | NFS versions | Description |
|---|---|---|
|
| 3, 4 | The NFS kernel module that services requests for shared NFS file systems. |
|
| 3 |
This process accepts port reservations from local remote procedure call (RPC) services, makes them available or advertised, allowing corresponding remote RPC services to access them. The |
|
| 3, 4 |
This service processes It checks that the requested NFS share is currently exported by the NFS server and that the client is allowed to access it. |
|
| 3, 4 | This process advertises explicit NFS versions and protocols the server defines. It works with the kernel to meet the dynamic demands of NFS clients, such as providing server threads each time an NFS client connects.
The |
|
| 3 | This kernel module implements the Network Lock Manager (NLM) protocol, which enables clients to lock files on the server. RHEL loads the module automatically when the NFS server runs. |
|
| 3, 4 | This service provides user quota information for remote users. |
|
| 4 | This process provides NFSv4 client and server upcalls, which map between NFSv4 names (strings in the form of `user@domain`) and local user and group IDs. |
|
| 3, 4 |
This service handles |
|
| 4 | This service provides a NFSv4 client tracking daemon that prevents the server from granting lock reclaims when other clients have taken conflicting locks during a network partition combined with a server reboot. |
|
| 3 | This service provides notification to other NFSv3 clients when the local host reboots, and to the kernel when a remote NFSv3 host reboots. |
5.6. The /etc/exports configuration file Link kopierenLink in die Zwischenablage kopiert!
The /etc/exports file controls which directories the server exports. Each line contains an export point, a whitespace-separated list of clients that are allowed to mount the directory, and options for each of the clients:
<directory> <host_or_network_1>(<options_1>) <host_or_network_n>(<options_n>)...
<directory> <host_or_network_1>(<options_1>) <host_or_network_n>(<options_n>)...
The following are the individual parts of an /etc/exports entry:
- <directory>
- The directory that is being exported.
- <host_or_network>
- The host or network to which the export is being shared. For example, you can specify a hostname, an IP address, or an IP network.
- <options>
- The options for the host or network.
Adding a space between a client and options, changes the behavior. For example, the following lines do not have the same meaning:
/projects client.example.com(rw) /projects client.example.com (rw)
/projects client.example.com(rw)
/projects client.example.com (rw)
In the first line, the server allows only client.example.com to mount the /projects directory in read-write mode, and no other hosts can mount the share. However, due to the space between client.example.com and (rw) in the second line, the server exports the directory to client.example.com in read-only mode (default setting), but all other hosts can mount the share in read-write mode.
The NFS server uses the following default settings for each exported directory:
| Default setting | Description |
|---|---|
|
| Exports the directory in read-only mode. |
|
| The NFS server does not reply to requests before changes made by previous requests are written to disk. |
|
| The server delays writing to the disk if it suspects another write request is pending.. |
|
|
Prevents that the |
5.7. Configuring an NFSv4-only server Link kopierenLink in die Zwischenablage kopiert!
If you do not have any NFSv3 clients in your network, you can configure the NFS server to support only NFSv4 or specific minor protocol versions of it. Using only NFSv4 on the server reduces the number of ports that are open to the network.
Procedure
Install the
nfs-utilspackage:dnf install nfs-utils
# dnf install nfs-utilsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/nfs.conffile, and make the following changes:Disable the
vers3parameter in the[nfsd]section to disable NFSv3:[nfsd] vers3=n
[nfsd] vers3=nCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: If you require only specific NFSv4 minor versions, uncomment all
vers4.<minor_version>parameters and set them accordingly, for example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this configuration, the server provides only NFS version 4.2.
ImportantIf you require only a specific NFSv4 minor version, set only the parameters for the minor versions. Do not uncomment the
vers4parameter to avoid an unpredictable activation or deactivation of minor versions. By default, thevers4parameter enables or disables all NFSv4 minor versions. However, this behavior changes if you setvers4in conjunction with otherversparameters.
Disable all NFSv3-related services:
systemctl mask --now rpc-statd.service rpcbind.service rpcbind.socket
# systemctl mask --now rpc-statd.service rpcbind.service rpcbind.socketCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the
rpc.mountddaemon to not listen for NFSv3 mount requests. Create a/etc/systemd/system/nfs-mountd.service.d/v4only.conffile with the following content:[Service] ExecStart= ExecStart=/usr/sbin/rpc.mountd --no-tcp --no-udp
[Service] ExecStart= ExecStart=/usr/sbin/rpc.mountd --no-tcp --no-udpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the
systemdmanager configuration and restart thenfs-mountdservice:systemctl daemon-reload systemctl restart nfs-mountd
# systemctl daemon-reload # systemctl restart nfs-mountdCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Create a directory that you want to share, for example:
mkdir -p /nfs/projects/
# mkdir -p /nfs/projects/Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you want to share an existing directory, skip this step.
Set the permissions you require on the
/nfs/projects/directory:chmod 2770 /nfs/projects/ chgrp users /nfs/projects/
# chmod 2770 /nfs/projects/ # chgrp users /nfs/projects/Copy to Clipboard Copied! Toggle word wrap Toggle overflow These commands set write permissions for the
usersgroup on the/nfs/projects/directory and ensure that the same group is automatically set on new entries created in this directory.Add an export point to the
/etc/exportsfile for each directory that you want to share:/nfs/projects/ 192.0.2.0/24(rw) 2001:db8::/32(rw)
/nfs/projects/ 192.0.2.0/24(rw) 2001:db8::/32(rw)Copy to Clipboard Copied! Toggle word wrap Toggle overflow This entry shares the
/nfs/projects/directory to be accessible with read and write access to clients in the192.0.2.0/24and2001:db8::/32subnets.Open the relevant ports in
firewalld:firewall-cmd --permanent --add-service nfs firewall-cmd --reload
# firewall-cmd --permanent --add-service nfs # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the NFS server:
systemctl enable --now nfs-server
# systemctl enable --now nfs-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
On the server, verify that the server provides only the NFS versions that you have configured:
cat /proc/fs/nfsd/versions -3 +4 -4.0 -4.1 +4.2
# cat /proc/fs/nfsd/versions -3 +4 -4.0 -4.1 +4.2Copy to Clipboard Copied! Toggle word wrap Toggle overflow On a client, perform the following steps:
Install the
nfs-utilspackage:dnf install nfs-utils
# dnf install nfs-utilsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Mount an exported NFS share:
mount server.example.com:/nfs/projects/ /mnt/
# mount server.example.com:/nfs/projects/ /mnt/Copy to Clipboard Copied! Toggle word wrap Toggle overflow As a user which is a member of the
usersgroup, create a file in/mnt/:touch /mnt/file
# touch /mnt/fileCopy to Clipboard Copied! Toggle word wrap Toggle overflow List the directory to verify that the file was created:
ls -l /mnt/
# ls -l /mnt/ total 0 -rw-r--r--. 1 demo users 0 Jan 16 14:18 fileCopy to Clipboard Copied! Toggle word wrap Toggle overflow
5.8. Configuring an NFSv3 server with optional NFSv4 support Link kopierenLink in die Zwischenablage kopiert!
In a network which still uses NFSv3 clients, configure the server to provide shares by using the NFSv3 protocol. If you also have newer clients in your network, you can, additionally, enable NFSv4. By default, Red Hat Enterprise Linux NFS clients use the latest NFS version that the server provides.
Procedure
Install the
nfs-utilspackage:dnf install nfs-utils
# dnf install nfs-utilsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: By default, NFSv3 and NFSv4 are enabled. If you do not require NFSv4 or only specific minor versions, uncomment all
vers4.<minor_version>parameters and set them accordingly:Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this configuration, the server provides only the NFS version 3 and 4.2.
ImportantIf you require only a specific NFSv4 minor version, set only the parameters for the minor versions. Do not uncomment the
vers4parameter to avoid an unpredictable activation or deactivation of minor versions. By default, thevers4parameter enables or disables all NFSv4 minor versions. However, this behavior changes if you setvers4in conjunction with otherversparameters.By default, NFSv3 RPC services use random ports. To enable a firewall configuration, configure fixed port numbers in the
/etc/nfs.conffile:In the
[lockd]section, set a fixed port number for thenlockmgrRPC service, for example:[lockd] port=5555
[lockd] port=5555Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting, the service automatically uses this port number for both the UDP and TCP protocol.
In the
[statd]section, set a fixed port number for therpc.statdservice, for example:[statd] port=6666
[statd] port=6666Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting, the service automatically uses this port number for both the UDP and TCP protocol.
Optional: Create a directory that you want to share, for example:
mkdir -p /nfs/projects/
# mkdir -p /nfs/projects/Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you want to share an existing directory, skip this step.
Set the permissions you require on the
/nfs/projects/directory:chmod 2770 /nfs/projects/ chgrp users /nfs/projects/
# chmod 2770 /nfs/projects/ # chgrp users /nfs/projects/Copy to Clipboard Copied! Toggle word wrap Toggle overflow These commands set write permissions for the
usersgroup on the/nfs/projects/directory and ensure that the same group is automatically set on new entries created in this directory.Add an export point to the
/etc/exportsfile for each directory that you want to share:/nfs/projects/ 192.0.2.0/24(rw) 2001:db8::/32(rw)
/nfs/projects/ 192.0.2.0/24(rw) 2001:db8::/32(rw)Copy to Clipboard Copied! Toggle word wrap Toggle overflow This entry shares the
/nfs/projects/directory to be accessible with read and write access to clients in the192.0.2.0/24and2001:db8::/32subnets.Open the relevant ports in
firewalld:firewall-cmd --permanent --add-service={nfs,rpc-bind,mountd} firewall-cmd --permanent --add-port={5555/tcp,5555/udp,6666/tcp,6666/udp} firewall-cmd --reload# firewall-cmd --permanent --add-service={nfs,rpc-bind,mountd} # firewall-cmd --permanent --add-port={5555/tcp,5555/udp,6666/tcp,6666/udp} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the NFS server:
systemctl enable --now rpc-statd nfs-server
# systemctl enable --now rpc-statd nfs-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
On the server, verify that the server provides only the NFS versions that you have configured:
cat /proc/fs/nfsd/versions +3 +4 -4.0 -4.1 +4.2
# cat /proc/fs/nfsd/versions +3 +4 -4.0 -4.1 +4.2Copy to Clipboard Copied! Toggle word wrap Toggle overflow On a client, perform the following steps:
Install the
nfs-utilspackage:dnf install nfs-utils
# dnf install nfs-utilsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Mount an exported NFS share:
mount -o vers=<version> server.example.com:/nfs/projects/ /mnt/
# mount -o vers=<version> server.example.com:/nfs/projects/ /mnt/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that the share was mounted with the specified NFS version:
mount | grep "/mnt"
# mount | grep "/mnt" server.example.com:/nfs/projects/ on /mnt type nfs (rw,relatime,vers=3,...Copy to Clipboard Copied! Toggle word wrap Toggle overflow As a user which is a member of the
usersgroup, create a file in/mnt/:touch /mnt/file
# touch /mnt/fileCopy to Clipboard Copied! Toggle word wrap Toggle overflow List the directory to verify that the file was created:
ls -l /mnt/
# ls -l /mnt/ total 0 -rw-r--r--. 1 demo users 0 Jan 16 14:18 fileCopy to Clipboard Copied! Toggle word wrap Toggle overflow
5.9. Enabling quota support on an NFS server Link kopierenLink in die Zwischenablage kopiert!
If you want to restrict the amount of data a user or a group can store, you can configure quotas on the file system. On an NFS server, the rpc-rquotad service ensures that the quota is also applied to users on NFS clients.
Prerequisites
Procedure
Verify that quotas are enabled on the directories that you export:
For ext file system, enter:
quotaon -p /nfs/projects/
# quotaon -p /nfs/projects/ group quota on /nfs/projects (/dev/sdb1) is on user quota on /nfs/projects (/dev/sdb1) is on project quota on /nfs/projects (/dev/sdb1) is offCopy to Clipboard Copied! Toggle word wrap Toggle overflow For an XFS file system, enter:
findmnt /nfs/projects
# findmnt /nfs/projects TARGET SOURCE FSTYPE OPTIONS /nfs/projects /dev/sdb1 xfs rw,relatime,seclabel,attr2,inode64,logbufs=8,logbsize=32k,usrquota,grpquotaCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Install the
quota-rpcpackage:dnf install quota-rpc
# dnf install quota-rpcCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: By default, the quota RPC service runs on port 875. If you want to run the service on a different port, append
-p <port_number>to theRPCRQUOTADOPTSvariable in the/etc/sysconfig/rpc-rquotadfile:RPCRQUOTADOPTS="-p __<port_number>__"
RPCRQUOTADOPTS="-p __<port_number>__"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: By default, remote hosts can only read quotas. To allow clients to set quotas, append the
-Soption to theRPCRQUOTADOPTSvariable in the/etc/sysconfig/rpc-rquotadfile:RPCRQUOTADOPTS="-S"
RPCRQUOTADOPTS="-S"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Open the port in
firewalld:firewall-cmd --permanent --add-port=875/udp firewall-cmd --reload
# firewall-cmd --permanent --add-port=875/udp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
rpc-rquotadservice:systemctl enable --now rpc-rquotad
# systemctl enable --now rpc-rquotadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
On the client:
Mount the exported share:
mount server.example.com:/nfs/projects/ /mnt/
# mount server.example.com:/nfs/projects/ /mnt/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Display the quota. The command depends on the file system of the exported directory. For example:
To display the quota of a specific user on all mounted ext file systems, enter:
quota -u <user_name>
# quota -u <user_name> Disk quotas for user demo (uid 1000): Filesystem space quota limit grace files quota limit grace server.example.com:/nfs/projects 0K 100M 200M 0 0 0Copy to Clipboard Copied! Toggle word wrap Toggle overflow To display the user and group quota on an XFS file system, enter:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
5.10. Enabling NFS over RDMA on an NFS server Link kopierenLink in die Zwischenablage kopiert!
If both the NFS server and clients are connected over RDMA, clients can use NFS over Remote Direct Memory Access (NFSoRDMA) to mount an exported directory.
RDMA is a protocol that enables a client system to directly transfer data from the memory of a storage server into its own memory. This enhances storage throughput, decreases latency in data transfer between the server and client, and reduces CPU load on both ends.
Prerequisites
- The NFS service is running and configured
- An InfiniBand or RDMA over Converged Ethernet (RoCE) device is installed on the server.
- IP over InfiniBand (IPoIB) is configured on the server, and the InfiniBand device has an IP address assigned.
Procedure
Install the
rdma-corepackage:dnf install rdma-core
# dnf install rdma-coreCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the package was already installed, verify that the
xprtrdmaandsvcrdmamodules in the/etc/rdma/modules/rdma.conffile are uncommented:NFS over RDMA client support NFS over RDMA server support
# NFS over RDMA client support xprtrdma # NFS over RDMA server support svcrdmaCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: By default, NFS over RDMA uses port 20049. If you want to use a different port, set the
rdma-portsetting in the[nfsd]section of the/etc/nfs.conffile:rdma-port=<port>
rdma-port=<port>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Open the NFSoRDMA port in
firewalld:firewall-cmd --permanent --add-port={20049/tcp,20049/udp} firewall-cmd --reload# firewall-cmd --permanent --add-port={20049/tcp,20049/udp} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Adjust the port numbers if you set a different port than 20049.
Restart the
nfs-serverservice:systemctl restart nfs-server
# systemctl restart nfs-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
On a client with InfiniBand hardware, perform the following steps:
Install the following packages:
dnf install nfs-utils rdma-core
# dnf install nfs-utils rdma-coreCopy to Clipboard Copied! Toggle word wrap Toggle overflow Mount an exported NFS share over RDMA:
mount -o rdma server.example.com:/nfs/projects/ /mnt/
# mount -o rdma server.example.com:/nfs/projects/ /mnt/Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you set a port number other than the default (20049), pass
port=<port_number>to the command:mount -o rdma,port=<port_number> server.example.com:/nfs/projects/ /mnt/
# mount -o rdma,port=<port_number> server.example.com:/nfs/projects/ /mnt/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that the share was mounted with the
rdmaoption:mount | grep "/mnt"
# mount | grep "/mnt" server.example.com:/nfs/projects/ on /mnt type nfs (...,proto=rdma,...)Copy to Clipboard Copied! Toggle word wrap Toggle overflow
5.11. Setting up an NFS server with Kerberos in a Red Hat Enterprise Linux Identity Management domain Link kopierenLink in die Zwischenablage kopiert!
If you use Red Hat Enterprise Linux Identity Management (IdM), you can join your NFS server to the IdM domain. This enables you to centrally manage users and groups and to use Kerberos for authentication, integrity protection, and traffic encryption.
Prerequisites
- The NFS server is enrolled in a Red Hat Enterprise Linux Identity Management (IdM) domain.
- The NFS server is running and configured.
Procedure
Obtain a kerberos ticket as an IdM administrator:
kinit admin
# kinit adminCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create a
nfs/<FQDN>service principal:ipa service-add nfs/nfs_server.idm.example.com
# ipa service-add nfs/nfs_server.idm.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Retrieve the
nfsservice principal from IdM, and store it in the/etc/krb5.keytabfile:ipa-getkeytab -s idm_server.idm.example.com -p nfs/nfs_server.idm.example.com -k /etc/krb5.keytab
# ipa-getkeytab -s idm_server.idm.example.com -p nfs/nfs_server.idm.example.com -k /etc/krb5.keytabCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the principals in the
/etc/krb5.keytabfile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the IdM client adds the host principal to the
/etc/krb5.keytabfile when you join the host to the IdM domain. If the host principal is missing, use theipa-getkeytab -s idm_server.idm.example.com -p host/nfs_server.idm.example.com -k /etc/krb5.keytabcommand to add it.Use the
ipa-client-automountutility to configure mapping of IdM IDs:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Update your
/etc/exportsfile, and add the Kerberos security method to the client options. For example:/nfs/projects/ 192.0.2.0/24(rw,sec=krb5i)
/nfs/projects/ 192.0.2.0/24(rw,sec=krb5i)Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you want that your clients can select from multiple security methods, specify them separated by colons:
/nfs/projects/ 192.0.2.0/24(rw,sec=krb5:krb5i:krb5p)
/nfs/projects/ 192.0.2.0/24(rw,sec=krb5:krb5i:krb5p)Copy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the exported file systems:
exportfs -r
# exportfs -rCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Chapter 6. Configuring the Squid caching proxy server Link kopierenLink in die Zwischenablage kopiert!
Squid is a proxy server that caches content to reduce bandwidth and load web pages more quickly. This chapter describes how to set up Squid as a proxy for the HTTP, HTTPS, and FTP protocol, as well as authentication and restricting access.
6.1. Setting up Squid as a caching proxy without authentication Link kopierenLink in die Zwischenablage kopiert!
You can configure Squid as a caching proxy without authentication. The procedure limits access to the proxy based on IP ranges.
Prerequisites
-
The procedure assumes that the
/etc/squid/squid.conffile is as provided by thesquidpackage. If you edited this file before, remove the file and reinstall the package.
Procedure
Install the
squidpackage:yum install squid
# yum install squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/squid/squid.conffile:Adapt the
localnetaccess control lists (ACL) to match the IP ranges that should be allowed to use the proxy:acl localnet src 192.0.2.0/24 acl localnet 2001:db8:1::/64
acl localnet src 192.0.2.0/24 acl localnet 2001:db8:1::/64Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the
/etc/squid/squid.conffile contains thehttp_access allow localnetrule that allows using the proxy from all IP ranges specified inlocalnetACLs. Note that you must specify alllocalnetACLs before thehttp_access allow localnetrule.ImportantRemove all existing
acl localnetentries that do not match your environment.The following ACL exists in the default configuration and defines
443as a port that uses the HTTPS protocol:acl SSL_ports port 443
acl SSL_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow If users should be able to use the HTTPS protocol also on other ports, add an ACL for each of these port:
acl SSL_ports port port_number
acl SSL_ports port port_numberCopy to Clipboard Copied! Toggle word wrap Toggle overflow Update the list of
acl Safe_portsrules to configure to which ports Squid can establish a connection. For example, to configure that clients using the proxy can only access resources on port 21 (FTP), 80 (HTTP), and 443 (HTTPS), keep only the followingacl Safe_portsstatements in the configuration:acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443
acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the configuration contains the
http_access deny !Safe_portsrule that defines access denial to ports that are not defined inSafe_portsACLs.Configure the cache type, the path to the cache directory, the cache size, and further cache type-specific settings in the
cache_dirparameter:cache_dir ufs /var/spool/squid 10000 16 256
cache_dir ufs /var/spool/squid 10000 16 256Copy to Clipboard Copied! Toggle word wrap Toggle overflow With these settings:
-
Squid uses the
ufscache type. -
Squid stores its cache in the
/var/spool/squid/directory. -
The cache grows up to
10000MB. -
Squid creates
16level-1 sub-directories in the/var/spool/squid/directory. Squid creates
256sub-directories in each level-1 directory.If you do not set a
cache_dirdirective, Squid stores the cache in memory.
-
Squid uses the
If you set a different cache directory than
/var/spool/squid/in thecache_dirparameter:Create the cache directory:
mkdir -p path_to_cache_directory
# mkdir -p path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the permissions for the cache directory:
chown squid:squid path_to_cache_directory
# chown squid:squid path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run SELinux in
enforcingmode, set thesquid_cache_tcontext for the cache directory:semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" restorecon -Rv path_to_cache_directory
# semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" # restorecon -Rv path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
semanageutility is not available on your system, install thepolicycoreutils-python-utilspackage.
Open the
3128port in the firewall:firewall-cmd --permanent --add-port=3128/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=3128/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
squidservice:systemctl enable --now squid
# systemctl enable --now squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To verify that the proxy works correctly, download a web page using the curl utility:
curl -O -L "https://www.redhat.com/index.html" -x "proxy.example.com:3128"
# curl -O -L "https://www.redhat.com/index.html" -x "proxy.example.com:3128"
If curl does not display any error and the index.html file was downloaded to the current directory, the proxy works.
6.2. Setting up Squid as a caching proxy with LDAP authentication Link kopierenLink in die Zwischenablage kopiert!
You can configure Squid as a caching proxy that uses LDAP to authenticate users. The procedure configures that only authenticated users can use the proxy.
Prerequisites
-
The procedure assumes that the
/etc/squid/squid.conffile is as provided by thesquidpackage. If you edited this file before, remove the file and reinstall the package. -
An service user, such as
uid=proxy_user,cn=users,cn=accounts,dc=example,dc=comexists in the LDAP directory. Squid uses this account only to search for the authenticating user. If the authenticating user exists, Squid binds as this user to the directory to verify the authentication.
Procedure
Install the
squidpackage:yum install squid
# yum install squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/squid/squid.conffile:To configure the
basic_ldap_authhelper utility, add the following configuration entry to the top of/etc/squid/squid.conf:auth_param basic program /usr/lib64/squid/basic_ldap_auth -b "cn=users,cn=accounts,dc=example,dc=com" -D "uid=proxy_user,cn=users,cn=accounts,dc=example,dc=com" -W /etc/squid/ldap_password -f "(&(objectClass=person)(uid=%s))" -ZZ -H ldap://ldap_server.example.com:389
auth_param basic program /usr/lib64/squid/basic_ldap_auth -b "cn=users,cn=accounts,dc=example,dc=com" -D "uid=proxy_user,cn=users,cn=accounts,dc=example,dc=com" -W /etc/squid/ldap_password -f "(&(objectClass=person)(uid=%s))" -ZZ -H ldap://ldap_server.example.com:389Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following describes the parameters passed to the
basic_ldap_authhelper utility in the example above:-
-b base_DNsets the LDAP search base. -
-D proxy_service_user_DNsets the distinguished name (DN) of the account Squid uses to search for the authenticating user in the directory. -
-W path_to_password_filesets the path to the file that contains the password of the proxy service user. Using a password file prevents that the password is visible in the operating system’s process list. -f LDAP_filterspecifies the LDAP search filter. Squid replaces the%svariable with the user name provided by the authenticating user.The
(&(objectClass=person)(uid=%s))filter in the example defines that the user name must match the value set in theuidattribute and that the directory entry contains thepersonobject class.-ZZenforces a TLS-encrypted connection over the LDAP protocol using theSTARTTLScommand. Omit the-ZZin the following situations:- The LDAP server does not support encrypted connections.
- The port specified in the URL uses the LDAPS protocol.
- The -H LDAP_URL parameter specifies the protocol, the host name or IP address, and the port of the LDAP server in URL format.
-
Add the following ACL and rule to configure that Squid allows only authenticated users to use the proxy:
acl ldap-auth proxy_auth REQUIRED http_access allow ldap-auth
acl ldap-auth proxy_auth REQUIRED http_access allow ldap-authCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantSpecify these settings before the
http_access denyall rule.Remove the following rule to disable bypassing the proxy authentication from IP ranges specified in
localnetACLs:http_access allow localnet
http_access allow localnetCopy to Clipboard Copied! Toggle word wrap Toggle overflow The following ACL exists in the default configuration and defines
443as a port that uses the HTTPS protocol:acl SSL_ports port 443
acl SSL_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow If users should be able to use the HTTPS protocol also on other ports, add an ACL for each of these port:
acl SSL_ports port port_number
acl SSL_ports port port_numberCopy to Clipboard Copied! Toggle word wrap Toggle overflow Update the list of
acl Safe_portsrules to configure to which ports Squid can establish a connection. For example, to configure that clients using the proxy can only access resources on port 21 (FTP), 80 (HTTP), and 443 (HTTPS), keep only the followingacl Safe_portsstatements in the configuration:acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443
acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the configuration contains the
http_access deny !Safe_portsrule that defines access denial to ports that are not defined inSafe_ports ACLs.Configure the cache type, the path to the cache directory, the cache size, and further cache type-specific settings in the
cache_dirparameter:cache_dir ufs /var/spool/squid 10000 16 256
cache_dir ufs /var/spool/squid 10000 16 256Copy to Clipboard Copied! Toggle word wrap Toggle overflow With these settings:
-
Squid uses the
ufscache type. -
Squid stores its cache in the
/var/spool/squid/directory. -
The cache grows up to
10000MB. -
Squid creates
16level-1 sub-directories in the/var/spool/squid/directory. Squid creates
256sub-directories in each level-1 directory.If you do not set a
cache_dirdirective, Squid stores the cache in memory.
-
Squid uses the
If you set a different cache directory than
/var/spool/squid/in thecache_dirparameter:Create the cache directory:
mkdir -p path_to_cache_directory
# mkdir -p path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the permissions for the cache directory:
chown squid:squid path_to_cache_directory
# chown squid:squid path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run SELinux in
enforcingmode, set thesquid_cache_tcontext for the cache directory:semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" restorecon -Rv path_to_cache_directory
# semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" # restorecon -Rv path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
semanageutility is not available on your system, install thepolicycoreutils-python-utilspackage.
Store the password of the LDAP service user in the
/etc/squid/ldap_passwordfile, and set appropriate permissions for the file:echo "password" > /etc/squid/ldap_password chown root:squid /etc/squid/ldap_password chmod 640 /etc/squid/ldap_password
# echo "password" > /etc/squid/ldap_password # chown root:squid /etc/squid/ldap_password # chmod 640 /etc/squid/ldap_passwordCopy to Clipboard Copied! Toggle word wrap Toggle overflow Open the
3128port in the firewall:firewall-cmd --permanent --add-port=3128/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=3128/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
squidservice:systemctl enable --now squid
# systemctl enable --now squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To verify that the proxy works correctly, download a web page using the curl utility:
curl -O -L "https://www.redhat.com/index.html" -x "user_name:password@proxy.example.com:3128"
# curl -O -L "https://www.redhat.com/index.html" -x "user_name:password@proxy.example.com:3128"
If curl does not display any error and the index.html file was downloaded to the current directory, the proxy works.
Troubleshooting steps
To verify that the helper utility works correctly:
Manually start the helper utility with the same settings you used in the
auth_paramparameter:/usr/lib64/squid/basic_ldap_auth -b "cn=users,cn=accounts,dc=example,dc=com" -D "uid=proxy_user,cn=users,cn=accounts,dc=example,dc=com" -W /etc/squid/ldap_password -f "(&(objectClass=person)(uid=%s))" -ZZ -H ldap://ldap_server.example.com:389
# /usr/lib64/squid/basic_ldap_auth -b "cn=users,cn=accounts,dc=example,dc=com" -D "uid=proxy_user,cn=users,cn=accounts,dc=example,dc=com" -W /etc/squid/ldap_password -f "(&(objectClass=person)(uid=%s))" -ZZ -H ldap://ldap_server.example.com:389Copy to Clipboard Copied! Toggle word wrap Toggle overflow Enter a valid user name and password, and press Enter:
user_name password
user_name passwordCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the helper utility returns
OK, authentication succeeded.
6.3. Setting up Squid as a caching proxy with kerberos authentication Link kopierenLink in die Zwischenablage kopiert!
You can configure Squid as a caching proxy that authenticates users to an Active Directory (AD) using Kerberos. The procedure configures that only authenticated users can use the proxy.
Prerequisites
-
The procedure assumes that the
/etc/squid/squid.conffile is as provided by thesquidpackage. If you edited this file before, remove the file and reinstall the package.
Procedure
Install the following packages:
yum install squid krb5-workstation
# yum install squid krb5-workstationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Authenticate as the AD domain administrator:
kinit administrator@AD.EXAMPLE.COM
# kinit administrator@AD.EXAMPLE.COMCopy to Clipboard Copied! Toggle word wrap Toggle overflow Create a keytab for Squid, store it in the
/etc/squid/HTTP.keytabfile and add theHTTPservice principal to the keytab:export KRB5_KTNAME=FILE:/etc/squid/HTTP.keytab net ads keytab CREATE -U administrator net ads keytab ADD HTTP -U administrator
# export KRB5_KTNAME=FILE:/etc/squid/HTTP.keytab # net ads keytab CREATE -U administrator # net ads keytab ADD HTTP -U administratorCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: If system is initially joined to the AD domain with realm (via
adcli), use following instructions to addHTTPprincipal and create a keytab file for squid:Add the
HTTPservice principal to the default keytab file/etc/krb5.keytaband verify:adcli update -vvv --domain=ad.example.com --computer-name=PROXY --add-service-principal="HTTP/proxy.ad.example.com" -C klist -kte /etc/krb5.keytab | grep -i HTTP
# adcli update -vvv --domain=ad.example.com --computer-name=PROXY --add-service-principal="HTTP/proxy.ad.example.com" -C # klist -kte /etc/krb5.keytab | grep -i HTTPCopy to Clipboard Copied! Toggle word wrap Toggle overflow Load the
/etc/krb5.keytabfile, remove all service principals exceptHTTP, and save the remaining principals into the/etc/squid/HTTP.keytabfile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow In the interactive shell of
ktutil, you can use the different options, until all unwanted principals are removed from keytab, for example:ktutil: delent 1
ktutil: delent 1Copy to Clipboard Copied! Toggle word wrap Toggle overflow Copy to Clipboard Copied! Toggle word wrap Toggle overflow WarningThe keys in
/etc/krb5.keytabmight get updated if SSSD or Samba/winbind will update the machine account password. After the update, the key in/etc/squid/HTTP.keytabwill stop working, and you will need to perform thektutilsteps again to copy the new keys into the keytab.
Set the owner of the keytab file to the
squiduser:chown squid /etc/squid/HTTP.keytab
# chown squid /etc/squid/HTTP.keytabCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Verify that the keytab file contains the
HTTPservice principal for the fully-qualified domain name (FQDN) of the proxy server:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/etc/squid/squid.conffile:To configure the
negotiate_kerberos_authhelper utility, add the following configuration entry to the top of/etc/squid/squid.conf:auth_param negotiate program /usr/lib64/squid/negotiate_kerberos_auth -k /etc/squid/HTTP.keytab -s HTTP/proxy.ad.example.com@AD.EXAMPLE.COM
auth_param negotiate program /usr/lib64/squid/negotiate_kerberos_auth -k /etc/squid/HTTP.keytab -s HTTP/proxy.ad.example.com@AD.EXAMPLE.COMCopy to Clipboard Copied! Toggle word wrap Toggle overflow The following describes the parameters passed to the
negotiate_kerberos_authhelper utility in the example above:-
-k filesets the path to the key tab file. Note that the squid user must have read permissions on this file. -s HTTP/host_name@kerberos_realmsets the Kerberos principal that Squid uses.Optionally, you can enable logging by passing one or both of the following parameters to the helper utility:
-
-ilogs informational messages, such as the authenticating user. -denables debug logging.Squid logs the debugging information from the helper utility to the
/var/log/squid/cache.logfile.
-
Add the following ACL and rule to configure that Squid allows only authenticated users to use the proxy:
acl kerb-auth proxy_auth REQUIRED http_access allow kerb-auth
acl kerb-auth proxy_auth REQUIRED http_access allow kerb-authCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantSpecify these settings before the
http_access deny allrule.Remove the following rule to disable bypassing the proxy authentication from IP ranges specified in
localnetACLs:http_access allow localnet
http_access allow localnetCopy to Clipboard Copied! Toggle word wrap Toggle overflow The following ACL exists in the default configuration and defines
443as a port that uses the HTTPS protocol:acl SSL_ports port 443
acl SSL_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow If users should be able to use the HTTPS protocol also on other ports, add an ACL for each of these port:
acl SSL_ports port port_number
acl SSL_ports port port_numberCopy to Clipboard Copied! Toggle word wrap Toggle overflow Update the list of
acl Safe_portsrules to configure to which ports Squid can establish a connection. For example, to configure that clients using the proxy can only access resources on port 21 (FTP), 80 (HTTP), and 443 (HTTPS), keep only the followingacl Safe_portsstatements in the configuration:acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443
acl Safe_ports port 21 acl Safe_ports port 80 acl Safe_ports port 443Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the configuration contains the
http_access deny !Safe_portsrule that defines access denial to ports that are not defined inSafe_portsACLs.Configure the cache type, the path to the cache directory, the cache size, and further cache type-specific settings in the
cache_dirparameter:cache_dir ufs /var/spool/squid 10000 16 256
cache_dir ufs /var/spool/squid 10000 16 256Copy to Clipboard Copied! Toggle word wrap Toggle overflow With these settings:
-
Squid uses the
ufscache type. -
Squid stores its cache in the
/var/spool/squid/directory. -
The cache grows up to
10000MB. -
Squid creates
16level-1 sub-directories in the/var/spool/squid/directory. Squid creates
256sub-directories in each level-1 directory.If you do not set a
cache_dirdirective, Squid stores the cache in memory.
-
Squid uses the
If you set a different cache directory than
/var/spool/squid/in thecache_dirparameter:Create the cache directory:
mkdir -p path_to_cache_directory
# mkdir -p path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the permissions for the cache directory:
chown squid:squid path_to_cache_directory
# chown squid:squid path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run SELinux in
enforcingmode, set thesquid_cache_tcontext for the cache directory:semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" restorecon -Rv path_to_cache_directory
# semanage fcontext -a -t squid_cache_t "path_to_cache_directory(/.*)?" # restorecon -Rv path_to_cache_directoryCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
semanageutility is not available on your system, install thepolicycoreutils-python-utilspackage.
Open the
3128port in the firewall:firewall-cmd --permanent --add-port=3128/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=3128/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
squidservice:systemctl enable --now squid
# systemctl enable --now squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To verify that the proxy works correctly, download a web page using the
curlutility:curl -O -L "https://www.redhat.com/index.html" --proxy-negotiate -u : -x "proxy.ad.example.com:3128"
# curl -O -L "https://www.redhat.com/index.html" --proxy-negotiate -u : -x "proxy.ad.example.com:3128"Copy to Clipboard Copied! Toggle word wrap Toggle overflow If
curldoes not display any error and theindex.htmlfile exists in the current directory, the proxy works.
Troubleshooting steps
Obtain a Kerberos ticket for the AD account:
kinit user@AD.EXAMPLE.COM
# kinit user@AD.EXAMPLE.COMCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the ticket:
klist
# klistCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use the
negotiate_kerberos_auth_testutility to test the authentication:/usr/lib64/squid/negotiate_kerberos_auth_test proxy.ad.example.com
# /usr/lib64/squid/negotiate_kerberos_auth_test proxy.ad.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the helper utility returns a token, the authentication succeeded:
Token: YIIFtAYGKwYBBQUCoIIFqDC...
Token: YIIFtAYGKwYBBQUCoIIFqDC...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
6.4. Configuring a domain deny list in Squid Link kopierenLink in die Zwischenablage kopiert!
Frequently, administrators want to block access to specific domains. This section describes how to configure a domain deny list in Squid.
Prerequisites
- Squid is configured, and users can use the proxy.
Procedure
Edit the
/etc/squid/squid.conffile and add the following settings:acl domain_deny_list dstdomain "/etc/squid/domain_deny_list.txt" http_access deny all domain_deny_list
acl domain_deny_list dstdomain "/etc/squid/domain_deny_list.txt" http_access deny all domain_deny_listCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantAdd these entries before the first
http_access allowstatement that allows access to users or clients.Create the
/etc/squid/domain_deny_list.txtfile and add the domains you want to block. For example, to block access toexample.comincluding subdomains and to blockexample.net, add:.example.com example.net
.example.com example.netCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantIf you referred to the
/etc/squid/domain_deny_list.txtfile in the squid configuration, this file must not be empty. If the file is empty, Squid fails to start.Restart the
squidservice:systemctl restart squid
# systemctl restart squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow
6.5. Configuring the Squid service to listen on a specific port or IP address Link kopierenLink in die Zwischenablage kopiert!
By default, the Squid proxy service listens on the 3128 port on all network interfaces. You can change the port and configuring Squid to listen on a specific IP address.
Prerequisites
-
The
squidpackage is installed.
Procedure
Edit the
/etc/squid/squid.conffile:To set the port on which the Squid service listens, set the port number in the
http_portparameter. For example, to set the port to8080, set:http_port 8080
http_port 8080Copy to Clipboard Copied! Toggle word wrap Toggle overflow To configure on which IP address the Squid service listens, set the IP address and port number in the
http_portparameter. For example, to configure that Squid listens only on the192.0.2.1IP address on port3128, set:http_port 192.0.2.1:3128
http_port 192.0.2.1:3128Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add multiple
http_portparameters to the configuration file to configure that Squid listens on multiple ports and IP addresses:http_port 192.0.2.1:3128 http_port 192.0.2.1:8080
http_port 192.0.2.1:3128 http_port 192.0.2.1:8080Copy to Clipboard Copied! Toggle word wrap Toggle overflow
If you configured that Squid uses a different port as the default (
3128):Open the port in the firewall:
firewall-cmd --permanent --add-port=port_number/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=port_number/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run SELinux in enforcing mode, assign the port to the
squid_port_tport type definition:semanage port -a -t squid_port_t -p tcp port_number
# semanage port -a -t squid_port_t -p tcp port_numberCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
semanageutility is not available on your system, install thepolicycoreutils-python-utilspackage.
Restart the
squidservice:systemctl restart squid
# systemctl restart squidCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Chapter 7. Database servers Link kopierenLink in die Zwischenablage kopiert!
Install the MariaDB, MySQL, or PostgreSQL database server on Red Hat Enterprise Linux 10. Configure the chosen database server, back up your data, and migrate your data to a later version of the database server.
7.1. Introduction to database servers Link kopierenLink in die Zwischenablage kopiert!
A database server is a service that provides features of a database management system (DBMS). DBMS provides utilities for database administration and interacts with end users, applications, and databases.
Red Hat Enterprise Linux 8 provides the following database management systems:
- MariaDB 10.3
- MariaDB 10.5 - available since RHEL 8.4
- MariaDB 10.11 - available since RHEL 8.10
- MySQL 8.0
- PostgreSQL 10
- PostgreSQL 9.6
- PostgreSQL 12 - available since RHEL 8.1.1
- PostgreSQL 13 - available since RHEL 8.4
- PostgreSQL 15 - available since RHEL 8.8
- PostgreSQL 16 - available since RHEL 8.10
7.2. Using MariaDB Link kopierenLink in die Zwischenablage kopiert!
MariaDB Server is a high-performance, open source relational database management system (RDBMS). Built on the MySQL technology, it offers a powerful SQL interface for data access and includes advanced features, such as support for multiple storage engines.
Learn how to install and configure MariaDB on a RHEL system, how to back up MariaDB data, how to migrate from an earlier MariaDB version, and how to replicate a database using the MariaDB Galera Cluster.
7.2.1. Installing MariaDB Link kopierenLink in die Zwischenablage kopiert!
RHEL 8 provides MariaDB 10.3 as the initial version of the Application Stream. Additional MariaDB versions are provided as modules with a shorter life cycle in minor releases of RHEL 8.
In RHEL 8, the MariaDB server is available in the following versions, each provided by a separate stream:
- MariaDB 10.3
- MariaDB 10.5 - available since RHEL 8.4
- MariaDB 10.11 - available since RHEL 8.10
By design, you can install only one version (stream) of the same module and, because of conflicting RPM packages, you cannot install MariaDB and MySQL on the same host. As an alternative, you can run the database server services in a container. See Using containers to run multiple MariaDB and MySQL instances on a single host.
Procedure
Install MariaDB server packages by selecting a stream (version) from the
mariadbmodule and specifying theserverprofile. For example:yum module install mariadb:10.3/server
# yum module install mariadb:10.3/serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
mariadbservice:systemctl enable --now mariadb.service
# systemctl enable --now mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow To improve security when installing MariaDB 10.3, enter:
mysql_secure_installation
$ mysql_secure_installationCopy to Clipboard Copied! Toggle word wrap Toggle overflow The command launches a fully interactive script, which prompts for each step in the process. The script enables you to improve security in the following ways:
- Setting a password for root accounts
- Removing anonymous users
Disallowing remote root logins (outside the local host)
NoteThe mysql_secure_installation script is no longer valuable in MariaDB 10.5 or later. The security enhancements are part of the default behavior since MariaDB 10.5.
7.2.2. Using containers to run multiple MariaDB and MySQL instances on a single host Link kopierenLink in die Zwischenablage kopiert!
If you install MariaDB or MySQL from packages, you can only run one of these services and only a single version of it on the same host. As an alternative, you can run the services in a container.
You can configure the following scenarios:
- You want to run multiple instances of MariaDB or MySQL on the same host.
- You want to run both MariaDB and MySQL on the same host.
Prerequisites
-
The
container-toolsmodule is installed.
Procedure
Use your Red Hat Customer Portal account to authenticate to the
registry.redhat.ioregistry:podman login registry.redhat.io
# podman login registry.redhat.ioCopy to Clipboard Copied! Toggle word wrap Toggle overflow Skip this step if you are already logged in to the container registry.
Run MySQL 8.0 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mysql_root_password> -p <host_port_1>:3306 rhel8/mysql-80
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mysql_root_password> -p <host_port_1>:3306 rhel8/mysql-80Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run MariaDB 10.5 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_2>:3306 rhel8/mariadb-105
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_2>:3306 rhel8/mariadb-105Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run MariaDB 10.11 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_3>:3306 rhel8/mariadb-1011
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_3>:3306 rhel8/mariadb-1011Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
NoteThe container names and host ports of the two database servers must differ.
To ensure that clients can access the database server on the network, open the host ports in the firewall:
firewall-cmd --permanent --add-port={<host_port>/tcp,<host_port>/tcp,...} firewall-cmd --reload# firewall-cmd --permanent --add-port={<host_port>/tcp,<host_port>/tcp,...} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display information about running containers:
podman ps
$ podman psCopy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to the database server and log in as root:
mysql -u root -p -h localhost -P <host_port> --protocol tcp
# mysql -u root -p -h localhost -P <host_port> --protocol tcpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.3. Configuring MariaDB Link kopierenLink in die Zwischenablage kopiert!
To configure the MariaDB server for networking, use the following procedure.
Procedure
Edit the
[mysqld]section of the/etc/my.cnf.d/mariadb-server.cnffile. You can set the following configuration directives:bind-address- is the address on which the server listens. Possible options are:- a host name
- an IPv4 address
- an IPv6 address
skip-networking- controls whether the server listens for TCP/IP connections. Possible values are:- 0 - to listen for all clients
- 1 - to listen for local clients only
-
port- the port on which MariaDB listens for TCP/IP connections.
Restart the
mariadbservice:systemctl restart mariadb.service
# systemctl restart mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.4. Setting up TLS encryption on a MariaDB server Link kopierenLink in die Zwischenablage kopiert!
By default, MariaDB uses unencrypted connections. For secure connections, enable TLS support on the MariaDB server and configure your clients to establish encrypted connections.
7.2.4.1. Placing the CA certificate, server certificate, and private key on the MariaDB server Link kopierenLink in die Zwischenablage kopiert!
Before you can enable TLS encryption in the MariaDB server, store the certificate authority (CA) certificate, the server certificate, and the private key on the MariaDB server.
Prerequisites
The following files in Privacy Enhanced Mail (PEM) format have been copied to the server:
-
The private key of the server:
server.example.com.key.pem -
The server certificate:
server.example.com.crt.pem -
The Certificate Authority (CA) certificate:
ca.crt.pem
For details about creating a private key and certificate signing request (CSR), as well as about requesting a certificate from a CA, see your CA’s documentation.
-
The private key of the server:
Procedure
Store the CA and server certificates in the
/etc/pki/tls/certs/directory:mv <path>/server.example.com.crt.pem /etc/pki/tls/certs/ mv <path>/ca.crt.pem /etc/pki/tls/certs/
# mv <path>/server.example.com.crt.pem /etc/pki/tls/certs/ # mv <path>/ca.crt.pem /etc/pki/tls/certs/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set permissions on the CA and server certificate that enable the MariaDB server to read the files:
chmod 644 /etc/pki/tls/certs/server.example.com.crt.pem /etc/pki/tls/certs/ca.crt.pem
# chmod 644 /etc/pki/tls/certs/server.example.com.crt.pem /etc/pki/tls/certs/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow Because certificates are part of the communication before a secure connection is established, any client can retrieve them without authentication. Therefore, you do not need to set strict permissions on the CA and server certificate files.
Store the server’s private key in the
/etc/pki/tls/private/directory:mv <path>/server.example.com.key.pem /etc/pki/tls/private/
# mv <path>/server.example.com.key.pem /etc/pki/tls/private/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set secure permissions on the server’s private key:
chmod 640 /etc/pki/tls/private/server.example.com.key.pem chgrp mysql /etc/pki/tls/private/server.example.com.key.pem
# chmod 640 /etc/pki/tls/private/server.example.com.key.pem # chgrp mysql /etc/pki/tls/private/server.example.com.key.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow If unauthorized users have access to the private key, connections to the MariaDB server are no longer secure.
Restore the SELinux context:
restorecon -Rv /etc/pki/tls/
# restorecon -Rv /etc/pki/tls/Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.4.2. Configuring TLS encryption on a MariaDB server Link kopierenLink in die Zwischenablage kopiert!
By default, MariaDB uses unencrypted connections. For more secure connections, you can enable Transport Layer Security (TLS) support on the MariaDB server and configure your clients to establish encrypted connections.
Prerequisites
- You installed the MariaDB server.
-
The
mariadbservice is running. The following files in Privacy Enhanced Mail (PEM) format exist on the server and are readable by the
mysqluser:-
The private key of the server:
/etc/pki/tls/private/server.example.com.key.pem -
The server certificate:
/etc/pki/tls/certs/server.example.com.crt.pem -
The Certificate Authority (CA) certificate
/etc/pki/tls/certs/ca.crt.pem
-
The private key of the server:
- The subject distinguished name (DN) or the subject alternative name (SAN) field in the server certificate matches the server’s hostname.
Procedure
Create the
/etc/my.cnf.d/mariadb-server-tls.cnffile:Add the following content to configure the paths to the private key, server and CA certificate:
[mariadb] ssl_key = /etc/pki/tls/private/server.example.com.key.pem ssl_cert = /etc/pki/tls/certs/server.example.com.crt.pem ssl_ca = /etc/pki/tls/certs/ca.crt.pem
[mariadb] ssl_key = /etc/pki/tls/private/server.example.com.key.pem ssl_cert = /etc/pki/tls/certs/server.example.com.crt.pem ssl_ca = /etc/pki/tls/certs/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you have a Certificate Revocation List (CRL), configure the MariaDB server to use it:
ssl_crl = /etc/pki/tls/certs/example.crl.pem
ssl_crl = /etc/pki/tls/certs/example.crl.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: If you run MariaDB 10.5.2 or later, you can reject connection attempts without encryption. To enable this feature, append:
require_secure_transport = on
require_secure_transport = onCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: If you run MariaDB 10.4.6 or later, you can set the TLS versions the server should support. For example, to support TLS 1.2 and TLS 1.3, append:
tls_version = TLSv1.2,TLSv1.3
tls_version = TLSv1.2,TLSv1.3Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the server supports TLS 1.1, TLS 1.2, and TLS 1.3.
Restart the
mariadbservice:systemctl restart mariadb.service
# systemctl restart mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To simplify troubleshooting, perform the following steps on the MariaDB server before you configure the local client to use TLS encryption:
Verify that MariaDB now has TLS encryption enabled:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the
have_sslvariable is set toyes, TLS encryption is enabled.If you configured the MariaDB service to only support specific TLS versions, display the
tls_versionvariable:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.4.3. Requiring TLS encrypted connections for specific user accounts Link kopierenLink in die Zwischenablage kopiert!
You can configure specific MariaDB user accounts to require TLS-encrypted connections to protect sensitive data transmission.
If you cannot configure on the server that a secure transport is required for all connections (require_secure_transport = on), configure individual user accounts to require TLS encryption.
Prerequisites
- The MariaDB server has TLS support enabled.
- The user you configure to require secure transport exists.
- The client trusts the CA certificate that issued the server’s certificate.
Procedure
Connect as an administrative user to the MariaDB server:
mysql -u root -p -h server.example.com
# mysql -u root -p -h server.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow If your administrative user has no permissions to access the server remotely, perform the command on the MariaDB server and connect to
localhost.Use the
REQUIRE SSLclause to enforce that a user must connect using a TLS-encrypted connection:MariaDB [(none)]> ALTER USER 'example'@'%' REQUIRE SSL;
MariaDB [(none)]> ALTER USER 'example'@'%' REQUIRE SSL;Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Connect to the server as the
exampleuser using TLS encryption:mysql -u example -p -h server.example.com --ssl
# mysql -u example -p -h server.example.com --ssl ... MariaDB [(none)]>Copy to Clipboard Copied! Toggle word wrap Toggle overflow If no error is shown and you have access to the interactive MariaDB console, the connection with TLS succeeds.
Attempt to connect as the
exampleuser with TLS disabled:mysql -u example -p -h server.example.com --skip-ssl
# mysql -u example -p -h server.example.com --skip-ssl ERROR 1045 (28000): Access denied for user 'example'@'server.example.com' (using password: YES)Copy to Clipboard Copied! Toggle word wrap Toggle overflow The server rejected the login attempt because TLS is required for this user but disabled (
--skip-ssl).
7.2.5. Configuring the MariaDB client to use TLS encryption by default Link kopierenLink in die Zwischenablage kopiert!
On RHEL, you can globally configure that the MariaDB client uses TLS encryption and verifies that the Common Name (CN) in the server certificate matches the hostname the user connects to. This prevents man-in-the-middle attacks.
Prerequisites
- The MariaDB server has TLS support enabled.
- If the certificate authority (CA) that issued the server’s certificate is not trusted by RHEL, the CA certificate has been copied to the client.
Procedure
If RHEL does not trust the CA that issued the server’s certificate:
Copy the CA certificate to the
/etc/pki/ca-trust/source/anchors/directory:cp <path>/ca.crt.pem /etc/pki/ca-trust/source/anchors/
# cp <path>/ca.crt.pem /etc/pki/ca-trust/source/anchors/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set permissions that enable all users to read the CA certificate file:
chmod 644 /etc/pki/ca-trust/source/anchors/ca.crt.pem
# chmod 644 /etc/pki/ca-trust/source/anchors/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow Rebuild the CA trust database:
update-ca-trust
# update-ca-trustCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Create the
/etc/my.cnf.d/mariadb-client-tls.cnffile with the following content:[client-mariadb] ssl ssl-verify-server-cert
[client-mariadb] ssl ssl-verify-server-certCopy to Clipboard Copied! Toggle word wrap Toggle overflow These settings define that the MariaDB client uses TLS encryption (
ssl) and that the client compares the hostname with the CN in the server certificate (ssl-verify-server-cert).
Verification
Connect to the server using the hostname, and display the server status:
mysql -u root -p -h server.example.com -e status
# mysql -u root -p -h server.example.com -e status ... SSL: Cipher in use is TLS_AES_256_GCM_SHA384Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the
SSLentry containsCipher in use is…, the connection is encrypted.Note that the user you use in this command has permissions to authenticate remotely.
If the hostname you connect to does not match the hostname in the TLS certificate of the server, the
ssl-verify-server-certparameter causes the connection to fail. For example, if you connect tolocalhost:mysql -u root -p -h localhost -e status
# mysql -u root -p -h localhost -e status ERROR 2026 (HY000): SSL connection error: Validation of SSL server certificate failedCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.6. Backing up and restoring MariaDB data with logical dumps Link kopierenLink in die Zwischenablage kopiert!
A logical backup of MariaDB data consists of the SQL statements necessary to restore the data. The advantage of logical backup over physical backup is that the data can be restored on other hardware configurations and MariaDB versions.
7.2.6.1. Performing a logical backup by using mysqldump Link kopierenLink in die Zwischenablage kopiert!
The mysqldump utility is a versatile backup tool that can export one or more databases. Its output is typically a file containing SQL statements designed to re-create the database structure and populate it with data, making it ideal for backups or server transfers.
To perform the mysqldump backup, you can use one of the following options:
- Back up one or more selected databases
- Back up all databases
- Back up a subset of tables from one database
Procedure
To dump a single database, run:
mysqldump [options] --databases db_name > backup-file.sql
# mysqldump [options] --databases db_name > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump multiple databases at once, run:
mysqldump [options] --databases db_name1 [db_name2 ...] > backup-file.sql
# mysqldump [options] --databases db_name1 [db_name2 ...] > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump all databases, run:
mysqldump [options] --all-databases > backup-file.sql
# mysqldump [options] --all-databases > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load one or more dumped full databases back into a server, run:
mysql < backup-file.sql
# mysql < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load a database to a remote MySQL server, run:
mysql --host=remote_host < backup-file.sql
# mysql --host=remote_host < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump a subset of tables from one database, add a list of the chosen tables at the end of the
mysqldumpcommand:mysqldump [options] db_name [tbl_name ...] > backup-file.sql
# mysqldump [options] db_name [tbl_name ...] > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load a literal,subset of tables dumped from one database, run:
mysql db_name < backup-file.sql
# mysql db_name < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteThe db_name database must exist at this point.
To see a list of the options that mysqldump supports, run:
mysqldump --help
$ mysqldump --helpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.7. Backing up and restoring MariaDB data with physical copies Link kopierenLink in die Zwischenablage kopiert!
A physical backup of MariaDB data contains file and directories that store the content. This method is typically faster and smaller in size.
7.2.7.1. Performing a physical online backup by using mariabackup Link kopierenLink in die Zwischenablage kopiert!
You can create physical online backups of your MariaDB server by using the mariabackup utility to backup InnoDB, Aria, and MyISAM tables while the server is running. The utility supports full backup capability for MariaDB server, which includes encrypted and compressed data.
Prerequisites
The
mariadb-backuppackage is installed on the system:yum install mariadb-backup
# yum install mariadb-backupCopy to Clipboard Copied! Toggle word wrap Toggle overflow
- You must provide Mariabackup with credentials for the user under which the backup will be run. You can provide the credentials either on the command line or by a configuration file.
-
Users of Mariabackup must have the
RELOAD,LOCK TABLES, andREPLICATION CLIENTprivileges.
To create a backup of a database using Mariabackup, use the following procedure.
Procedure
To create a backup while providing credentials on the command line, run:
mariabackup --backup --target-dir <backup_directory> --user <backup_user> --password <backup_passwd>
$ mariabackup --backup --target-dir <backup_directory> --user <backup_user> --password <backup_passwd>Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
target-diroption defines the directory where the backup files are stored. If you want to perform a full backup, the target directory must be empty or not exist.The
userandpasswordoptions allow you to configure the user name and the password.To create a backup with credentials set in a configuration file:
-
Create a configuration file in the
/etc/my.cnf.d/directory, for example,/etc/my.cnf.d/mariabackup.cnf. Add the following lines into the
[xtrabackup]or[mysqld]section of the new file:[xtrabackup] user=myuser password=mypassword
[xtrabackup] user=myuser password=mypasswordCopy to Clipboard Copied! Toggle word wrap Toggle overflow Perform the backup:
mariabackup --backup --target-dir <backup_directory>
$ mariabackup --backup --target-dir <backup_directory>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
-
Create a configuration file in the
7.2.7.2. Restoring data by using mariabackup Link kopierenLink in die Zwischenablage kopiert!
If you have a MariaDB backup created by the mariabackup utility, you can use the same utility to restore the data.
Prerequisites
-
The
mariadbservice is stopped. - The data directory is empty.
-
Users of
mariabackupmust have theRELOAD,LOCK TABLES, andREPLICATION CLIENTprivileges.
Procedure
Use one of the following options to restore the data:
To restore data from the backup in the
/var/mariadb/backup/directory and keep the original backup files, enter:mariabackup --copy-back --target-dir=/var/mariadb/backup/
$ mariabackup --copy-back --target-dir=/var/mariadb/backup/Copy to Clipboard Copied! Toggle word wrap Toggle overflow To restore data from the backup in the
/var/mariadb/backup/directory and remove the original backup files, enter:mariabackup --move-back --target-dir=/var/mariadb/backup/
$ mariabackup --move-back --target-dir=/var/mariadb/backup/Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Fix the file permissions. For example, to recursively change ownership of the files to the
mysqluser and group, enter:chown -R mysql:mysql /var/lib/mysql/
# chown -R mysql:mysql /var/lib/mysql/Copy to Clipboard Copied! Toggle word wrap Toggle overflow When restoring a database,
mariabackuppreserves the file and directory privileges of the backup. However,mariabackupwrites the files to disk as the user and group restoring the database. Therefore, after restoring a backup, you must adjust the owner of the data directory to match the user and group for the MariaDB server.Start the
mariadbservice:systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.7.3. Performing a file system backup on a MariaDB server Link kopierenLink in die Zwischenablage kopiert!
You can create a file system backup of your MariaDB server by copying data files, configuration files, and log files to a backup location.
Procedure
Stop the
mariadbservice:systemctl stop mariadb.service
# systemctl stop mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Copy the data files to the required location:
cp -r /var/lib/mysql /backup-location
# cp -r /var/lib/mysql /backup-locationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Copy the configuration files to the required location:
cp -r /etc/my.cnf /etc/my.cnf.d /backup-location/configuration
# cp -r /etc/my.cnf /etc/my.cnf.d /backup-location/configurationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Copy the log files to the required location:
cp /var/log/mariadb/* /backup-location/logs
# cp /var/log/mariadb/* /backup-location/logsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the
mariadbservice:systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow When loading the backed up data from the backup location to the
/var/lib/mysqldirectory, ensure thatmysql:mysqlis an owner of all data in/var/lib/mysql:chown -R mysql:mysql /var/lib/mysql
# chown -R mysql:mysql /var/lib/mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.8. Replicating MariaDB with Galera Link kopierenLink in die Zwischenablage kopiert!
You can replicate a MariaDB database using the Galera solution to create a synchronous multi-source cluster for high availability and data consistency.
Replication itself is not a sufficient backup solution. Replication protects source servers against hardware failures, but it does not ensure protection against data loss.
7.2.8.1. Introduction to MariaDB Galera Cluster Link kopierenLink in die Zwischenablage kopiert!
MariaDB Galera Cluster provides synchronous multi-source replication that allows all nodes to be writable and ensures data consistency across the cluster.
The interface between Galera replication and a MariaDB database is defined by the write set replication API (wsrep API).
The main features of MariaDB Galera Cluster are:
- Synchronous replication
- Active-active multi-source topology
- Read and write to any cluster node
- Automatic membership control, failed nodes drop from the cluster
- Automatic node joining
- Parallel replication on row level
- Direct client connections: users can log on to the cluster nodes, and work with the nodes directly while the replication runs
Synchronous replication means that a server replicates a transaction at commit time by broadcasting the write set associated with the transaction to every node in the cluster. The client (user application) connects directly to the Database Management System (DBMS), and experiences behavior that is similar to native MariaDB.
Synchronous replication guarantees that a change that happened on one node in the cluster happens on other nodes in the cluster at the same time.
Therefore, synchronous replication has the following advantages over asynchronous replication:
- No delay in propagation of the changes between particular cluster nodes
- All cluster nodes are always consistent
- The latest changes are not lost if one of the cluster nodes crashes
- Transactions on all cluster nodes are executed in parallel
- Causality across the whole cluster
7.2.8.2. Components to build MariaDB Galera Cluster Link kopierenLink in die Zwischenablage kopiert!
Before deploying a functional, synchronously replicated MariaDB Galera Cluster, you must first install and understand the function of the core software components, specifically the MariaDB Server, the Galera Replication library, and the supporting Galera packages.
To build MariaDB Galera Cluster, you must install the following packages on your system:
-
mariadb-server-galera- contains support files and scripts for MariaDB Galera Cluster. -
mariadb-server- is patched by MariaDB upstream to include the write set replication API (wsrep API). This API provides the interface between Galera replication and MariaDB. galera- is patched by MariaDB upstream to add full support for MariaDB. Thegalerapackage contains the following:- Galera Replication Library provides the whole replication functionality.
- The Galera Arbitrator utility can be used as a cluster member that participates in voting in split-brain scenarios. However, Galera Arbitrator cannot participate in the actual replication.
-
Galera Systemd service and Galera wrapper script which are used for deploying the Galera Arbitrator utility. MariaDB 10.3, MariaDB 10.5, and MariaDB 10.11 in RHEL 8 include a Red Hat version of the
garbdsystemd service and a wrapper script for thegalerapackage in the/usr/lib/systemd/system/garbd.serviceand/usr/sbin/garbd-wrapperfiles, respectively. Since RHEL 8.6, MariaDB distributed with RHEL also provides an upstream version of these files located at/usr/share/doc/galera/garb-systemdand/usr/share/doc/galera/garbd.service.
7.2.8.3. Deploying MariaDB Galera Cluster Link kopierenLink in die Zwischenablage kopiert!
You can deploy MariaDB Galera Cluster by installing the required packages, configuring cluster settings, and bootstrapping the first node to create a new cluster.
Prerequisites
- All of the nodes in the cluster have TLS set up.
All certificates on all nodes must have the
Extended Key Usagefield set to:TLS Web Server Authentication, TLS Web Client Authentication
TLS Web Server Authentication, TLS Web Client AuthenticationCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Procedure
Install MariaDB Galera Cluster packages by selecting a stream (version) from the
mariadbmodule and specifying thegaleraprofile. For example:yum module install mariadb:10.3/galera
# yum module install mariadb:10.3/galeraCopy to Clipboard Copied! Toggle word wrap Toggle overflow As a result, the following packages are installed together with their dependencies:
-
mariadb-server-galera -
mariadb-server galeraFor more information about which packages you need to install to build MariaDB Galera Cluster, see Components to build MariaDB Cluster.
-
Update the MariaDB server replication configuration before the system is added to a cluster for the first time. The default configuration is distributed in the
/etc/my.cnf.d/galera.cnffile. Before deploying MariaDB Galera Cluster, set thewsrep_cluster_addressoption in the/etc/my.cnf.d/galera.cnffile on all nodes to start with the following string:gcomm://
gcomm://Copy to Clipboard Copied! Toggle word wrap Toggle overflow For the initial node, it is possible to set
wsrep_cluster_addressas an empty list:wsrep_cluster_address="gcomm://"
wsrep_cluster_address="gcomm://"Copy to Clipboard Copied! Toggle word wrap Toggle overflow For all other nodes, set
wsrep_cluster_addressto include an address to any node which is already a part of the running cluster. For example:wsrep_cluster_address="gcomm://10.0.0.10"
wsrep_cluster_address="gcomm://10.0.0.10"Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about how to set Galera Cluster address, see Galera Cluster Address.
-
Enable the
wsrepAPI on every node by setting thewsrep_on=1option in the/etc/my.cnf.d/galera.cnfconfiguration file. Add the
wsrep_provider_optionsvariable to the Galera configuration file with the TLS keys and certificates. For example:wsrep_provider_options="socket.ssl_cert=/etc/pki/tls/certs/source.crt;socket.ssl_key=/etc/pki/tls/private/source.key;socket.ssl_ca=/etc/pki/tls/certs/ca.crt”
wsrep_provider_options="socket.ssl_cert=/etc/pki/tls/certs/source.crt;socket.ssl_key=/etc/pki/tls/private/source.key;socket.ssl_ca=/etc/pki/tls/certs/ca.crt”Copy to Clipboard Copied! Toggle word wrap Toggle overflow Bootstrap a first node of a new cluster by running the following wrapper on that node:
galera_new_cluster
# galera_new_clusterCopy to Clipboard Copied! Toggle word wrap Toggle overflow This wrapper ensures that the MariaDB server daemon (
mysqld) runs with the--wsrep-new-clusteroption. This option provides the information that there is no existing cluster to connect to. Therefore, the node creates a new UUID to identify the new cluster.NoteThe
mariadbservice supports a systemd method for interacting with multiple MariaDB server processes. Therefore, in cases with multiple running MariaDB servers, you can bootstrap a specific instance by specifying the instance name as a suffix:galera_new_cluster mariadb@node1
# galera_new_cluster mariadb@node1Copy to Clipboard Copied! Toggle word wrap Toggle overflow Connect other nodes to the cluster by running the following command on each of the nodes:
systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow As a result, the node connects to the cluster, and synchronizes itself with the state of the cluster.
Verification
7.2.8.4. Checking the status of a MariaDB Galera cluster Link kopierenLink in die Zwischenablage kopiert!
It is important to monitor and ensure the health, performance, and synchronization of a MariaDB Galera cluster. For that, you can query status variables on each node to monitor the node and the cluster.
To check the status of a MariaDB Galera cluster, you can use the following queries:
Display the number of nodes in the cluster:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Display the node’s cluster component status:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The value of the
wsrep_cluster_statusvariable indicates the status of the cluster component the current node belongs to. Possible values are:-
Primary: The cluster is functioning normally. A quorum is present. In a healthy cluster, all nodes reportPrimary. -
Non-primary: The node has lost the connection to the primary component of the cluster and is no longer part of the active cluster. However, the node still can serve read queries but cannot process write operations. -
Disconnected: The node is not connected to any cluster component. Consequently, it cannot accept queries and is not replicating any data.
-
Display the node’s status:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following are frequent values of the
wsrep_local_state_commentvariable:-
Synced: The node is fully synchronized within the cluster and actively participating in replication. -
Desynced: The node is still part of the cluster but it is primarily busy with the state transfer. -
Joining: The node is in the process of joining a cluster. -
Joined: The node has successfully joined a cluster. It can receive and apply write sets from the cluster. -
Donor: The node currently provides a State Snapshot Transfer (SST) to a joining node. When a new node joins and requires a full state transfer, the cluster selects an existing node to send the necessary data.
-
Check whether the node accepts write sets from the cluster:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow When the
wsrep_readyvariable isON, the node has successfully initialized its components and is connected to a cluster. Additionally, the node is synchronized or has reached a state where it can serve queries.Check whether the node has network connectivity with other hosts:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
ONvalue means that node has connectivity to at least one member in the cluster.Display the average size of the local received queue for write sets since the last
FLUSH STATUScommand or since the server started:Copy to Clipboard Copied! Toggle word wrap Toggle overflow A value near 0 is the ideal state and indicates that the node continues applying write sets as they are received. A persistently high or growing value can be an indicator of performance bottlenecks, such as slow disk I/O.
Display the flow control status:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow This variable represents the fraction of time a node has been paused and is unable to process new incoming transactions because its local receive queue was too full, triggering flow control. A value close to 0 indicates the node continues with the replication workload efficiently. A value approaching 1.0 means that the node frequently or constantly encounters difficulty in applying write sets and can be a bottleneck for the cluster.
If the node is frequently pausing, you can adjust the
wsrep_slave_threadsparameter in the/etc/my.cnf.d/galera.cnffile.Display the average distance between the lowest and highest sequence numbers the node can apply in parallel:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow A higher value indicates a greater degree of parallelism. It is the optimal value you can use in the
wsrep_slave_threadsparameter in the/etc/my.cnf.d/galera.cnffile.
7.2.8.5. Adding a new node to MariaDB Galera Cluster Link kopierenLink in die Zwischenablage kopiert!
You can add a new node to your MariaDB Galera Cluster or reconnect an existing one by configuring the cluster address in the node’s configuration file.
Procedure
On the particular node, provide an address to one or more existing cluster members in the
wsrep_cluster_addressoption within the[mariadb]section of the/etc/my.cnf.d/galera.cnfconfiguration file :[mariadb] wsrep_cluster_address="gcomm://192.168.0.1"
[mariadb] wsrep_cluster_address="gcomm://192.168.0.1"Copy to Clipboard Copied! Toggle word wrap Toggle overflow When a new node connects to one of the existing cluster nodes, it is able to see all nodes in the cluster.
However, preferably list all nodes of the cluster in
wsrep_cluster_address.As a result, any node can join a cluster by connecting to any other cluster node, even if one or more cluster nodes are down. When all members agree on the membership, the cluster’s state is changed. If the new node’s state is different from the state of the cluster, the new node requests either an Incremental State Transfer (IST) or a State Snapshot Transfer (SST) to ensure consistency with the other nodes.
7.2.8.6. Restarting MariaDB Galera Cluster Link kopierenLink in die Zwischenablage kopiert!
If you shut down all nodes at the same time, you stop the cluster, and the running cluster no longer exists. However, the cluster’s data still exist.
To restart the cluster, bootstrap a first node as described in Configuring MariaDB Galera Cluster.
If the cluster is not bootstrapped, and mariadb on the first node is started with only the systemctl start mariadb.service command, the node tries to connect to at least one of the nodes listed in the wsrep_cluster_address option in the /etc/my.cnf.d/galera.cnf file. If no nodes are currently running, the restart fails.
7.2.9. Migrating to MariaDB 10.3 Link kopierenLink in die Zwischenablage kopiert!
You can migrate your MariaDB databases a RHEL 8 version of MariaDB 10.3 by using the mysql_upgrade utility to perform an in-place upgrade of your database server.
RHEL 7 contains MariaDB 5.5 as the default implementation of a server from the MySQL databases family. Later versions of the MariaDB database server are available as Software Collections for RHEL 7. RHEL 8 provides MariaDB 10.3, MariaDB 10.5, MariaDB 10.11, and MySQL 8.0.
This part describes migration to MariaDB 10.3 from a RHEL 7 or Red Hat Software Collections version of MariaDB.
If you want to migrate from MariaDB 10.3 to MariaDB 10.5 within RHEL 8, see Upgrading from MariaDB 10.3 to MariaDB 10.5 instead.
If you want to migrate from MariaDB 10.5 to MariaDB 10.11 within RHEL 8, see Upgrading from MariaDB 10.5 to MariaDB 10.11.
7.2.9.1. Notable differences between the RHEL 7 and RHEL 8 versions of MariaDB Link kopierenLink in die Zwischenablage kopiert!
MariaDB 10.3 on RHEL 8 introduces significant changes including Galera Cluster integration, new storage engines, InnoDB as default, and unified client libraries for MySQL and MariaDB compatibility.
The most important changes between MariaDB 5.5 and MariaDB 10.3 are:
- MariaDB Galera Cluster, a synchronous multi-source cluster, is a standard part of MariaDB since 10.1.
- The ARCHIVE storage engine is no longer enabled by default, and the plugin needs to be specifically enabled.
- The BLACKHOLE storage engine is no longer enabled by default, and the plugin needs to be specifically enabled.
InnoDB is used as the default storage engine instead of XtraDB, which was used in MariaDB 10.1 and earlier versions.
For more details, see InnoDB instead of XtraDB.
-
The new
mariadb-connector-cpackages provide a common client library for MySQL and MariaDB. This library is usable with any version of the MySQL and MariaDB database servers. As a result, the user is able to connect one build of an application to any of the MySQL and MariaDB servers distributed with Red Hat Enterprise Linux 8.
To migrate from MariaDB 5.5 to MariaDB 10.3, you need to perform multiple configuration changes.
7.2.9.2. Configuration changes Link kopierenLink in die Zwischenablage kopiert!
If you want to upgrade MariaDB from 5.5 to 10.3, upgrade one minor version at a time. Start with the upgrade to MariaDB 10.0, and then upgrade by one version successively.
For more information about configuration changes when migrating from MariaDB 5.5 to MariaDB 10.0, see Migrating to MariaDB 10.0 in Red Hat Software Collections documentation.
The migration to following successive versions of MariaDB and the required configuration changes is described in these documents:
- Migrating to MariaDB 10.1 in Red Hat Software Collections documentation.
- Migrating to MariaDB 10.2 in Red Hat Software Collections documentation.
- Migrating to MariaDB 10.3 in Red Hat Software Collections documentation.
Migration directly from MariaDB 5.5 to MariaDB 10.3 is also possible, but you must perform all configuration changes that are required by differences described in the migration documents above.
7.2.9.3. In-place upgrade using the mysql_upgrade utility Link kopierenLink in die Zwischenablage kopiert!
You can migrate your MariaDB databases from RHEL 7 to RHEL 8 by copying data files and using the mysql_upgrade utility to perform an in-place upgrade.
You can use this method for migrating data from:
- The Red Hat Enterprise Linux 7 version of MariaDB 5.5
The Red Hat Software Collections versions of:
- MariaDB 5.5 (no longer supported)
- MariaDB 10.0 (no longer supported)
- MariaDB 10.1 (no longer supported)
- MariaDB 10.2 (no longer supported)
MariaDB 10.3 (no longer supported)
Note that it is recommended to upgrade to MariaDB 10.3 by one version successively. See the respective Migration chapters in the Release Notes for Red Hat Software Collections.
If you are upgrading from the RHEL 7 version of MariaDB, the source data is stored in the /var/lib/mysql/ directory. In case of Red Hat Software Collections versions of MariaDB, the source data directory is /var/opt/rh/<collection_name>/lib/mysql/ (with the exception of the mariadb55, which uses the /opt/rh/mariadb55/root/var/lib/mysql/ data directory).
There are certain risks and known problems related to an in-place upgrade. For example, some queries might not work or they will be run in a different order than before the upgrade. For more information about these risks and problems, and for general information about an in-place upgrade, see MariaDB 10.3 Release Notes.
Prerequisites
- Before performing the upgrade, back up all your data stored in the MariaDB databases.
Procedure
Ensure that the
mariadb-serverpackage is installed on the RHEL 8 system:yum install mariadb-server
# yum install mariadb-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Ensure that the
mariadbservice is not running on either of the source and target systems at the time of copying data:systemctl stop mariadb.service
# systemctl stop mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Copy the data from the source location to the
/var/lib/mysql/directory on the RHEL 8 target system. Set the appropriate permissions and SELinux context for copied files on the target system:
restorecon -vr /var/lib/mysql
# restorecon -vr /var/lib/mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the MariaDB server on the target system:
systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Run the
mysql_upgradecommand to check and repair internal tables:mysql_upgrade
$ mysql_upgradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
When the upgrade is complete, verify that all configuration files within the
/etc/my.cnf.d/directory include only options valid for MariaDB 10.3.
7.2.10. Upgrading from MariaDB 10.3 to MariaDB 10.5 Link kopierenLink in die Zwischenablage kopiert!
You can upgrade your MariaDB database from version 10.3 to 10.5 on RHEL 8 to take advantage of new features and improvements in the newer version.
7.2.10.1. Notable differences between MariaDB 10.3 and MariaDB 10.5 Link kopierenLink in die Zwischenablage kopiert!
MariaDB 10.5 introduces significant changes including new authentication plugins, updated privileges, improved Galera Cluster features, and enhanced PAM plugin functionality.
Significant changes between MariaDB 10.3 and MariaDB 10.5 include:
-
MariaDB now uses the
unix_socketauthentication plugin by default. The plugin enables users to use operating system credentials when connecting to MariaDB through the local UNIX socket file. -
MariaDBaddsmariadb-*named binaries andmysql*symbolic links pointing to themariadb-*binaries. For example, themysqladmin,mysqlaccess, andmysqlshowsymlinks point to themariadb-admin,mariadb-access, andmariadb-showbinaries, respectively. -
The
SUPERprivilege has been split into several privileges to better align with each user role. As a result, certain statements have changed required privileges. -
In parallel replication, the
slave_parallel_modenow defaults tooptimistic. -
In the InnoDB storage engine, defaults of the following variables have been changed:
innodb_adaptive_hash_indextoOFFandinnodb_checksum_algorithmtofull_crc32. MariaDB now uses the
libeditimplementation of the underlying software managing the MariaDB command history (the.mysql_historyfile) instead of the previously usedreadlinelibrary. This change impacts users working directly with the.mysql_historyfile. Note that.mysql_historyis a file managed by the MariaDB or MySQL applications, and users should not work with the file directly. The human-readable appearance is coincidental.NoteTo increase security, you can consider not maintaining a history file. To disable the command history recording:
-
Remove the
.mysql_historyfile if it exists. Use either of the following approaches:
-
Set the
MYSQL_HISTFILEvariable to/dev/nulland include this setting in any of your shell’s startup files. Change the
.mysql_historyfile to a symbolic link to/dev/null:ln -s /dev/null $HOME/.mysql_history
$ ln -s /dev/null $HOME/.mysql_historyCopy to Clipboard Copied! Toggle word wrap Toggle overflow
-
Set the
-
Remove the
MariaDB Galera Cluster has been upgraded to version 4 with the following notable changes:
- Galera adds a new streaming replication feature, which supports replicating transactions of unlimited size. During an execution of streaming replication, a cluster replicates a transaction in small fragments.
- Galera now fully supports Global Transaction ID (GTID).
-
The default value for the
wsrep_onoption in the/etc/my.cnf.d/galera.cnffile has changed from1to0to prevent end users from startingwsrepreplication without configuring required additional options.
Changes to the PAM plugin in MariaDB 10.5 include:
-
MariaDB 10.5 adds a new version of the Pluggable Authentication Modules (PAM) plugin. The PAM plugin version 2.0 performs PAM authentication using a separate
setuid roothelper binary, which enables MariaDB to use additional PAM modules. -
The helper binary can be executed only by users in the
mysqlgroup. By default, the group contains only themysqluser. Red Hat recommends that administrators do not add more users to themysqlgroup to prevent password-guessing attacks without throttling or logging through this helper utility. -
In MariaDB 10.5, the Pluggable Authentication Modules (PAM) plugin and its related files have been moved to a new package,
mariadb-pam. As a result, no newsetuid rootbinary is introduced on systems that do not use PAM authentication forMariaDB. -
The
mariadb-pampackage contains both PAM plugin versions: version 2.0 is the default, and version 1.0 is available as theauth_pam_v1shared object library. -
The
mariadb-pampackage is not installed by default with the MariaDB server. To make the PAM authentication plugin available in MariaDB 10.5, install themariadb-pampackage manually.
7.2.10.2. Upgrading from a RHEL 8 version of MariaDB 10.3 to MariaDB 10.5 Link kopierenLink in die Zwischenablage kopiert!
This procedure describes upgrading from the mariadb:10.3 module stream to the mariadb:10.5 module stream using the yum and mariadb-upgrade utilities.
The mariadb-upgrade utility is provided by the mariadb-server-utils subpackage, which is installed as a dependency of the mariadb-server package.
There are certain risks and known problems related to an in-place upgrade. For example, some queries might not work or they will be run in a different order than before the upgrade. For more information about these risks and problems, and for general information about an in-place upgrade, see MariaDB 10.5 Release Notes.
Prerequisites
- Before performing the upgrade, back up all your data stored in the MariaDB databases.
Procedure
Stop the MariaDB server:
systemctl stop mariadb.service
# systemctl stop mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Execute the following command to determine if your system is prepared for switching to a later stream:
yum distro-sync
# yum distro-syncCopy to Clipboard Copied! Toggle word wrap Toggle overflow This command must finish with the message Nothing to do. Complete! For more information, see Switching to a later stream.
Reset the
mariadbmodule on your system:yum module reset mariadb
# yum module reset mariadbCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the new
mariadb:10.5module stream:yum module enable mariadb:10.5
# yum module enable mariadb:10.5Copy to Clipboard Copied! Toggle word wrap Toggle overflow Synchronize installed packages to perform the change between streams:
yum distro-sync
# yum distro-syncCopy to Clipboard Copied! Toggle word wrap Toggle overflow This will update all installed MariaDB packages.
-
Adjust the configuration so that option files located in
/etc/my.cnf.d/include only options valid for MariaDB 10.5. For details, see upstream documentation for MariaDB 10.4 and MariaDB 10.5. Start the MariaDB server.
When upgrading a database running standalone:
systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow When upgrading a Galera cluster node:
galera_new_cluster
# galera_new_clusterCopy to Clipboard Copied! Toggle word wrap Toggle overflow The
mariadbservice will be started automatically.
Execute the mariadb-upgrade utility to check and repair internal tables.
When upgrading a database running standalone:
mariadb-upgrade
# mariadb-upgradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow When upgrading a Galera cluster node:
mariadb-upgrade --skip-write-binlog
# mariadb-upgrade --skip-write-binlogCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.11. Upgrading from MariaDB 10.5 to MariaDB 10.11 Link kopierenLink in die Zwischenablage kopiert!
You can upgrade your MariaDB database from version 10.5 to 10.11 on RHEL 8 to take advantage of new features and improvements in the newer version.
7.2.11.1. Notable differences between MariaDB 10.5 and MariaDB 10.11 Link kopierenLink in die Zwischenablage kopiert!
MariaDB 10.11 introduces significant changes including atomic DDL statements, new UUID data type, enhanced SSL support, improved Unicode collations, and updated systemd integration.
Significant changes between MariaDB 10.5 and MariaDB 10.11 include:
-
A new
sys_schemafeature is a collection of views, functions, and procedures to provide information about database usage. -
The
CREATE TABLE,ALTER TABLE,RENAME TABLE,DROP TABLE,DROP DATABASE, and related Data Definition Language (DDL) statements are now atomic. The statement must be fully completed, otherwise the changes are reverted. Note that when deleting multiple tables withDROP TABLE, only each individual drop is atomic, not the full list of tables. -
A new
GRANT … TO PUBLICprivilege is available. -
The
SUPERandREAD ONLY ADMINprivileges are now separate. -
You can now store universally unique identifiers in the new
UUIDdatabase data type. - MariaDB now supports the Secure Socket Layer (SSL) protocol version 3.
- The MariaDB server now requires correctly configured SSL to start. Previously, MariaDB silently disabled SSL and used insecure connections in case of misconfigured SSL.
-
MariaDB now supports the natural sort order through the
natural_sort_key()function. -
A new
SFORMATfunction is now available for arbitrary text formatting. -
The
utf8character set (and related collations) is now by default an alias forutf8mb3. - MariaDB supports the Unicode Collation Algorithm (UCA) 14 collations.
-
systemdsocket activation files for MariaDB are now available in the/usr/share/directory. Note that they are not a part of the default configuration in RHEL as opposed to upstream. -
Error messages now contain the
MariaDBstring instead ofMySQL. - Error messages are now available in the Chinese language.
- The default logrotate file has changed significantly. Review your configuration before migrating to MariaDB 10.11.
-
For MariaDB and MySQL clients, the connection property specified on the command line (for example,
--port=3306), now forces the protocol type of communication between the client and the server, such astcp,socket,pipe, ormemory. Previously, for example, the specified port was ignored if a MariaDB client connected through a UNIX socket.
7.2.11.2. Upgrading from a RHEL 8 version of MariaDB 10.5 to MariaDB 10.11 Link kopierenLink in die Zwischenablage kopiert!
This procedure describes upgrading from the mariadb:10.5 module stream to the mariadb:10.11 module stream using the yum and mariadb-upgrade utilities.
The mariadb-upgrade utility is provided by the mariadb-server-utils subpackage, which is installed as a dependency of the mariadb-server package.
There are certain risks and known problems related to an in-place upgrade. For example, some queries might not work or they will be run in a different order than before the upgrade. For more information about these risks and problems, and for general information about an in-place upgrade, see MariaDB 10.11 Release Notes.
Prerequisites
- Before performing the upgrade, back up all your data stored in the MariaDB databases.
Procedure
Stop the MariaDB server:
systemctl stop mariadb.service
# systemctl stop mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Execute the following command to determine if your system is prepared for switching to a later stream:
yum distro-sync
# yum distro-syncCopy to Clipboard Copied! Toggle word wrap Toggle overflow This command must finish with the message Nothing to do. Complete! For more information, see Switching to a later stream.
Reset the
mariadbmodule on your system:yum module reset mariadb
# yum module reset mariadbCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the new
mariadb:10.11module stream:yum module enable mariadb:10.11
# yum module enable mariadb:10.11Copy to Clipboard Copied! Toggle word wrap Toggle overflow Synchronize installed packages to perform the change between streams:
yum distro-sync
# yum distro-syncCopy to Clipboard Copied! Toggle word wrap Toggle overflow This will update all installed MariaDB packages.
-
Adjust the configuration so that option files located in
/etc/my.cnf.d/include only options valid for MariaDB 10.11. For details, see upstream documentation for MariaDB 10.6 and MariaDB 10.11. Start the MariaDB server.
When upgrading a database running standalone:
systemctl start mariadb.service
# systemctl start mariadb.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow When upgrading a Galera cluster node:
galera_new_cluster
# galera_new_clusterCopy to Clipboard Copied! Toggle word wrap Toggle overflow The
mariadbservice will be started automatically.
Execute the mariadb-upgrade utility to check and repair internal tables.
When upgrading a database running standalone:
mariadb-upgrade
# mariadb-upgradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow When upgrading a Galera cluster node:
mariadb-upgrade --skip-write-binlog
# mariadb-upgrade --skip-write-binlogCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.2.12. Developing MariaDB client applications Link kopierenLink in die Zwischenablage kopiert!
MariaDB client applications should be developed against the MariaDB client library. The development files and programs necessary for building these applications are provided by the mariadb-connector-c-devel package.
Instead of using a direct library name, use the mariadb_config program, which is distributed in the mariadb-connector-c-devel package. This program ensures that the correct build flags are returned.
7.3. Using MySQL Link kopierenLink in die Zwischenablage kopiert!
MySQL server is a high-performance, open source relational database management system (RDBMS). It offers an SQL interface for data access and includes advanced features, such as support for multiple storage engines.
Learn how to install and configure MySQL on a RHEL system, how to back up MySQL data, how to migrate from an earlier MySQL version, and how to replicate a MySQL.
7.3.1. Installing MySQL Link kopierenLink in die Zwischenablage kopiert!
RHEL 8 provides MySQL 8.0 as the initial version of the Application Stream.
By design, you can install only one version (stream) of the same module and, because of conflicting RPM packages, you cannot install MariaDB and MySQL on the same host. As an alternative, you can run the database server services in a container. See Using containers to run multiple MariaDB and MySQL instances on a single host.
Procedure
Install MySQL server packages by selecting the
8.0stream (version) from themysqlmodule and specifying theserverprofile:yum module install mysql:8.0/server
# yum module install mysql:8.0/serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the
mysqldservice:systemctl start mysqld.service
# systemctl start mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
mysqldservice to start at boot:systemctl enable mysqld.service
# systemctl enable mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Recommended: To improve security when installing MySQL, run the following command:
mysql_secure_installation
$ mysql_secure_installationCopy to Clipboard Copied! Toggle word wrap Toggle overflow The command launches a fully interactive script, which prompts for each step in the process. The script enables you to improve security in the following ways:
- Setting a password for root accounts
- Removing anonymous users
- Disallowing remote root logins (outside the local host)
7.3.2. Using containers to run multiple MariaDB and MySQL instances on a single host Link kopierenLink in die Zwischenablage kopiert!
If you install MariaDB or MySQL from packages, you can only run one of these services and only a single version of it on the same host. As an alternative, you can run the services in a container.
You can configure the following scenarios:
- You want to run multiple instances of MariaDB or MySQL on the same host.
- You want to run both MariaDB and MySQL on the same host.
Prerequisites
-
The
container-toolsmodule is installed.
Procedure
Use your Red Hat Customer Portal account to authenticate to the
registry.redhat.ioregistry:podman login registry.redhat.io
# podman login registry.redhat.ioCopy to Clipboard Copied! Toggle word wrap Toggle overflow Skip this step if you are already logged in to the container registry.
Run MySQL 8.0 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mysql_root_password> -p <host_port_1>:3306 rhel8/mysql-80
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mysql_root_password> -p <host_port_1>:3306 rhel8/mysql-80Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run MariaDB 10.5 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_2>:3306 rhel8/mariadb-105
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_2>:3306 rhel8/mariadb-105Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run MariaDB 10.11 in a container:
podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_3>:3306 rhel8/mariadb-1011
$ podman run -d --name <container_name> -e MYSQL_ROOT_PASSWORD=<mariadb_root_password> -p <host_port_3>:3306 rhel8/mariadb-1011Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
NoteThe container names and host ports of the two database servers must differ.
To ensure that clients can access the database server on the network, open the host ports in the firewall:
firewall-cmd --permanent --add-port={<host_port>/tcp,<host_port>/tcp,...} firewall-cmd --reload# firewall-cmd --permanent --add-port={<host_port>/tcp,<host_port>/tcp,...} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display information about running containers:
podman ps
$ podman psCopy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to the database server and log in as root:
mysql -u root -p -h localhost -P <host_port> --protocol tcp
# mysql -u root -p -h localhost -P <host_port> --protocol tcpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.3. Configuring MySQL Link kopierenLink in die Zwischenablage kopiert!
To configure the MySQL server for networking, use the following procedure.
Procedure
Edit the
[mysqld]section of the/etc/my.cnf.d/mysql-server.cnffile. You can set the following configuration directives:bind-address- is the address on which the server listens. Possible options are:- a host name
- an IPv4 address
- an IPv6 address
skip-networking- controls whether the server listens for TCP/IP connections. Possible values are:- 0 - to listen for all clients
- 1 - to listen for local clients only
-
port- the port on which MySQL listens for TCP/IP connections.
Restart the
mysqldservice:systemctl restart mysqld.service
# systemctl restart mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.4. Setting up TLS encryption on a MySQL server Link kopierenLink in die Zwischenablage kopiert!
By default, MySQL uses unencrypted connections. For secure connections, enable TLS support on the MariaDB server and configure your clients to establish encrypted connections.
7.3.4.1. Placing the CA certificate, server certificate, and private key on the MySQL server Link kopierenLink in die Zwischenablage kopiert!
Before you can enable TLS encryption on the MySQL server, store the certificate authority (CA) certificate, the server certificate, and the private key on the MySQL server.
Prerequisites
The following files in Privacy Enhanced Mail (PEM) format have been copied to the server:
-
The private key of the server:
server.example.com.key.pem -
The server certificate:
server.example.com.crt.pem -
The Certificate Authority (CA) certificate:
ca.crt.pem
For details about creating a private key and certificate signing request (CSR), as well as about requesting a certificate from a CA, see your CA’s documentation.
-
The private key of the server:
Procedure
Store the CA and server certificates in the
/etc/pki/tls/certs/directory:mv <path>/server.example.com.crt.pem /etc/pki/tls/certs/ mv <path>/ca.crt.pem /etc/pki/tls/certs/
# mv <path>/server.example.com.crt.pem /etc/pki/tls/certs/ # mv <path>/ca.crt.pem /etc/pki/tls/certs/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set permissions on the CA and server certificate that enable the MySQL server to read the files:
chmod 644 /etc/pki/tls/certs/server.example.com.crt.pem /etc/pki/tls/certs/ca.crt.pem
# chmod 644 /etc/pki/tls/certs/server.example.com.crt.pem /etc/pki/tls/certs/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow Because certificates are part of the communication before a secure connection is established, any client can retrieve them without authentication. Therefore, you do not need to set strict permissions on the CA and server certificate files.
Store the server’s private key in the
/etc/pki/tls/private/directory:mv <path>/server.example.com.key.pem /etc/pki/tls/private/
# mv <path>/server.example.com.key.pem /etc/pki/tls/private/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set secure permissions on the server’s private key:
chmod 640 /etc/pki/tls/private/server.example.com.key.pem chgrp mysql /etc/pki/tls/private/server.example.com.key.pem
# chmod 640 /etc/pki/tls/private/server.example.com.key.pem # chgrp mysql /etc/pki/tls/private/server.example.com.key.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow If unauthorized users have access to the private key, connections to the MySQL server are no longer secure.
Restore the SELinux context:
restorecon -Rv /etc/pki/tls/
# restorecon -Rv /etc/pki/tls/Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.4.2. Configuring TLS encryption on a MySQL server Link kopierenLink in die Zwischenablage kopiert!
By default, MySQL uses unencrypted connections. For more secure connections, you can enable Transport Layer Security (TLS) support on the MySQL server and configure your clients to establish encrypted connections.
Prerequisites
- You installed the MySQL server.
-
The
mysqldservice is running. The following files in Privacy Enhanced Mail (PEM) format exist on the server and are readable by the
mysqluser:-
The private key of the server:
/etc/pki/tls/private/server.example.com.key.pem -
The server certificate:
/etc/pki/tls/certs/server.example.com.crt.pem -
The Certificate Authority (CA) certificate
/etc/pki/tls/certs/ca.crt.pem
-
The private key of the server:
- The subject distinguished name (DN) or the subject alternative name (SAN) field in the server certificate matches the server’s host name.
Procedure
Create the
/etc/my.cnf.d/mysql-server-tls.cnffile:Add the following content to configure the paths to the private key, server and CA certificate:
[mysqld] ssl_key = /etc/pki/tls/private/server.example.com.key.pem ssl_cert = /etc/pki/tls/certs/server.example.com.crt.pem ssl_ca = /etc/pki/tls/certs/ca.crt.pem
[mysqld] ssl_key = /etc/pki/tls/private/server.example.com.key.pem ssl_cert = /etc/pki/tls/certs/server.example.com.crt.pem ssl_ca = /etc/pki/tls/certs/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you have a Certificate Revocation List (CRL), configure the MySQL server to use it:
ssl_crl = /etc/pki/tls/certs/example.crl.pem
ssl_crl = /etc/pki/tls/certs/example.crl.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Reject connection attempts without encryption. To enable this feature, append:
require_secure_transport = on
require_secure_transport = onCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Set the TLS versions the server should support. For example, to support only TLS 1.3, append:
tls_version = TLSv1.3
tls_version = TLSv1.3Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the server supports TLS 1.2 and TLS 1.3.
Restart the
mysqldservice:systemctl restart mysqld.service
# systemctl restart mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To simplify troubleshooting, perform the following steps on the MySQL server before you configure the local client to use TLS encryption:
Verify that MySQL now has TLS encryption enabled:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow If you configured the MySQL server to only support specific TLS versions, display the
tls_versionvariable:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that the server uses the correct CA certificate, server certificate, and private key files:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.4.3. Requiring TLS encrypted connections for specific user accounts Link kopierenLink in die Zwischenablage kopiert!
You can configure specific MySQL accounts to require TLS-encrypted connections to protect sensitive data transmission.
If you cannot configure on the server that a secure transport is required for all connections (require_secure_transport = on), configure individual user accounts to require TLS encryption.
Prerequisites
- The MySQL server has TLS support enabled.
- The user you configure to require secure transport exists.
- The CA certificate is stored on the client.
Procedure
Connect as an administrative user to the MySQL server:
mysql -u root -p -h server.example.com
# mysql -u root -p -h server.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow If your administrative user has no permissions to access the server remotely, perform the command on the MySQL server and connect to
localhost.Use the
REQUIRE SSLclause to enforce that a user must connect using a TLS-encrypted connection:MySQL [(none)]> ALTER USER 'example'@'%' REQUIRE SSL;
MySQL [(none)]> ALTER USER 'example'@'%' REQUIRE SSL;Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Connect to the server as the
exampleuser using TLS encryption:mysql -u example -p -h server.example.com
# mysql -u example -p -h server.example.com ... MySQL [(none)]>Copy to Clipboard Copied! Toggle word wrap Toggle overflow If no error is shown and you have access to the interactive MySQL console, the connection with TLS succeeds.
By default, the client automatically uses TLS encryption if the server provides it. Therefore, the
--ssl-ca=ca.crt.pemand--ssl-mode=VERIFY_IDENTITYoptions are not required, but improve the security because, with these options, the client verifies the identity of the server.Attempt to connect as the
exampleuser with TLS disabled:mysql -u example -p -h server.example.com --ssl-mode=DISABLED
# mysql -u example -p -h server.example.com --ssl-mode=DISABLED ERROR 1045 (28000): Access denied for user 'example'@'server.example.com' (using password: YES)Copy to Clipboard Copied! Toggle word wrap Toggle overflow The server rejected the login attempt because TLS is required for this user but disabled (
--ssl-mode=DISABLED).
7.3.5. Globally enabling TLS encryption with CA certificate validation in MySQL clients Link kopierenLink in die Zwischenablage kopiert!
If your MySQL server supports TLS encryption, configure your clients to establish only secure connections and to verify the server certificate. This procedure describes how to enable TLS support for all users on the server.
7.3.5.1. Configuring the MySQL client to use TLS encryption by default Link kopierenLink in die Zwischenablage kopiert!
On RHEL, you can globally configure that the MySQL client uses TLS encryption and verifies that the Common Name (CN) in the server certificate matches the hostname the user connects to. This prevents man-in-the-middle attacks.
Prerequisites
- The MySQL server has TLS support enabled.
-
The CA certificate is stored in the
/etc/pki/tls/certs/ca.crt.pemfile on the client.
Procedure
Create the
/etc/my.cnf.d/mysql-client-tls.cnffile with the following content:[client] ssl-mode=VERIFY_IDENTITY ssl-ca=/etc/pki/tls/certs/ca.crt.pem
[client] ssl-mode=VERIFY_IDENTITY ssl-ca=/etc/pki/tls/certs/ca.crt.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow These settings define that the MySQL client uses TLS encryption and that the client compares the hostname with the CN in the server certificate (
ssl-mode=VERIFY_IDENTITY). Additionally, it specifies the path to the CA certificate (ssl-ca).
Verification
Connect to the server using the hostname, and display the server status:
mysql -u root -p -h server.example.com -e status
# mysql -u root -p -h server.example.com -e status ... SSL: Cipher in use is TLS_AES_256_GCM_SHA384Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the
SSLentry containsCipher in use is…, the connection is encrypted.Note that the user you use in this command has permissions to authenticate remotely.
If the hostname you connect to does not match the hostname in the TLS certificate of the server, the
ssl-mode=VERIFY_IDENTITYparameter causes the connection to fail. For example, if you connect tolocalhost:mysql -u root -p -h localhost -e status
# mysql -u root -p -h localhost -e status ERROR 2026 (HY000): SSL connection error: error:0A000086:SSL routines::certificate verify failedCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.6. Backing up and restoring MySQL data with logical dumps Link kopierenLink in die Zwischenablage kopiert!
A logical backup of MySQL data consists of the SQL statements necessary to restore the data. The advantage of logical backup over physical backup is that the data can be restored on other hardware configurations and MySQL versions.
7.3.6.1. Performing a logical backup by using mysqldump Link kopierenLink in die Zwischenablage kopiert!
The mysqldump utility is a versatile backup tool that can export one or more databases. Its output is typically a file containing SQL statements designed to re-create the database structure and populate it with data, making it ideal for backups or server transfers.
To perform the mysqldump backup, you can use one of the following options:
- Back up one or more selected databases
- Back up all databases
- Back up a subset of tables from one database
Procedure
To dump a single database, run:
mysqldump [options] --databases db_name > backup-file.sql
# mysqldump [options] --databases db_name > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump multiple databases at once, run:
mysqldump [options] --databases db_name1 [db_name2 ...] > backup-file.sql
# mysqldump [options] --databases db_name1 [db_name2 ...] > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump all databases, run:
mysqldump [options] --all-databases > backup-file.sql
# mysqldump [options] --all-databases > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load one or more dumped full databases back into a server, run:
mysql < backup-file.sql
# mysql < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load a database to a remote MySQL server, run:
mysql --host=remote_host < backup-file.sql
# mysql --host=remote_host < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To dump a subset of tables from one database, add a list of the chosen tables at the end of the
mysqldumpcommand:mysqldump [options] db_name [tbl_name ...] > backup-file.sql
# mysqldump [options] db_name [tbl_name ...] > backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow To load a literal,subset of tables dumped from one database, run:
mysql db_name < backup-file.sql
# mysql db_name < backup-file.sqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteThe db_name database must exist at this point.
To see a list of the options that mysqldump supports, run:
mysqldump --help
$ mysqldump --helpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.7. Backing up and restoring MySQL data with physical copies Link kopierenLink in die Zwischenablage kopiert!
A physical backup of MySQL data contains file and directories that store the content. This method is typically faster and smaller in size.
7.3.7.1. Performing a file system backup on a MySQL server Link kopierenLink in die Zwischenablage kopiert!
You can create a file system backup of your MySQL server by copying data files, configuration files, and log files to a backup location.
Procedure
Stop the
mysqldservice:systemctl stop mysqld.service
# systemctl stop mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Copy the data files to the required location:
cp -r /var/lib/mysql /backup-location
# cp -r /var/lib/mysql /backup-locationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Copy the configuration files to the required location:
cp -r /etc/my.cnf /etc/my.cnf.d /backup-location/configuration
# cp -r /etc/my.cnf /etc/my.cnf.d /backup-location/configurationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Copy the log files to the required location:
cp /var/log/mysql/* /backup-location/logs
# cp /var/log/mysql/* /backup-location/logsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the
mysqldservice:systemctl start mysqld.service
# systemctl start mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow When loading the backed up data from the backup location to the
/var/lib/mysqldirectory, ensure thatmysql:mysqlis an owner of all data in/var/lib/mysql:chown -R mysql:mysql /var/lib/mysql
# chown -R mysql:mysql /var/lib/mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.8. Replicating MySQL with TLS encryption Link kopierenLink in die Zwischenablage kopiert!
You can set up MySQL replication with TLS encryption to create secure data replication between source and replica servers.
Replication itself is not a sufficient backup solution. Replication protects source servers against hardware failures, but it does not ensure protection against data loss.
7.3.8.1. Configuring a MySQL source server Link kopierenLink in die Zwischenablage kopiert!
You can set configuration options required for a MySQL source server to properly run and replicate all changes made on the database server through the TLS protocol.
Prerequisites
- The source server is installed.
The source server has TLS set up.
ImportantThe source and replica certificates must be signed by the same certificate authority.
Procedure
Include the following options in the
/etc/my.cnf.d/mysql-server.cnffile under the[mysqld]section:bind-address=source_ip_adressThis option is required for connections made from replicas to the source.
server-id=idThe id must be unique.
log_bin=path_to_source_server_logThis option defines a path to the binary log file of the MySQL source server. For example:
log_bin=/var/log/mysql/mysql-bin.log.gtid_mode=ONThis option enables global transaction identifiers (GTIDs) on the server.
enforce-gtid-consistency=ONThe server enforces GTID consistency by allowing execution of only statements that can be safely logged using a GTID.
Optional:
binlog_do_db=db_nameUse this option if you want to replicate only selected databases. To replicate more than one selected database, specify each of the databases separately:
binlog_do_db=db_name1 binlog_do_db=db_name2 binlog_do_db=db_name3
binlog_do_db=db_name1 binlog_do_db=db_name2 binlog_do_db=db_name3Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional:
binlog_ignore_db=db_nameUse this option to exclude a specific database from replication.
Restart the
mysqldservice:systemctl restart mysqld.service
# systemctl restart mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.8.2. Configuring a MySQL replica server Link kopierenLink in die Zwischenablage kopiert!
You can set configuration options required for a MySQL replica server to ensure a successful replication.
Prerequisites
- The replica server is installed.
The replica server has TLS set up.
ImportantThe source and replica certificates must be signed by the same certificate authority.
Procedure
Include the following options in the
/etc/my.cnf.d/mysql-server.cnffile under the[mysqld]section:server-id=idThe id must be unique.
relay-log=path_to_replica_server_logThe relay log is a set of log files created by the MySQL replica server during replication.
log_bin=path_to_replica_sever_logThis option defines a path to the binary log file of the MySQL replica server. For example:
log_bin=/var/log/mysql/mysql-bin.log.This option is not required in a replica but strongly recommended.
gtid_mode=ONThis option enables global transaction identifiers (GTIDs) on the server.
enforce-gtid-consistency=ONThe server enforces GTID consistency by allowing execution of only statements that can be safely logged using a GTID.
log-replica-updates=ONThis option ensures that updates received from the source server are logged in the replica’s binary log.
skip-replica-start=ONThis option ensures that the replica server does not start the replication threads when the replica server starts.
Optional:
binlog_do_db=db_nameUse this option if you want to replicate only certain databases. To replicate more than one database, specify each of the databases separately:
binlog_do_db=db_name1 binlog_do_db=db_name2 binlog_do_db=db_name3
binlog_do_db=db_name1 binlog_do_db=db_name2 binlog_do_db=db_name3Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional:
binlog_ignore_db=db_nameUse this option to exclude a specific database from replication.
Restart the
mysqldservice:systemctl restart mysqld.service
# systemctl restart mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.8.3. Creating a replication user on the MySQL source server Link kopierenLink in die Zwischenablage kopiert!
You must create a replication user with appropriate permissions on the MySQL source server to enable replica servers to connect and receive data changes.
Prerequisites
- The source server is installed and configured as described in Configuring a MySQL source server.
Procedure
Create a replication user:
mysql> CREATE USER 'replication_user'@'replica_server_hostname' IDENTIFIED WITH mysql_native_password BY 'password';
mysql> CREATE USER 'replication_user'@'replica_server_hostname' IDENTIFIED WITH mysql_native_password BY 'password';Copy to Clipboard Copied! Toggle word wrap Toggle overflow Grant the user replication permissions:
mysql> GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'replica_server_hostname';
mysql> GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'replica_server_hostname';Copy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the grant tables in the MySQL database:
mysql> FLUSH PRIVILEGES;
mysql> FLUSH PRIVILEGES;Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set the source server to read-only state:
mysql> SET @@GLOBAL.read_only = ON;
mysql> SET @@GLOBAL.read_only = ON;Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.8.4. Connecting the replica server to the source server Link kopierenLink in die Zwischenablage kopiert!
On the MySQL replica server, you must configure credentials and the address of the source server. Use the following procedure to implement the replica server.
Prerequisites
- The source server is installed and configured as described in Configuring a MySQL source server.
- The replica server is installed and configured as described in Configuring a MySQL replica server.
- You have created a replication user. See Creating a replication user on the MySQL source server.
Procedure
Set the replica server to read-only state:
mysql> SET @@GLOBAL.read_only = ON;
mysql> SET @@GLOBAL.read_only = ON;Copy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the replication source:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Start the replica thread in the MySQL replica server:
mysql> START REPLICA;
mysql> START REPLICA;Copy to Clipboard Copied! Toggle word wrap Toggle overflow Unset the read-only state on both the source and replica servers:
mysql> SET @@GLOBAL.read_only = OFF;
mysql> SET @@GLOBAL.read_only = OFF;Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Inspect the status of the replica server for debugging purposes:
mysql> SHOW REPLICA STATUS\G;
mysql> SHOW REPLICA STATUS\G;Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteIf the replica server fails to start or connect, you can skip a certain number of events following the binary log file position displayed in the output of the
SHOW MASTER STATUScommand. For example, skip the first event from the defined position:mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;Copy to Clipboard Copied! Toggle word wrap Toggle overflow and try to start the replica server again.
Optional: Stop the replica thread in the replica server:
mysql> STOP REPLICA;
mysql> STOP REPLICA;Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.3.8.5. Verifying replication on a MySQL server Link kopierenLink in die Zwischenablage kopiert!
You can verify that MySQL replication works correctly by creating test databases and checking replication status on source and replica servers.
Procedure
Create an example database on the source server:
mysql> CREATE DATABASE test_db_name;
mysql> CREATE DATABASE test_db_name;Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
Verify that the
test_db_namedatabase replicates on the replica server. Display status information about the binary log files of the MySQL server by executing the following command on either of the source or replica servers:
mysql> SHOW MASTER STATUS;
mysql> SHOW MASTER STATUS;Copy to Clipboard Copied! Toggle word wrap Toggle overflow The
Executed_Gtid_Setcolumn, which shows a set of GTIDs for transactions executed on the source, must not be empty.NoteThe same set of GTIDs is displayed in the
Executed_Gtid_Setrow when you use theSHOW REPLICA STATUSon the replica server.
7.3.9. Migrating to a RHEL 8 version of MySQL 8.0 Link kopierenLink in die Zwischenablage kopiert!
RHEL 7 contains MariaDB 5.5 as the default implementation of a server from the MySQL databases family. The Red Hat Software Collections offering for RHEL 7 provides MySQL 8.0 and several versions of MariaDB. RHEL 8 provides MySQL 8.0, MariaDB 10.3, and MariaDB 10.5.
This procedure describes migration from a Red Hat Software Collections version of MySQL 8.0 to a RHEL 8 version of MySQL 8.0 using the mysql_upgrade utility. The mysql_upgrade utility is provided by the mysql-server package.
In the Red Hat Software Collections version of MySQL, the source data directory is /var/opt/rh/rh-mysql80/lib/mysql/. In RHEL 8, MySQL data is stored in the /var/lib/mysql/ directory.
Prerequisites
- Before performing the upgrade, back up all your data stored in the MySQL databases.
Procedure
Ensure that the
mysql-serverpackage is installed on the RHEL 8 system:yum install mysql-server
# yum install mysql-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Ensure that the
mysqldservice is not running on either of the source and target systems at the time of copying data:systemctl stop mysqld.service
# systemctl stop mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Copy the data from the
/var/opt/rh/rh-mysql80/lib/mysql/directory on the RHEL 7 source system to the/var/lib/mysql/directory on the RHEL 8 target system. Set the appropriate permissions and SELinux context for copied files on the target system:
restorecon -vr /var/lib/mysql
# restorecon -vr /var/lib/mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Ensure that
mysql:mysqlis an owner of all data in the/var/lib/mysqldirectory:chown -R mysql:mysql /var/lib/mysql
# chown -R mysql:mysql /var/lib/mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the MySQL server on the target system:
systemctl start mysqld.service
# systemctl start mysqld.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note: In earlier versions of MySQL, the
mysql_upgradecommand was needed to check and repair internal tables. This is now done automatically when you start the server.
7.3.10. Developing MySQL client applications Link kopierenLink in die Zwischenablage kopiert!
Red Hat recommends developing your MySQL client applications against the MariaDB client library. The communication protocol between client and server is compatible between MariaDB and MySQL. The MariaDB client library works for most common MySQL scenarios, with the exception of a limited number of features specific to the MySQL implementation.
The development files and programs necessary to build applications against the MariaDB client library are provided by the mariadb-connector-c-devel package.
Instead of using a direct library name, use the mariadb_config program, which is distributed in the mariadb-connector-c-devel package. This program ensures that the correct build flags are returned.
7.4. Using PostgreSQL Link kopierenLink in die Zwischenablage kopiert!
The PostgreSQL server is an open source robust and highly-extensible database server based on the SQL language. The PostgreSQL server provides an object-relational database system that can manage extensive datasets and a high number of concurrent users.
The PostgreSQL server includes features for ensuring data integrity, building fault-tolerant environments and applications. With the PostgreSQL server, you can extend a database with your own data types, custom functions, or code from different programming languages without the need to recompile the database.
Learn how to install and configure PostgreSQL on a RHEL system, how to back up PostgreSQL data, and how to migrate from an earlier PostgreSQL version.
7.4.1. Installing PostgreSQL Link kopierenLink in die Zwischenablage kopiert!
RHEL 8 provides PostgreSQL 9.6 as the initial version of the Application Stream. Additional PostgreSQL versions are provided as modules with a shorter life cycle in minor releases of RHEL 8.
In RHEL 8, the PostgreSQL is available in the following versions, each provided by a separate stream:
- PostgreSQL 10 - the default stream
- PostgreSQL 9.6
- PostgreSQL 12 - available since RHEL 8.1.1
- PostgreSQL 13 - available since RHEL 8.4
- PostgreSQL 15 - available since RHEL 8.8
- PostgreSQL 16 - available since RHEL 8.10
By design, it is impossible to install more than one version (stream) of the same module in parallel. Therefore, you must choose only one of the available streams from the postgresql module. You can use different versions of the PostgreSQL database server in containers, see Running multiple PostgreSQL versions in containers.
For information about using module streams, see Installing, managing, and removing user-space components.
Procedure
Install the PostgreSQL server packages by selecting a stream (version) from the
postgresqlmodule and specifying the server profile. For example:yum module install postgresql:16/server
# yum module install postgresql:16/serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow The
postgressuperuser is created automatically.Initialize the database cluster:
postgresql-setup --initdb
# postgresql-setup --initdbCopy to Clipboard Copied! Toggle word wrap Toggle overflow Red Hat recommends storing the data in the default
/var/lib/pgsql/datadirectory.Start the
postgresqlservice:systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
postgresqlservice to start at boot:systemctl enable postgresql.service
# systemctl enable postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.2. Using containers to run multiple PostgreSQL instances on a single host Link kopierenLink in die Zwischenablage kopiert!
To run different versions of PostgreSQL on the same host, run them in containers because you cannot install multiple versions (streams) of the same module in parallel.
This procedure includes PostgreSQL 13 and PostgreSQL 15 as examples but you can use any PostgreSQL container version available in the Red Hat Ecosystem Catalog.
Prerequisites
-
The
container-toolsmodule is installed.
Procedure
Use your Red Hat Customer Portal account to authenticate to the
registry.redhat.ioregistry:podman login registry.redhat.io
# podman login registry.redhat.ioCopy to Clipboard Copied! Toggle word wrap Toggle overflow Skip this step if you are already logged in to the container registry.
Run PostgreSQL 13 in a container:
podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_1>:5432 rhel8/postgresql-13
$ podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_1>:5432 rhel8/postgresql-13Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run PostgreSQL 15 in a container:
podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_2>:5432 rhel8/postgresql-15
$ podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_2>:5432 rhel8/postgresql-15Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
Run PostgreSQL 16 in a container:
podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_3>:5432 rhel8/postgresql-16
$ podman run -d --name <container_name> -e POSTGRESQL_USER=<user_name> -e POSTGRESQL_PASSWORD=<password> -e POSTGRESQL_DATABASE=<database_name> -p <host_port_3>:5432 rhel8/postgresql-16Copy to Clipboard Copied! Toggle word wrap Toggle overflow For more information about the usage of this container image, see the Red Hat Ecosystem Catalog.
NoteThe container names and host ports of the two database servers must differ.
To ensure that clients can access the database server on the network, open the host ports in the firewall:
firewall-cmd --permanent --add-port={<host_port_1>/tcp,<host_port_2>/tcp,...} firewall-cmd --reload# firewall-cmd --permanent --add-port={<host_port_1>/tcp,<host_port_2>/tcp,...} # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display information about running containers:
podman ps
$ podman psCopy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to the database server and log in as root:
psql -u postgres -p -h localhost -P <host_port> --protocol tcp
# psql -u postgres -p -h localhost -P <host_port> --protocol tcpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.3. Creating PostgreSQL users Link kopierenLink in die Zwischenablage kopiert!
You can create PostgreSQL users with specific permissions to manage database access and control user privileges for secure database administration.
PostgreSQL users are of the following types:
-
The
postgresUNIX system user - should be used only to run the PostgreSQL server and client applications, such aspg_dump. Do not use thepostgressystem user for any interactive work on PostgreSQL administration, such as database creation and user management. -
A database superuser - the default
postgresPostgreSQL superuser is not related to thepostgressystem user. You can limit access of thepostgressuperuser in thepg_hba.conffile, otherwise no other permission limitations exist. You can also create other database superusers. A role with specific database access permissions:
- A database user - has a permission to log in by default
- A group of users - enables managing permissions for the group as a whole
Roles can own database objects (for example, tables and functions) and can assign object privileges to other roles using SQL commands.
Standard database management privileges include SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGE.
Role attributes are special privileges, such as LOGIN, SUPERUSER, CREATEDB, and CREATEROLE.
Red Hat recommends performing most tasks as a role that is not a superuser. A common practice is to create a role that has the CREATEDB and CREATEROLE privileges and use this role for all routine management of databases and roles.
Prerequisites
- The PostgreSQL server is installed.
- The database cluster is initialized.
Procedure
To create a user, set a password for the user, and assign the user the
CREATEROLEandCREATEDBpermissions:postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd' CREATEROLE CREATEDB;
postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd' CREATEROLE CREATEDB;Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace mydbuser with the username and mypasswd with the user’s password.
Example 7.1. Initializing, creating, and connecting to a PostgreSQL database
This example demonstrates how to initialize a PostgreSQL database, create a database user with routine database management privileges, and how to create a database that is accessible from any system account through the database user with management privileges.
Install the PosgreSQL server:
yum module install postgresql:13/server
# yum module install postgresql:13/serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Initialize the database cluster:
postgresql-setup --initdb
# postgresql-setup --initdb * Initializing database in '/var/lib/pgsql/data' * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.logCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the password hashing algorithm to
scram-sha-256.In the
/var/lib/pgsql/data/postgresql.conffile, change the following line:#password_encryption = md5 # md5 or scram-sha-256
#password_encryption = md5 # md5 or scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow to:
password_encryption = scram-sha-256
password_encryption = scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow In the
/var/lib/pgsql/data/pg_hba.conffile, change the following line for the IPv4 local connections:host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 identCopy to Clipboard Copied! Toggle word wrap Toggle overflow to:
host all all 127.0.0.1/32 scram-sha-256
host all all 127.0.0.1/32 scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Start the postgresql service:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Log in as the system user named
postgres:su - postgres
# su - postgresCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the PostgreSQL interactive terminal:
psql
$ psql psql (13.7) Type "help" for help. postgres=#Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Obtain information about the current database connection:
postgres=# \conninfo You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".
postgres=# \conninfo You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a user named
mydbuser, set a password formydbuser, and assignmydbusertheCREATEROLEandCREATEDBpermissions:postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd' CREATEROLE CREATEDB; CREATE ROLE
postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd' CREATEROLE CREATEDB; CREATE ROLECopy to Clipboard Copied! Toggle word wrap Toggle overflow The
mydbuseruser now can perform routine database management operations: create databases and manage user indexes.Log out of the interactive terminal by using the
\qmeta command:postgres=# \q
postgres=# \qCopy to Clipboard Copied! Toggle word wrap Toggle overflow Log out of the
postgresuser session:logout
$ logoutCopy to Clipboard Copied! Toggle word wrap Toggle overflow Log in to the PostgreSQL terminal as
mydbuser, specify the hostname, and connect to the defaultpostgresdatabase, which was created during initialization:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a database named
mydatabase:postgres=> CREATE DATABASE mydatabase; CREATE DATABASE postgres=>
postgres=> CREATE DATABASE mydatabase; CREATE DATABASE postgres=>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Log out of the session:
postgres=# \q
postgres=# \qCopy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to mydatabase as
mydbuser:psql -U mydbuser -h 127.0.0.1 -d mydatabase
# psql -U mydbuser -h 127.0.0.1 -d mydatabase Password for user mydbuser: psql (13.7) Type "help" for help. mydatabase=>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Obtain information about the current database connection:
mydatabase=> \conninfo You are connected to database "mydatabase" as user "mydbuser" on host "127.0.0.1" at port "5432".
mydatabase=> \conninfo You are connected to database "mydatabase" as user "mydbuser" on host "127.0.0.1" at port "5432".Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.4. Configuring PostgreSQL Link kopierenLink in die Zwischenablage kopiert!
You can configure PostgreSQL by editing the configuration files in the database cluster directory to set database parameters, authentication, and client access. By default, PostgreSQL uses the /var/lib/pgsql/data/ directory.
PostgreSQL configuration consists of the following files:
-
postgresql.conf- is used for setting the database cluster parameters. -
postgresql.auto.conf- holds basic PostgreSQL settings similarly topostgresql.conf. However, this file is under the server control. It is edited by theALTER SYSTEMqueries, and cannot be edited manually. -
pg_ident.conf- is used for mapping user identities from external authentication mechanisms into the PostgreSQL user identities. -
pg_hba.conf- is used for configuring client authentication for PostgreSQL databases.
To change the PostgreSQL configuration, use the following procedure.
Procedure
Edit the
/var/lib/pgsql/data/postgresql.conffile and configure basic settings of the database cluster parameters, for example:log_connections = yes log_destination = 'syslog' search_path = '"$user", public' shared_buffers = 128MB password_encryption = scram-sha-256
log_connections = yes log_destination = 'syslog' search_path = '"$user", public' shared_buffers = 128MB password_encryption = scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Edit the
/var/lib/pgsql/data/pg_hba.conffile and configure client authentication, for example:TYPE DATABASE USER ADDRESS METHOD
# TYPE DATABASE USER ADDRESS METHOD local all all trust host postgres all 192.168.93.0/24 ident host all all .example.com scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
postgresqlservice so that the changes become effective:systemctl restart postgresql.service
# systemctl restart postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.5. Configuring TLS encryption on a PostgreSQL server Link kopierenLink in die Zwischenablage kopiert!
By default, PostgreSQL uses unencrypted connections. For more secure connections, you can enable Transport Layer Security (TLS) support on the PostgreSQL server and configure your clients to establish encrypted connections.
Prerequisites
- The PostgreSQL server is installed.
- The database cluster is initialized.
Procedure
Install the OpenSSL library:
yum install openssl
# yum install opensslCopy to Clipboard Copied! Toggle word wrap Toggle overflow Generate a TLS certificate and a key:
openssl req -new -x509 -days 365 -nodes -text -out server.crt \ -keyout server.key -subj "/CN=dbhost.yourdomain.com"
# openssl req -new -x509 -days 365 -nodes -text -out server.crt \ -keyout server.key -subj "/CN=dbhost.yourdomain.com"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace dbhost.yourdomain.com with your database host and domain name.
Copy your signed certificate and your private key to the required locations on the database server:
cp server.{key,crt} /var/lib/pgsql/data/.# cp server.{key,crt} /var/lib/pgsql/data/.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Change the owner and group ownership of the signed certificate and your private key to the
postgresuser:chown postgres:postgres /var/lib/pgsql/data/server.{key,crt}# chown postgres:postgres /var/lib/pgsql/data/server.{key,crt}Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restrict the permissions for your private key so that it is readable only by the owner:
chmod 0400 /var/lib/pgsql/data/server.key
# chmod 0400 /var/lib/pgsql/data/server.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the password hashing algorithm to
scram-sha-256by changing the following line in the/var/lib/pgsql/data/postgresql.conffile:#password_encryption = md5 # md5 or scram-sha-256
#password_encryption = md5 # md5 or scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow to:
password_encryption = scram-sha-256
password_encryption = scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Configure PostgreSQL to use SSL/TLS by changing the following line in the
/var/lib/pgsql/data/postgresql.conffile:#ssl = off
#ssl = offCopy to Clipboard Copied! Toggle word wrap Toggle overflow to:
ssl=on
ssl=onCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restrict access to all databases to accept only connections from clients using TLS by changing the following line for the IPv4 local connections in the
/var/lib/pgsql/data/pg_hba.conffile:host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 identCopy to Clipboard Copied! Toggle word wrap Toggle overflow to:
hostssl all all 127.0.0.1/32 scram-sha-256
hostssl all all 127.0.0.1/32 scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Alternatively, you can restrict access for a single database and a user by adding the following new line:
hostssl mydatabase mydbuser 127.0.0.1/32 scram-sha-256
hostssl mydatabase mydbuser 127.0.0.1/32 scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace mydatabase with the database name and mydbuser with the username.
Make the changes effective by restarting the
postgresqlservice:systemctl restart postgresql.service
# systemctl restart postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
To manually verify that the connection is encrypted:
Connect to the PostgreSQL database as the mydbuser user, specify the hostname and the database name:
psql -U mydbuser -h 127.0.0.1 -d mydatabase
$ psql -U mydbuser -h 127.0.0.1 -d mydatabase Password for user mydbuser:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace mydatabase with the database name and mydbuser with the username.
Obtain information about the current database connection:
mydbuser=> \conninfo You are connected to database "mydatabase" as user "mydbuser" on host "127.0.0.1" at port "5432". SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
mydbuser=> \conninfo You are connected to database "mydatabase" as user "mydbuser" on host "127.0.0.1" at port "5432". SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)Copy to Clipboard Copied! Toggle word wrap Toggle overflow
You can write a simple application that verifies whether a connection to PostgreSQL is encrypted. This example demonstrates such an application written in C that uses the
libpqclient library, which is provided by thelibpq-develpackage:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace mypassword with the password, mydatabase with the database name, and mydbuser with the username.
NoteYou must load the
pqlibraries for compilation by using the-lpqoption. For example, to compile the application by using the GCC compiler:gcc source_file.c -lpq -o myapplication
$ gcc source_file.c -lpq -o myapplicationCopy to Clipboard Copied! Toggle word wrap Toggle overflow where the source_file.c contains the example code above, and myapplication is the name of your application for verifying secured PostgreSQL connection.
Example 7.2. Initializing, creating, and connecting to a PostgreSQL database using TLS encryption
This example demonstrates how to initialize a PostgreSQL database, create a database user and a database, and how to connect to the database using a secured connection.
Install the PosgreSQL server:
yum module install postgresql:13/server
# yum module install postgresql:13/serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Initialize the database cluster:
postgresql-setup --initdb
# postgresql-setup --initdb * Initializing database in '/var/lib/pgsql/data' * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.logCopy to Clipboard Copied! Toggle word wrap Toggle overflow Install the OpenSSL library:
yum install openssl
# yum install opensslCopy to Clipboard Copied! Toggle word wrap Toggle overflow Generate a TLS certificate and a key:
openssl req -new -x509 -days 365 -nodes -text -out server.crt \ -keyout server.key -subj "/CN=dbhost.yourdomain.com"
# openssl req -new -x509 -days 365 -nodes -text -out server.crt \ -keyout server.key -subj "/CN=dbhost.yourdomain.com"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace dbhost.yourdomain.com with your database host and domain name.
Copy your signed certificate and your private key to the required locations on the database server:
cp server.{key,crt} /var/lib/pgsql/data/.# cp server.{key,crt} /var/lib/pgsql/data/.Copy to Clipboard Copied! Toggle word wrap Toggle overflow Change the owner and group ownership of the signed certificate and your private key to the
postgresuser:chown postgres:postgres /var/lib/pgsql/data/server.{key,crt}# chown postgres:postgres /var/lib/pgsql/data/server.{key,crt}Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restrict the permissions for your private key so that it is readable only by the owner:
chmod 0400 /var/lib/pgsql/data/server.key
# chmod 0400 /var/lib/pgsql/data/server.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the password hashing algorithm to
scram-sha-256. In the/var/lib/pgsql/data/postgresql.conffile, change the following line:#password_encryption = md5 # md5 or scram-sha-256
#password_encryption = md5 # md5 or scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow to:
password_encryption = scram-sha-256
password_encryption = scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Configure PostgreSQL to use SSL/TLS. In the
/var/lib/pgsql/data/postgresql.conffile, change the following line:#ssl = off
#ssl = offCopy to Clipboard Copied! Toggle word wrap Toggle overflow to:
ssl=on
ssl=onCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the
postgresqlservice:systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Log in as the system user named
postgres:su - postgres
# su - postgresCopy to Clipboard Copied! Toggle word wrap Toggle overflow Start the PostgreSQL interactive terminal as the
postgresuser:psql -U postgres
$ psql -U postgres psql (13.7) Type "help" for help. postgres=#Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a user named
mydbuserand set a password formydbuser:postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd'; CREATE ROLE postgres=#
postgres=# CREATE USER mydbuser WITH PASSWORD 'mypasswd'; CREATE ROLE postgres=#Copy to Clipboard Copied! Toggle word wrap Toggle overflow Create a database named
mydatabase:postgres=# CREATE DATABASE mydatabase; CREATE DATABASE postgres=#
postgres=# CREATE DATABASE mydatabase; CREATE DATABASE postgres=#Copy to Clipboard Copied! Toggle word wrap Toggle overflow Grant all permissions to the
mydbuseruser:postgres=# GRANT ALL PRIVILEGES ON DATABASE mydatabase TO mydbuser; GRANT postgres=#
postgres=# GRANT ALL PRIVILEGES ON DATABASE mydatabase TO mydbuser; GRANT postgres=#Copy to Clipboard Copied! Toggle word wrap Toggle overflow Log out of the interactive terminal:
postgres=# \q
postgres=# \qCopy to Clipboard Copied! Toggle word wrap Toggle overflow Log out of the
postgresuser session:logout
$ logoutCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restrict access to all databases to accept only connections from clients using TLS by changing the following line for the IPv4 local connections in the
/var/lib/pgsql/data/pg_hba.conffile:host all all 127.0.0.1/32 ident
host all all 127.0.0.1/32 identCopy to Clipboard Copied! Toggle word wrap Toggle overflow to:
hostssl all all 127.0.0.1/32 scram-sha-256
hostssl all all 127.0.0.1/32 scram-sha-256Copy to Clipboard Copied! Toggle word wrap Toggle overflow Make the changes effective by restarting the
postgresqlservice:systemctl restart postgresql.service
# systemctl restart postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to the PostgreSQL database as the
mydbuseruser, specify the hostname and the database name:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.6. Backing up and restoring PostgreSQL data with logical dumps Link kopierenLink in die Zwischenablage kopiert!
A logical backup of PostgreSQL data consists of the SQL statements necessary to restore the data. The advantage of logical backup over physical backup is that the data can be restored on other hardware configurations and PostgreSQL versions.
The SQL dump method is based on generating a dump file with SQL commands. When a dump is uploaded back to the database server, it recreates the database in the same state as it was at the time of the dump.
The SQL dump is ensured by the following PostgreSQL client applications:
- pg_dump dumps a single database without cluster-wide information about roles or tablespaces
- pg_dumpall dumps each database in a given cluster and preserves cluster-wide data, such as role and tablespace definitions.
By default, the pg_dump and pg_dumpall commands write their results into the standard output. To store the dump in a file, redirect the output to an SQL file. The resulting SQL file can be either in a text format or in other formats that allow for parallelism and for more detailed control of object restoration.
You can perform the SQL dump from any remote host that has access to the database.
7.4.6.1. Advantages and disadvantages of an SQL dump Link kopierenLink in die Zwischenablage kopiert!
SQL dumps are text files containing a database’s structure and data in the form of SQL statements.
Advantages:
- An SQL dump is the only PostgreSQL backup method that is not server version-specific. The output of the pg_dump utility can be reloaded into later versions of PostgreSQL, which is not possible for file system level backups or continuous archiving.
- An SQL dump is the only method that works when transferring a database to a different machine architecture, such as going from a 32-bit to a 64-bit server.
- An SQL dump provides internally consistent dumps. A dump represents a snapshot of the database at the time pg_dump began running.
- The pg_dump utility does not block other operations on the database when it is running.
Disadvantage:
- An SQL dump takes more time compared to a file system level backup.
7.4.6.2. Backing up a single PostgreSQL database by using pg_dump Link kopierenLink in die Zwischenablage kopiert!
You can create a backup of a single PostgreSQL database by using the pg_dump utility to export the database structure and data to a file.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Dump a database without cluster-wide information:
pg_dump <db_name> > <dump_file>
$ pg_dump <db_name> > <dump_file>Copy to Clipboard Copied! Toggle word wrap Toggle overflow To specify which database server
pg_dumpwill contact, use the following command-line options:The
-hoption to define the host.The default host is either the local host or what is specified by the
PGHOSTenvironment variable.The
-poption to define the port.The default port is indicated by the
PGPORTenvironment variable or the compiled-in default.
7.4.6.3. Restoring a single PostgreSQL database by using pg_dump Link kopierenLink in die Zwischenablage kopiert!
You can restore a PostgreSQL database from an SQL dump file by using the pg_restore utility to recreate the database structure and data.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Create a new database:
createdb <db_name>
$ createdb <db_name>Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Verify that all users who own objects or were granted permissions on objects in the dumped database already exist. If such users do not exist, the restore fails to recreate the objects with the original ownership and permissions.
Run the
psqlutility to restore a text file dump created by thepg_dumputility:psql <db_name> < <dump_file>
$ psql <db_name> < <dump_file>Copy to Clipboard Copied! Toggle word wrap Toggle overflow where
<dump_file>is the output of thepg_dumpcommand. To restore a non-text file dump, use thepg_restoreutility instead:pg_restore <non-plain_text_file>
$ pg_restore <non-plain_text_file>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.6.4. Backing up all databases on a PostgreSQL server by using pg_dumpall Link kopierenLink in die Zwischenablage kopiert!
You can create a backup of all databases on a PostgreSQL server by using the pg_dumpall utility to export all databases and cluster-wide data to a single file.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Dump all databases in the database cluster and preserve cluster-wide data:
pg_dumpall > <dump_file>
$ pg_dumpall > <dump_file>Copy to Clipboard Copied! Toggle word wrap Toggle overflow To specify which database server pg_dumpall will contact, use the following command-line options:
The
-hoption to define the host.The default host is either the local host or what is specified by the
PGHOSTenvironment variable.The
-poption to define the port.The default port is indicated by the
PGPORTenvironment variable or the compiled-in default.The
-loption to define the default database.This option enables you to choose a default database different from the
postgresdatabase created automatically during initialization.
7.4.6.5. Restoring all databases on a PostgreSQL server by using pg_dumpall Link kopierenLink in die Zwischenablage kopiert!
You can restore all databases on a PostgreSQL server from a pg_dumpall file by using the psql utility to recreate the entire database cluster.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
- Ensure that all users who own objects or were granted permissions on objects in the dumped databases already exist. If such users do not exist, the restore fails to recreate the objects with the original ownership and permissions.
Run the
psqlutility to restore a text file dump created by thepg_dumpallutility:psql < <dump_file>
$ psql < <dump_file>Copy to Clipboard Copied! Toggle word wrap Toggle overflow where
<dump_file>is the output of thepg_dumpallcommand.
7.4.6.6. Handling SQL errors during restore Link kopierenLink in die Zwischenablage kopiert!
By default, the psql utility continues to execute if an SQL error occurs, causing the database to restore only partially. Alternatively, you can configure psql to stop on errors to ensure data integrity.
Prerequisites
-
You are logged in as the
postgressuperuser or a user with database administrator privileges.
Procedure
Make psql exit with an exit status of 3 if an SQL error occurs by setting the
ON_ERROR_STOPvariable:psql --set ON_ERROR_STOP=on dbname < dumpfile
$ psql --set ON_ERROR_STOP=on dbname < dumpfileCopy to Clipboard Copied! Toggle word wrap Toggle overflow Specify that the whole dump is restored as a single transaction so that the restore is either fully completed or canceled.
When restoring a text file dump using the
psqlutility:psql -1
$ psql -1Copy to Clipboard Copied! Toggle word wrap Toggle overflow When restoring a non-text file dump using the
pg_restoreutility:pg_restore -e
$ pg_restore -eCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that when using this approach, even a minor error can cancel a restore operation that has already run for many hours.
7.4.7. Backing up and restoring PostgreSQL data with physical copies Link kopierenLink in die Zwischenablage kopiert!
A physical backup of PostgreSQL data contains file and directories that store the content. This method is typically faster and smaller in size.
7.4.7.1. Performing a file system backup on a PostgreSQL server Link kopierenLink in die Zwischenablage kopiert!
You can create a file system backup of your PostgreSQL server by copying the data directory while the service is stopped for faster backup operations.
Limitations of a file system level backup compared to other PostgreSQL backup methods:
- File system level backup is specific to an architecture and a RHEL major version. For example, you cannot use this method to backup your data on RHEL 7 and restore it on RHEL 8.
- The database service must be stopped before backing up and restoring data.
- Backing up and restoring certain individual files or tables is impossible.
Procedure
Stop the postgresql service:
systemctl stop postgresql.service
# systemctl stop postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Use any method to create a file system backup, for example a
tararchive:tar -cf backup.tar /var/lib/pgsql/data/
$ tar -cf backup.tar /var/lib/pgsql/data/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Start the postgresql service:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.8. Backing up and restoring PostgreSQL data with continuous archiving Link kopierenLink in die Zwischenablage kopiert!
You can use continuous archiving to create robust PostgreSQL backups by combining WAL files with base backups for point-in-time recovery and high availability.
PostgreSQL records every change to the database’s data files to a write-ahead log (WAL) file that is available in the pg_wal/ subdirectory of the cluster’s data directory. This log is intended primarily for a crash recovery. After a crash, you can use log entries made since the last checkpoint to restore the database to a consistent state.
The continuous archiving method, also known as an online backup, combines the WAL files with a copy of the database cluster in the form of a base backup performed on a running server or a file system level backup.
If a database recovery is needed, you can restore the database from the copy of the database cluster and then replay log from the backed up WAL files to bring the system to the current state.
With the continuous archiving method, you must keep a continuous sequence of all archived WAL files that extends at minimum back to the start time of your last base backup. Therefore the ideal frequency of base backups depends on:
- The storage volume available for archived WAL files.
- The maximum possible duration of data recovery in situations when recovery is necessary. In cases with a long period since the last backup, the system replays more WAL segments, and the recovery therefore takes more time.
You cannot use pg_dump and pg_dumpall SQL dumps as a part of a continuous archiving backup solution. SQL dumps produce logical backups and do not contain enough information to be used by a WAL replay.
7.4.8.1. Advantages and disadvantages of continuous archiving Link kopierenLink in die Zwischenablage kopiert!
Continuous archiving is a feature that provides a robust strategy for data backup, high availability, and point-in-time recovery (PITR) by continuously saving the database’s transaction log files.
Advantages:
- With the continuous backup method, it is possible to use a base backup that is not entirely consistent because any internal inconsistency in the backup is corrected by the log replay. Therefore you can perform a base backup on a running PostgreSQL server.
-
A file system snapshot is not needed;
taror a similar archiving utility is sufficient. - Continuous backup can be achieved by continuing to archive the WAL files because the sequence of WAL files for the log replay can be indefinitely long. This is particularly valuable for large databases.
- Continuous backup supports point-in-time recovery. It is not necessary to replay the WAL entries to the end. The replay can be stopped at any point and the database can be restored to its state at any time since the base backup was taken.
- If the series of WAL files are continuously available to another machine that has been loaded with the same base backup file, it is possible to restore the other machine with a nearly-current copy of the database at any point.
Disadvantages:
- Continuous backup method supports only restoration of an entire database cluster, not a subset.
- Continuous backup requires extensive archival storage.
7.4.8.2. Setting up WAL archiving Link kopierenLink in die Zwischenablage kopiert!
You can enable write ahead log (WAL) archiving on your PostgreSQL server to capture and save WAL segment files for backup and point-in-time recovery purposes.
A running PostgreSQL server produces a sequence of WAL records. The server physically divides this sequence into WAL segment files, which are given numeric names that reflect their position in the WAL sequence. Without WAL archiving, the segment files are reused and renamed to higher segment numbers.
When archiving WAL data, the contents of each segment file are captured and saved at a new location before the segment file is reused. You have multiple options where to save the content, such as an NFS-mounted directory on another machine, a tape drive, or a CD.
Note that WAL records do not include changes to configuration files.
Procedure
In the
/var/lib/pgsql/data/postgresql.conffile:-
Set the
wal_levelconfiguration parameter toreplicaor higher. -
Set the
archive_modeparameter toon. Specify the shell command in the
archive_commandconfiguration parameter. You can use thecpcommand, another command, or a shell script.For example:
archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
archive_command = 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'Copy to Clipboard Copied! Toggle word wrap Toggle overflow where the
%pparameter is replaced by the relative path to the file to archive and the%fparameter is replaced by the file name.This command copies archivable WAL segments to the
/mnt/server/archivedir/directory. After replacing the%pand%fparameters, the executed command looks as follows:test ! -f /mnt/server/archivedir/00000001000000A900000065 && cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065
test ! -f /mnt/server/archivedir/00000001000000A900000065 && cp pg_wal/00000001000000A900000065 /mnt/server/archivedir/00000001000000A900000065Copy to Clipboard Copied! Toggle word wrap Toggle overflow A similar command is generated for each new file that is archived.
NoteThe archive command is executed only on completed WAL segments. A server that generates little WAL traffic can have a substantial delay between the completion of a transaction and its safe recording in archive storage. To limit how old unarchived data can be, you can:
-
Set the
archive_timeoutparameter to force the server to switch to a new WAL segment file with a given frequency. -
Use the
pg_switch_walparameter to force a segment switch to ensure that a transaction is archived immediately after it finishes.
-
Set the
-
Set the
Restart the
postgresqlservice to enable the changes:systemctl restart postgresql.service
# systemctl restart postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow - Test your archive command and ensure it does not overwrite an existing file and that it returns a nonzero exit status if it fails.
- To protect your data, ensure that the segment files are archived into a directory that does not have group or world read access.
7.4.8.3. Making a base backup Link kopierenLink in die Zwischenablage kopiert!
You can create a PostgreSQL base backup by using the pg_basebackup utility to capture a consistent snapshot of your database for backup and recovery purposes.
The base backup process creates a backup history file that is stored into the WAL archive area and is named after the first WAL segment file that you need for the base backup.
The backup history file is a small text file containing the starting and ending times, and WAL segments of the backup. If you used the label string to identify the associated dump file, you can use the backup history file to determine which dump file to restore.
Consider keeping several backup sets to be certain that you can recover your data.
Prerequisites
-
You are logged in as the
postgressuperuser, a user with database administrator privileges, or another user with at leastREPLICATIONpermissions. - You must keep all the WAL segment files generated during and after the base backup.
Procedure
Use the
pg_basebackuputility to perform the base backup.To create a base backup as individual files (plain format):
pg_basebackup -D backup_directory -Fp
$ pg_basebackup -D backup_directory -FpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Replace backup_directory with your chosen backup location.
If you use tablespaces and perform the base backup on the same host as the server, you must also use the
--tablespace-mappingoption, otherwise the backup will fail upon an attempt to write the backup to the same location.To create a base backup as a
tararchive (tarand compressed format):pg_basebackup -D backup_directory -Ft -z
$ pg_basebackup -D backup_directory -Ft -zCopy to Clipboard Copied! Toggle word wrap Toggle overflow Replace backup_directory with your chosen backup location.
To restore such data, you must manually extract the files in the correct locations.
To specify which database server pg_basebackup will contact, use the following command-line options:
The
-hoption to define the host.The default host is either the local host or a host specified by the
PGHOSTenvironment variable.The
-poption to define the port.The default port is indicated by the
PGPORTenvironment variable or the compiled-in default.
- After the base backup process is complete, safely archive the copy of the database cluster and the WAL segment files used during the backup, which are specified in the backup history file.
- Delete WAL segments numerically lower than the WAL segment files used in the base backup because these are older than the base backup and no longer needed for a restore.
7.4.8.4. Restoring the database using a continuous archive backup Link kopierenLink in die Zwischenablage kopiert!
You can restore a PostgreSQL database by restoring the base backup and applying archived WAL files for point-in-time recovery.
Procedure
Stop the server:
systemctl stop postgresql.service
# systemctl stop postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Copy the necessary data to a temporary location.
Preferably, copy the whole cluster data directory and any tablespaces. Note that this requires enough free space on your system to hold two copies of your existing database.
If you do not have enough space, save the contents of the cluster’s
pg_waldirectory, which can contain logs that were not archived before the system went down.- Remove all existing files and subdirectories under the cluster data directory and under the root directories of any tablespaces you are using.
Restore the database files from your base backup.
Ensure that:
-
The files are restored with the correct ownership (the database system user, not
root). - The files are restored with the correct permissions.
-
The symbolic links in the
pg_tblspc/subdirectory are restored correctly.
-
The files are restored with the correct ownership (the database system user, not
Remove any files present in the
pg_wal/subdirectory.These files resulted from the base backup and are therefore obsolete. If you did not archive
pg_wal/, recreate it with proper permissions.-
Copy any unarchived WAL segment files that you saved in step 2 into
pg_wal/. Create the
recovery.confrecovery command file in the cluster data directory and specify the shell command in therestore_commandconfiguration parameter. You can use thecpcommand, another command, or a shell script. For example:restore_command = 'cp /mnt/server/archivedir/%f "%p"'
restore_command = 'cp /mnt/server/archivedir/%f "%p"'Copy to Clipboard Copied! Toggle word wrap Toggle overflow Start the server:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow The server will enter the recovery mode and proceed to read through the archived WAL files that it needs.
If the recovery is terminated due to an external error, the server can be restarted and it will continue the recovery. When the recovery process is completed, the server renames
recovery.conftorecovery.done. This prevents the server from accidental re-entering the recovery mode after it starts normal database operations.Check the contents of the database to verify that the database has recovered into the required state.
If the database has not recovered into the required state, return to step 1. If the database has recovered into the required state, allow the users to connect by restoring the client authentication configuration in the
pg_hba.conffile.
7.4.9. Directly transferring a PostgreSQL database from one server to another Link kopierenLink in die Zwischenablage kopiert!
You can use the pg_dump and psql utilities to back up a PostgreSQL database and directly restore it on another PostgreSQL server. With this method you can transfer a database in a single step without intermediate files.
Prerequisites
-
You are logged in as the
postgresuser.
Procedure
Transfer a database from the source server to a destination server:
pg_dump -h <source_server> <db_name> | psql -h <destination_server> <db_name>
$ pg_dump -h <source_server> <db_name> | psql -h <destination_server> <db_name>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.10. Migrating to a RHEL 8 version of PostgreSQL Link kopierenLink in die Zwischenablage kopiert!
You can migrate your PostgreSQL databases to a RHEL 8 version of PostgreSQL by using the fast upgrade or dump and restore methods, depending on your specific requirements and constraints.
Red Hat Enterprise Linux 7 contains PostgreSQL 9.2 as the default version of the PostgreSQL server. In addition, several versions of PostgreSQL are provided as Software Collections for RHEL 7.
Red Hat Enterprise Linux 8 provides PostgreSQL 10 as the default postgresql stream, PostgreSQL 9.6, PostgreSQL 12, PostgreSQL 13, PostgreSQL 15, and PostgreSQL 16.
Users of PostgreSQL on Red Hat Enterprise Linux can use two migration paths for the database files:
The fast upgrade method is quicker than the dump and restore process. However, in certain cases, the fast upgrade does not work, and you can only use the dump and restore process. Such cases include:
- Cross-architecture upgrades
-
Systems using the
plpythonorplpython2extensions. Note that RHEL 8 AppStream repository includes only thepostgresql-plpython3package, not thepostgresql-plpython2package. - Fast upgrade is not supported for migration from Red Hat Software Collections versions of PostgreSQL.
As a prerequisite for migration to a later version of PostgreSQL, back up all your PostgreSQL databases.
Dumping the databases and performing backup of the SQL files is required for the dump and restore process and recommended for the fast upgrade method.
Before migrating to a later version of PostgreSQL, see the upstream compatibility notes for the version of PostgreSQL to which you want to migrate, and for all skipped PostgreSQL versions between the one you are migrating from and the target version.
7.4.10.1. Notable differences between PostgreSQL 15 and PostgreSQL 16 Link kopierenLink in die Zwischenablage kopiert!
PostgreSQL 16 introduced the following notable changes.
- The
postmastersbinary is no longer available -
PostgreSQL is no longer distributed with the
postmasterbinary. Users who start thepostgresqlserver by using the providedsystemdunit file (thesystemctl start postgres.servicecommand) are not affected by this change. If you previously started thepostgresqlserver directly through thepostmasterbinary, you must now use thepostgresbinary instead. - Documentation is no longer packaged
- PostgreSQL no longer provides documentation in PDF format within the package. Use the online documentation instead.
7.4.10.2. Notable differences between PostgreSQL 13 and PostgreSQL 15 Link kopierenLink in die Zwischenablage kopiert!
PostgreSQL 15 introduced the following backwards incompatible changes.
- Default permissions of the public schema
The default permissions of the public schema have been modified in PostgreSQL 15. Newly created users need to grant permission explicitly by using the
GRANT ALL ON SCHEMA public TO myuser;command.The following example works in PostgreSQL 13 and earlier:
postgres=# CREATE USER mydbuser; postgres=# \c postgres mydbuser postgres=$ CREATE TABLE mytable (id int);
postgres=# CREATE USER mydbuser; postgres=# \c postgres mydbuser postgres=$ CREATE TABLE mytable (id int);Copy to Clipboard Copied! Toggle word wrap Toggle overflow The following example works in PostgreSQL 15 and later:
postgres=# CREATE USER mydbuser; postgres=# GRANT ALL ON SCHEMA public TO mydbuser; postgres=# \c postgres mydbuser postgres=$ CREATE TABLE mytable (id int);
postgres=# CREATE USER mydbuser; postgres=# GRANT ALL ON SCHEMA public TO mydbuser; postgres=# \c postgres mydbuser postgres=$ CREATE TABLE mytable (id int);Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteEnsure that the
mydbuseraccess is configured appropriately in thepg_hba.conffile. See Creating PostgreSQL users for more information.PQsendQuery()no longer supported in pipeline mode-
Since PostgreSQL 15, the
libpqlibraryPQsendQuery()function is no longer supported in pipeline mode. Modify affected applications to use thePQsendQueryParams()function instead.
7.4.10.3. Fast upgrade using the pg_upgrade utility Link kopierenLink in die Zwischenablage kopiert!
As a system administrator, you can upgrade to the most recent version of PostgreSQL by using the fast upgrade method. To perform a fast upgrade, copy binary data files to the /var/lib/pgsql/data/ directory and use the pg_upgrade utility.
You can use this method for migrating data:
- From the RHEL 7 system version of PostgreSQL 9.2 to the RHEL 8 version of PostgreSQL 10
- From the RHEL 8 version of PostgreSQL 10 to a RHEL version of PostgreSQL 12
- From the RHEL 8 version of PostgreSQL 12 to a RHEL version of PostgreSQL 13
- From a RHEL version of PostgreSQL 13 to a RHEL version of PostgreSQL 15
- From a RHEL version of PostgreSQL 15 to a RHEL version of PostgreSQL 16
If you want to upgrade from an earlier postgresql stream within RHEL 8, follow the procedure described in Switching to a later stream and then migrate your PostgreSQL data.
For migrating between other combinations of PostgreSQL versions within RHEL, and for migration from the Red Hat Software Collections versions of PostgreSQL to RHEL, use Dump and restore upgrade.
The following procedure describes migration from the RHEL 7 system version of PostgreSQL 9.2 to a RHEL 8 version of PostgreSQL using the fast upgrade method.
Prerequisites
-
Before performing the upgrade, back up all your data stored in the PostgreSQL databases. By default, all data is stored in the
/var/lib/pgsql/data/directory on both the RHEL 7 and RHEL 8 systems.
Procedure
On the RHEL 8 system, enable the stream (version) to which you want to migrate:
yum module enable postgresql:stream
# yum module enable postgresql:streamCopy to Clipboard Copied! Toggle word wrap Toggle overflow Replace stream with the selected version of the PostgreSQL server.
You can omit this step if you want to use the default stream, which provides PostgreSQL 10.
On the RHEL 8 system, install the
postgresql-serverandpostgresql-upgradepackages:yum install postgresql-server postgresql-upgrade
# yum install postgresql-server postgresql-upgradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optionally, if you used any PostgreSQL server modules on RHEL 7, install them also on the RHEL 8 system in two versions, compiled both against PostgreSQL 9.2 (installed as the
postgresql-upgradepackage) and the target version of PostgreSQL (installed as thepostgresql-serverpackage). If you need to compile a third-party PostgreSQL server module, build it both against thepostgresql-develandpostgresql-upgrade-develpackages.Check the following items:
-
Basic configuration: On the RHEL 8 system, check whether your server uses the default
/var/lib/pgsql/datadirectory and the database is correctly initialized and enabled. In addition, the data files must be stored in the same path as mentioned in the/usr/lib/systemd/system/postgresql.servicefile. - PostgreSQL servers: Your system can run multiple PostgreSQL servers. Ensure that the data directories for all these servers are handled independently.
-
PostgreSQL server modules: Ensure that the PostgreSQL server modules that you used on RHEL 7 are installed on your RHEL 8 system as well. Note that plugins are installed in the
/usr/lib64/pgsql/directory (or in the/usr/lib/pgsql/directory on 32-bit systems).
-
Basic configuration: On the RHEL 8 system, check whether your server uses the default
Ensure that the
postgresqlservice is not running on either of the source and target systems at the time of copying data.systemctl stop postgresql.service
# systemctl stop postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Copy the database files from the source location to the
/var/lib/pgsql/data/directory on the RHEL 8 system. Perform the upgrade process by running the following command as the PostgreSQL user:
postgresql-setup --upgrade
# postgresql-setup --upgradeCopy to Clipboard Copied! Toggle word wrap Toggle overflow This launches the
pg_upgradeprocess in the background.In case of failure,
postgresql-setupprovides an informative error message.Copy the prior configuration from
/var/lib/pgsql/data-oldto the new cluster.Note that the fast upgrade does not reuse the prior configuration in the newer data stack and the configuration is generated from scratch. If you want to combine the old and new configurations manually, use the *.conf files in the data directories.
Start the new PostgreSQL server:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow Analyze the new database cluster.
For PostgreSQL 13 or earlier:
su postgres -c '~/analyze_new_cluster.sh'
su postgres -c '~/analyze_new_cluster.sh'Copy to Clipboard Copied! Toggle word wrap Toggle overflow For PostgreSQL 15 or later:
su postgres -c 'vacuumdb --all --analyze-in-stages'
su postgres -c 'vacuumdb --all --analyze-in-stages'Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteYou may need to use
ALTER COLLATION name REFRESH VERSION, see the upstream documentation for details.
If you want the new PostgreSQL server to be automatically started on boot, run:
systemctl enable postgresql.service
# systemctl enable postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.10.4. Dump and restore upgrade Link kopierenLink in die Zwischenablage kopiert!
When using the dump and restore upgrade, you must dump all databases contents into an SQL file dump file. Note that the dump and restore upgrade is slower than the fast upgrade method and it may require some manual fixing in the generated SQL file.
You can use this method for migrating data from:
- The Red Hat Enterprise Linux 7 system version of PostgreSQL 9.2
- Any earlier Red Hat Enterprise Linux 8 version of PostgreSQL
An earlier or equal version of PostgreSQL from Red Hat Software Collections:
- PostgreSQL 9.2 (no longer supported)
- PostgreSQL 9.4 (no longer supported)
- PostgreSQL 9.6 (no longer supported)
- PostgreSQL 10
- PostgreSQL 12
- PostgreSQL 13
On RHEL 7 and RHEL 8 systems, PostgreSQL data is stored in the /var/lib/pgsql/data/ directory by default. In case of Red Hat Software Collections versions of PostgreSQL, the default data directory is /var/opt/rh/collection_name/lib/pgsql/data/ (with the exception of postgresql92, which uses the /opt/rh/postgresql92/root/var/lib/pgsql/data/ directory).
If you want to upgrade from an earlier postgresql stream within RHEL 8, follow the procedure described in Switching to a later stream and then migrate your PostgreSQL data.
To perform the dump and restore upgrade, change the user to root.
The following procedure describes migration from the RHEL 7 system version of PostgreSQL 9.2 to a RHEL 8 version of PostgreSQL.
Procedure
On your RHEL 7 system, start the PostgreSQL 9.2 server:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow On the RHEL 7 system, dump all databases contents into the
pgdump_file.sqlfile:su - postgres -c "pg_dumpall > ~/pgdump_file.sql"
su - postgres -c "pg_dumpall > ~/pgdump_file.sql"Copy to Clipboard Copied! Toggle word wrap Toggle overflow Verify that the databases were dumped correctly:
su - postgres -c 'less "$HOME/pgdump_file.sql"'
su - postgres -c 'less "$HOME/pgdump_file.sql"'Copy to Clipboard Copied! Toggle word wrap Toggle overflow As a result, the path to the dumped sql file is displayed:
/var/lib/pgsql/pgdump_file.sql.On the RHEL 8 system, enable the stream (version) to which you wish to migrate:
yum module enable postgresql:stream
# yum module enable postgresql:streamCopy to Clipboard Copied! Toggle word wrap Toggle overflow Replace stream with the selected version of the PostgreSQL server.
You can omit this step if you want to use the default stream, which provides PostgreSQL 10.
On the RHEL 8 system, install the
postgresql-serverpackage:yum install postgresql-server
# yum install postgresql-serverCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optionally, if you used any PostgreSQL server modules on RHEL 7, install them also on the RHEL 8 system. If you need to compile a third-party PostgreSQL server module, build it against the
postgresql-develpackage.On the RHEL 8 system, initialize the data directory for the new PostgreSQL server:
postgresql-setup --initdb
# postgresql-setup --initdbCopy to Clipboard Copied! Toggle word wrap Toggle overflow On the RHEL 8 system, copy the
pgdump_file.sqlinto the PostgreSQL home directory, and check that the file was copied correctly:su - postgres -c 'test -e "$HOME/pgdump_file.sql" && echo exists'
su - postgres -c 'test -e "$HOME/pgdump_file.sql" && echo exists'Copy to Clipboard Copied! Toggle word wrap Toggle overflow Copy the configuration files from the RHEL 7 system:
su - postgres -c 'ls -1 $PGDATA/*.conf'
su - postgres -c 'ls -1 $PGDATA/*.conf'Copy to Clipboard Copied! Toggle word wrap Toggle overflow The configuration files to be copied are:
-
/var/lib/pgsql/data/pg_hba.conf -
/var/lib/pgsql/data/pg_ident.conf -
/var/lib/pgsql/data/postgresql.conf
-
On the RHEL 8 system, start the new PostgreSQL server:
systemctl start postgresql.service
# systemctl start postgresql.serviceCopy to Clipboard Copied! Toggle word wrap Toggle overflow On the RHEL 8 system, import data from the dumped sql file:
su - postgres -c 'psql -f ~/pgdump_file.sql postgres'
su - postgres -c 'psql -f ~/pgdump_file.sql postgres'Copy to Clipboard Copied! Toggle word wrap Toggle overflow NoteWhen upgrading from a Red Hat Software Collections version of PostgreSQL, adjust the commands to include
scl enable collection_name.For example, to dump data from therh-postgresql96Software Collection, use the following command:su - postgres -c 'scl enable rh-postgresql96 "pg_dumpall > ~/pgdump_file.sql"'
su - postgres -c 'scl enable rh-postgresql96 "pg_dumpall > ~/pgdump_file.sql"'Copy to Clipboard Copied! Toggle word wrap Toggle overflow
7.4.11. Installing and configuring a PostgreSQL database server by using RHEL system roles Link kopierenLink in die Zwischenablage kopiert!
You can use the postgresql RHEL system role to automate the installation and management of the PostgreSQL database server. By default, this role also optimizes PostgreSQL by automatically configuring performance-related settings in the PostgreSQL service configuration files.
7.4.11.1. Configuring PostgreSQL with an existing TLS certificate by using the postgresql RHEL system role Link kopierenLink in die Zwischenablage kopiert!
You can configure PostgreSQL with TLS encryption using the postgresql RHEL system role to automate secure database setup with existing certificates and private keys.
The postgresql role cannot open ports in the firewalld service. To allow remote access to the PostgreSQL server, add a task that uses the firewall RHEL system role to your playbook.
Prerequisites
- You have prepared the control node and the managed nodes.
- You are logged in to the control node as a user who can run playbooks on the managed nodes.
-
The account you use to connect to the managed nodes has
sudopermissions on them. Both the private key of the managed node and the certificate are stored on the control node in the following files:
-
Private key:
~/<FQDN_of_the_managed_node>.key -
Certificate:
~/<FQDN_of_the_managed_node>.crt
-
Private key:
Procedure
Store your sensitive variables in an encrypted file:
Create the vault:
ansible-vault create ~/vault.yml
$ ansible-vault create ~/vault.yml New Vault password: <vault_password> Confirm New Vault password: <vault_password>Copy to Clipboard Copied! Toggle word wrap Toggle overflow After the
ansible-vault createcommand opens an editor, enter the sensitive data in the<key>: <value>format:pwd: <password>
pwd: <password>Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Save the changes, and close the editor. Ansible encrypts the data in the vault.
Create a playbook file, for example,
~/playbook.yml, with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The settings specified in the example playbook include the following:
postgresql_version: <version>Sets the version of PostgreSQL to install. The version you can set depends on the PostgreSQL versions that are available in Red Hat Enterprise Linux running on the managed node.
You cannot upgrade or downgrade PostgreSQL by changing the
postgresql_versionvariable and running the playbook again.postgresql_password: <password>Sets the password of the
postgresdatabase superuser.You cannot change the password by changing the
postgresql_passwordvariable and running the playbook again.postgresql_cert_name: <private_key_and_certificate_file>Defines the path and base name of both the certificate and private key on the managed node without
.crtandkeysuffixes. During the PostgreSQL configuration, the role creates symbolic links in the/var/lib/pgsql/data/directory that refer to these files.The certificate and private key must exist locally on the managed node. You can use tasks with the
ansible.builtin.copymodule to transfer the files from the control node to the managed node, as shown in the playbook.postgresql_server_conf: <list_of_settings>Defines
postgresql.confsettings the role should set. The role adds these settings to the/etc/postgresql/system-roles.conffile and includes this file at the end of/var/lib/pgsql/data/postgresql.conf. Consequently, settings from thepostgresql_server_confvariable override settings in/var/lib/pgsql/data/postgresql.conf.Re-running the playbook with different settings in
postgresql_server_confoverwrites the/etc/postgresql/system-roles.conffile with the new settings.postgresql_pg_hba_conf: <list_of_authentication_entries>Configures client authentication entries in the
/var/lib/pgsql/data/pg_hba.conffile. For details, see see the PostgreSQL documentation.The example allows the following connections to PostgreSQL:
- Unencrypted connections by using local UNIX domain sockets.
- TLS-encrypted connections to the IPv4 and IPv6 localhost addresses.
-
TLS-encrypted connections from the 192.0.2.0/24 subnet. Note that access from remote addresses is only possible if you also configure the
listen_addressessetting in thepostgresql_server_confvariable appropriately.
Re-running the playbook with different settings in
postgresql_pg_hba_confoverwrites the/var/lib/pgsql/data/pg_hba.conffile with the new settings.
For details about all variables used in the playbook, see the
/usr/share/ansible/roles/rhel-system-roles.postgresql/README.mdfile on the control node.Validate the playbook syntax:
ansible-playbook --ask-vault-pass --syntax-check ~/playbook.yml
$ ansible-playbook --ask-vault-pass --syntax-check ~/playbook.ymlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that this command only validates the syntax and does not protect against a wrong but valid configuration.
Run the playbook:
ansible-playbook --ask-vault-pass ~/playbook.yml
$ ansible-playbook --ask-vault-pass ~/playbook.ymlCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use the
postgressuper user to connect to a PostgreSQL server and execute the\conninfometa command:psql "postgresql://postgres@managed-node-01.example.com:5432" -c '\conninfo'
# psql "postgresql://postgres@managed-node-01.example.com:5432" -c '\conninfo' Password for user postgres: You are connected to database "postgres" as user "postgres" on host "192.0.2.1" at port "5432". SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the output displays a TLS protocol version and cipher details, the connection works and TLS encryption is enabled.
7.4.11.2. Configuring PostgreSQL with a TLS certificate issued from IdM by using the postgresql RHEL system role Link kopierenLink in die Zwischenablage kopiert!
You can configure PostgreSQL with TLS encryption using the postgresql RHEL system role to automate secure database setup with certificates issued from Identity Management (IdM) and managed by the certmonger service.
The postgresql role cannot open ports in the firewalld service. To allow remote access to the PostgreSQL server, add a task to your playbook that uses the firewall RHEL system role.
Prerequisites
- You have prepared the control node and the managed nodes.
- You are logged in to the control node as a user who can run playbooks on the managed nodes.
-
The account you use to connect to the managed nodes has
sudopermissions on them. - You enrolled the managed node in an IdM domain.
Procedure
Store your sensitive variables in an encrypted file:
Create the vault:
ansible-vault create ~/vault.yml
$ ansible-vault create ~/vault.yml New Vault password: <vault_password> Confirm New Vault password: <vault_password>Copy to Clipboard Copied! Toggle word wrap Toggle overflow After the
ansible-vault createcommand opens an editor, enter the sensitive data in the<key>: <value>format:pwd: <password>
pwd: <password>Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Save the changes, and close the editor. Ansible encrypts the data in the vault.
Create a playbook file, for example,
~/playbook.yml, with the following content:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The settings specified in the example playbook include the following:
postgresql_version: <version>Sets the version of PostgreSQL to install. The version you can set depends on the PostgreSQL versions that are available in Red Hat Enterprise Linux running on the managed node.
You cannot upgrade or downgrade PostgreSQL by changing the
postgresql_versionvariable and running the playbook again.postgresql_password: <password>Sets the password of the
postgresdatabase superuser.You cannot change the password by changing the
postgresql_passwordvariable and running the playbook again.postgresql_certificates: <certificate_role_settings>-
A list of YAML dictionaries with settings for the
certificaterole. postgresql_server_conf: <list_of_settings>Defines
postgresql.confsettings you want the role to set. The role adds these settings to the/etc/postgresql/system-roles.conffile and includes this file at the end of/var/lib/pgsql/data/postgresql.conf. Consequently, settings from thepostgresql_server_confvariable override settings in/var/lib/pgsql/data/postgresql.conf.Re-running the playbook with different settings in
postgresql_server_confoverwrites the/etc/postgresql/system-roles.conffile with the new settings.postgresql_pg_hba_conf: <list_of_authentication_entries>Configures client authentication entries in the
/var/lib/pgsql/data/pg_hba.conffile. For details, see see the PostgreSQL documentation.The example allows the following connections to PostgreSQL:
- Unencrypted connections by using local UNIX domain sockets.
- TLS-encrypted connections to the IPv4 and IPv6 localhost addresses.
-
TLS-encrypted connections from the 192.0.2.0/24 subnet. Note that access from remote addresses is only possible if you also configure the
listen_addressessetting in thepostgresql_server_confvariable appropriately.
Re-running the playbook with different settings in
postgresql_pg_hba_confoverwrites the/var/lib/pgsql/data/pg_hba.conffile with the new settings.
For details about all variables used in the playbook, see the
/usr/share/ansible/roles/rhel-system-roles.postgresql/README.mdfile on the control node.Validate the playbook syntax:
ansible-playbook --ask-vault-pass --syntax-check ~/playbook.yml
$ ansible-playbook --ask-vault-pass --syntax-check ~/playbook.ymlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Note that this command only validates the syntax and does not protect against a wrong but valid configuration.
Run the playbook:
ansible-playbook --ask-vault-pass ~/playbook.yml
$ ansible-playbook --ask-vault-pass ~/playbook.ymlCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use the
postgressuper user to connect to a PostgreSQL server and execute the\conninfometa command:psql "postgresql://postgres@managed-node-01.example.com:5432" -c '\conninfo'
# psql "postgresql://postgres@managed-node-01.example.com:5432" -c '\conninfo' Password for user postgres: You are connected to database "postgres" as user "postgres" on host "192.0.2.1" at port "5432". SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the output displays a TLS protocol version and cipher details, the connection works and TLS encryption is enabled.
Chapter 8. Deploying and configuring a Postfix SMTP server Link kopierenLink in die Zwischenablage kopiert!
As a system administrator, you can configure your email infrastructure by using a mail transport agent (MTA), such as Postfix, to transport email messages between hosts using the SMTP protocol. Postfix is a server-side application for routing and delivering mail. You can use Postfix to set up a local mail server, create a null-client mail relay, use a Postfix server as a destination for multiple domains, or choose an LDAP directory instead of files for lookups.
The postfix package provides multiple configuration files in the /etc/postfix/ directory.
To configure your email infrastructure, use the following configuration files:
-
main.cf- contains the global configuration of Postfix. -
master.cf- specifies Postfix interaction with various processes to accomplish mail delivery. -
access- specifies access rules, for example hosts that are allowed to connect to Postfix. -
transport- maps email addresses to relay hosts. -
aliases- contains a configurable list required by the mail protocol that describes user ID aliases. Note that you can find this file in the/etc/directory.
The key features of Postfix:
- Security features to protect against common email related threats
- Customization options, including support for virtual domains and aliases
8.1. Installing and configuring a Postfix SMTP server Link kopierenLink in die Zwischenablage kopiert!
You can configure your Postfix SMTP server to receive, store, and deliver email messages. If the mail server package is not selected during the system installation, Postfix will not be available by default. Perform the following steps to install Postfix:
Prerequisites
- You have the root access.
- Register your system
Procedure
Remove the Sendmail utility:
yum remove sendmail
# yum remove sendmailCopy to Clipboard Copied! Toggle word wrap Toggle overflow Install Postfix:
yum install postfix
# yum install postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow To configure Postfix, edit the
/etc/postfix/main.cffile and make the following changes:By default, Postfix receives emails only on the
loopbackinterface. To configure Postfix to listen on specific interfaces, update theinet_interfacesparameter to the IP addresses of these interfaces:inet_interfaces = 127.0.0.1/32, [::1]/128, 192.0.2.1, [2001:db8:1::1]
inet_interfaces = 127.0.0.1/32, [::1]/128, 192.0.2.1, [2001:db8:1::1]Copy to Clipboard Copied! Toggle word wrap Toggle overflow To configure Postfix to listen on all interfaces, set:
inet_interfaces = all
inet_interfaces = allCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you want that Postfix uses a different hostname than the fully-qualified domain name (FQDN) that is returned by the
gethostname()function, add themyhostnameparameter:myhostname = smtp.example.com
myhostname = smtp.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow For example, Postfix adds this hostname to header of emails it processes.
If the domain name differs from the one in the
myhostnameparameter, add themydomainparameter:mydomain = example.com
mydomain = example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
myoriginparameter and set it to the value ofmydomain:myorigin = $mydomain
myorigin = $mydomainCopy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting, Postfix uses the domain name as origin for locally posted mails instead of the hostname.
Add the
mynetworksparameter, and define the IP ranges of trusted networks that are allowed to send mails:mynetworks = 127.0.0.1/32, [::1]/128, 192.0.2.1/24, [2001:db8:1::1]/64
mynetworks = 127.0.0.1/32, [::1]/128, 192.0.2.1/24, [2001:db8:1::1]/64Copy to Clipboard Copied! Toggle word wrap Toggle overflow If clients from not trustworthy networks, such as the internet, should be able to send mails through this server, you must configure relay restrictions in a later step.
Verify if the Postfix configuration in the
main.cffile is correct:postfix check
# postfix checkCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
postfixservice to start at boot and start it:systemctl enable --now postfix
# systemctl enable --now postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow Allow the smtp traffic through firewall and reload the firewall rules:
firewall-cmd --permanent --add-service smtp firewall-cmd --reload
# firewall-cmd --permanent --add-service smtp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Verify that the
postfixservice is running:systemctl status postfix
# systemctl status postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Restart the
postfixservice, if the output is stopped, waiting, or the service is not running:systemctl restart postfix
# systemctl restart postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Reload the
postfixservice after changing any options in the configuration files in the/etc/postfix/directory to apply those changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify the email communication between local users on your system:
echo "This is a test message" | mail -s <subject> <user@mydomain.com>
# echo "This is a test message" | mail -s <subject> <user@mydomain.com>Copy to Clipboard Copied! Toggle word wrap Toggle overflow To verify that your mail server does not relay emails from external IP ranges to foreign domains, follow the below mentioned procedure:
-
Log in to a client which is not within the subnets that you defined in
mynetworks. - Configure the client to use your mail server.
-
Try to send an email to an email address that is not under the domain you specified in mydomain on your mail server. For example, try to send an email to
non-existing-user@redhat.com. Check the
/var/log/maillogfile:554 Relay access denied - the server is not going to relay. 250 OK or similar - the server is going to relay.
554 Relay access denied - the server is not going to relay. 250 OK or similar - the server is going to relay.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
-
Log in to a client which is not within the subnets that you defined in
Troubleshooting
-
In case of errors, check the
/var/log/maillogfile.
8.2. Customizing TLS settings of a Postfix server Link kopierenLink in die Zwischenablage kopiert!
To make your email traffic encrypted and therefore more secure, you can configure Postfix to use a certificate from a trusted certificate authority (CA) instead of the self-signed certificate and customize the Transport Layer Security (TLS) security settings. In RHEL 8, the TLS encryption protocol is enabled in the Postfix server by default. The basic Postfix TLS configuration contains self-signed certificates for inbound SMTP and the opportunistic TLS for outbound SMTP.
Prerequisites
- You have the root access.
-
You have the
postfixpackage installed on your server. - You have a certificate signed by a trusted certificate authority (CA) and a private key.
You have copied the following files to the Postfix server:
-
The server certificate:
/etc/pki/tls/certs/postfix.pem -
The private key:
/etc/pki/tls/private/postfix.key
-
The server certificate:
Procedure
Set the path to the certificate and private key files on the server where Postfix is running by adding the following lines to the
/etc/postfix/main.cffile:smtpd_tls_cert_file = /etc/pki/tls/certs/postfix.pem smtpd_tls_key_file = /etc/pki/tls/private/postfix.key
smtpd_tls_cert_file = /etc/pki/tls/certs/postfix.pem smtpd_tls_key_file = /etc/pki/tls/private/postfix.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restrict the incoming SMTP connections to authenticated users only by editing the
/etc/postfix/main.cffile:smtpd_tls_auth_only = yes
smtpd_tls_auth_only = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the
postfixservice to apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Configure your client to use TLS encryption and send an email.
NoteTo get additional information about Postfix client TLS activity, increase the log level from
0to1by changing the following line in the/etc/postfix/main.cf:smtp_tls_loglevel = 1
smtp_tls_loglevel = 1Copy to Clipboard Copied! Toggle word wrap Toggle overflow
8.3. Configuring Postfix to forward all emails to a mail relay Link kopierenLink in die Zwischenablage kopiert!
If you want to forward all email to a mail relay, you can configure Postfix server as a null client. In this configuration Postfix only forwards mail to a different mail server and is not capable of receiving mail.
Prerequisites
- You have the root access.
-
You have the
postfixpackage installed on your server. - You have the IP address or hostname of the relay host to which you want to forward emails.
Procedure
To prevent Postfix from accepting any local email delivery and making it a null client, edit the
/etc/postfix/main.cffile and make the following changes:Configure Postfix to forward all email by setting the
mydestinationparameter equal to an empty value:mydestination =
mydestination =Copy to Clipboard Copied! Toggle word wrap Toggle overflow In this configuration the Postfix server is not a destination for any email and acts as a null client.
Specify the mail relay server that receives the email from your null client:
relayhost = [<ip_address_or_hostname>]
relayhost = [<ip_address_or_hostname>]Copy to Clipboard Copied! Toggle word wrap Toggle overflow The relay host is responsible for the mail delivery. Enclose
<ip_address_or_hostname>in square brackets.Configure the Postfix mail server to listen only on the loopback interface for emails to deliver:
inet_interfaces = loopback-only
inet_interfaces = loopback-onlyCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you want Postfix to rewrite the sender domain of all outgoing emails to the company domain of your relay mail server, set:
myorigin = relay.example.com
myorigin = relay.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow To disable the local mail delivery, add the following directive at the end of the configuration file:
local_transport = error: local delivery disabled
local_transport = error: local delivery disabledCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the
mynetworksparameter so that Postfix forwards email from the local system originating from the 127.0.0.0/8 IPv4 network and the [::1]/128 IPv6 network to the mail relay server:mynetworks = 127.0.0.0/8, [::1]/128
mynetworks = 127.0.0.0/8, [::1]/128Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Verify if the Postfix configuration in the
main.cffile is correct:postfix check
# postfix checkCopy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
postfixservice to apply the changes:systemctl restart postfix
# systemctl restart postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Verify that the email communication is forwarded to the mail relay:
echo "This is a test message" | mail -s <subject> <user@example.com>
# echo "This is a test message" | mail -s <subject> <user@example.com>Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Troubleshooting
-
In case of errors, check the
/var/log/maillogfile.
8.4. Configuring Postfix as a destination for multiple domains Link kopierenLink in die Zwischenablage kopiert!
You can configure Postfix as a mail server that can receive emails for multiple domains. In this configuration, Postfix acts as the final destination for emails sent to addresses within the specified domains. You can configure the following:
- Set up multiple email addresses that point to the same email destination
- Route incoming email for multiple domains to the same Postfix server
Prerequisites
- You have the root access.
- You have configured a Postfix server.
Procedure
In the
/etc/postfix/virtualvirtual alias file, specify the email addresses for each domain. Add each email address on a new line:<info@example.com> <user22@example.net> <sales@example.com> <user11@example.org>
<info@example.com> <user22@example.net> <sales@example.com> <user11@example.org>Copy to Clipboard Copied! Toggle word wrap Toggle overflow In this example, Postfix redirects all emails sent to info@example.com to user22@example.net and email sent to sales@example.com to user11@example.org.
Create a hash file for the virtual alias map:
postmap /etc/postfix/virtual
# postmap /etc/postfix/virtualCopy to Clipboard Copied! Toggle word wrap Toggle overflow This command creates the
/etc/postfix/virtual.dbfile. Note that you must always re-run this command after you update the/etc/postfix/virtualfile.In the Postfix
/etc/postfix/main.cfconfiguration file, add thevirtual_alias_mapsparameter and point it to the hash file:virtual_alias_maps = hash:/etc/postfix/virtual
virtual_alias_maps = hash:/etc/postfix/virtualCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the
postfixservice to apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Test the configuration by sending an email to one of the virtual email addresses.
Troubleshooting
-
In case of errors, check the
/var/log/maillogfile.
8.5. Using an LDAP directory as a lookup table Link kopierenLink in die Zwischenablage kopiert!
If you use a Lightweight Directory Access Protocol (LDAP) server to store accounts, domains or aliases, you can configure Postfix to use the LDAP server as a lookup table. Using LDAP instead of files for lookups enables you to have a central database.
Prerequisites
- You have the root access.
-
You have the
postfixpackage installed on your server. - You have an LDAP server with the required schema and user credentials.
-
You have the
postfix-ldapplugin installed on the server running Postfix.
Procedure
Configure the LDAP lookup parameters by creating a
/etc/postfix/ldap-aliases.cffile with the following content:Specify the hostname of the LDAP server:
server_host = ldap.example.com
server_host = ldap.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Specify the base domain name for the LDAP search:
search_base = dc=example,dc=com
search_base = dc=example,dc=comCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
Optional: Customize the LDAP search filter and attributes based on your requirements. The filter for searching the directory defaults to
query_filter = mailacceptinggeneralid=%s.
Enable the LDAP source as a lookup table in the
/etc/postfix/main.cfconfiguration file by adding the following content:virtual_alias_maps = ldap:/etc/postfix/ldap-aliases.cf
virtual_alias_maps = ldap:/etc/postfix/ldap-aliases.cfCopy to Clipboard Copied! Toggle word wrap Toggle overflow Verify the LDAP configuration by running the
postmapcommand, which checks for any syntax errors or connectivity issues:postmap -q @example.com ldap:/etc/postfix/ldap-aliases.cf
# postmap -q @example.com ldap:/etc/postfix/ldap-aliases.cfCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload the
postfixservice to apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
Send a test email to verify that the LDAP lookup works correctly. Check the mail logs in
/var/log/maillogfor any errors.
8.6. Configuring Postfix as an outgoing mail server to relay for authenticated users Link kopierenLink in die Zwischenablage kopiert!
You can configure Postfix to relay mail for authenticated users. In this scenario, you allow users to authenticate themselves and use their email address to send mail through your SMTP server by configuring Postfix as an outgoing mail server with SMTP authentication, TLS encryption, and sender address restrictions.
Prerequisites
- You have the root access.
- You have configured a Postfix server.
Procedure
To configure Postfix as an outgoing mail server, edit the
/etc/postfix/main.cffile and add the following:Enable SMTP authentication:
smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yes
smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Disable access without TLS:
smtpd_tls_auth_only = yes
smtpd_tls_auth_only = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Allow mail relaying only for authenticated users:
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destinationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Restrict users to use their own email address only as a sender:
smtpd_sender_restrictions = reject_sender_login_mismatch
smtpd_sender_restrictions = reject_sender_login_mismatchCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Reload the
postfixservice to apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Authenticate in your SMTP client that supports TLS and SASL. Send an test email to verify that the SMTP authentication works correctly.
8.7. Delivering email from Postfix to Dovecot running on the same host Link kopierenLink in die Zwischenablage kopiert!
You can configure Postfix to deliver incoming mail to Dovecot on the same host using LMTP over a UNIX socket. This socket enables direct communication between Postfix and Dovecot on the local machine.
Prerequisites
- You have the root access.
- You have configured a Postfix server.
- You have configured a Dovecot server, see Configuring and maintaining a Dovecot IMAP and POP3 server.
- You have configured the LMTP socket on your Dovecot server, see Configuring an LMTP socket and LMTPS listener.
Procedure
Configure Postfix to use the LMTP protocol and the UNIX domain socket for delivering mail to Dovecot in the
/etc/postfix/main.cffile:If you want to use virtual mailboxes, add the following content:
virtual_transport = lmtp:unix:/var/run/dovecot/lmtp
virtual_transport = lmtp:unix:/var/run/dovecot/lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you want to use non-virtual mailboxes, add the following content:
mailbox_transport = lmtp:unix:/var/run/dovecot/lmtp
mailbox_transport = lmtp:unix:/var/run/dovecot/lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Reload
postfixto apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
Send an test email to verify that the LMTP socket works correctly. Check the mail logs in
/var/log/maillogfor any errors.
8.8. Delivering email from Postfix to Dovecot running on a different host Link kopierenLink in die Zwischenablage kopiert!
You can establish a secure connection between Postfix mail server and the Dovecot delivery agent over the network. To do so, configure the LMTP service to use network socket for delivering mail between mail servers. By default, the LMTP protocol is not encrypted. However, if you configured TLS encryption, Dovecot uses the same settings automatically for the LMTP service. SMTP servers can then connect to it using the STARTTLS command over LMTP.
Prerequisites
- You have the root access.
- You have configured a Postfix server.
- You have configured a Dovecot server, see Configuring and maintaining a Dovecot IMAP and POP3 server.
- You have configured the LMTP service on your Dovecot server, see Configuring an LMTP socket and LMTPS listener.
Procedure
Configure Postfix to use the LMTP protocol and the INET domain socket for delivering mail to Dovecot in the
/etc/postfix/main.cffile by adding the following content:mailbox_transport = lmtp:inet:<dovecot_host>:<port>
mailbox_transport = lmtp:inet:<dovecot_host>:<port>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace
<dovecot_host>with the IP address or hostname of the Dovecot server and<port>with the port number of the LMTP service.Reload the
postfixservice to apply the changes:systemctl reload postfix
# systemctl reload postfixCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Send an test email to an address hosted by the remote Dovecot server and check the Dovecot logs to ensure that the mail was successfully delivered.
8.9. Securing the Postfix service Link kopierenLink in die Zwischenablage kopiert!
Postfix is a mail transfer agent (MTA) that uses the Simple Mail Transfer Protocol (SMTP) to deliver electronic messages between other MTAs and to email clients or delivery agents. Although MTAs can encrypt traffic between one another, they might not do so by default. You can also mitigate risks to various attacks by changing setting to more secure values.
8.9.2. Postfix configuration options for limiting DoS attacks Link kopierenLink in die Zwischenablage kopiert!
An attacker can flood the server with traffic, or send information that triggers a crash, causing a denial of service (DoS) attack. You can configure your system to reduce the risk of such attacks by setting limits in the /etc/postfix/main.cf file. You can change the value of the existing directives or you can add new directives with custom values in the <directive> = <value> format.
Use the following list of directives for limiting a DoS attack:
smtpd_client_connection_rate_limit-
Limits the maximum number of connection attempts any client can make to this service per time unit. The default value is
0, which means a client can make as many connections per time unit as Postfix can accept. By default, the directive excludes clients in trusted networks. anvil_rate_time_unit-
Defines a time unit to calculate the rate limit. The default value is
60seconds. smtpd_client_event_limit_exceptions- Excludes clients from the connection and rate limit commands. By default, the directive excludes clients in trusted networks.
smtpd_client_message_rate_limit- Defines the maximum number of message deliveries from client to request per time unit (regardless of whether or not Postfix actually accepts those messages).
default_process_limit-
Defines the default maximum number of Postfix child processes that provide a given service. You can ignore this rule for specific services in the
master.cffile. By default, the value is100. queue_minfree-
Defines the minimum amount of free space required to receive mail in the queue file system. The directive is currently used by the Postfix SMTP server to decide if it accepts any mail at all. By default, the Postfix SMTP server rejects
MAIL FROMcommands when the amount of free space is less than 1.5 times themessage_size_limit. To specify a higher minimum free space limit, specify aqueue_minfreevalue that is at least 1.5 times themessage_size_limit. By default, thequeue_minfreevalue is0. header_size_limit-
Defines the maximum amount of memory in bytes for storing a message header. If a header is large, it discards the excess header. By default, the value is
102400bytes. message_size_limit-
Defines the maximum size of a message including the envelope information in bytes. By default, the value is
10240000bytes.
8.9.3. Configuring Postfix to use SASL Link kopierenLink in die Zwischenablage kopiert!
Postfix supports Simple Authentication and Security Layer (SASL) based SMTP Authentication (AUTH). SMTP AUTH is an extension of the Simple Mail Transfer Protocol. Currently, the Postfix SMTP server supports the SASL implementations in the following ways:
- Dovecot SASL
- The Postfix SMTP server can communicate with the Dovecot SASL implementation using either a UNIX-domain socket or a TCP socket. Use this method if Postfix and Dovecot applications are running on separate machines.
- Cyrus SASL
- When enabled, SMTP clients must authenticate with the SMTP server using an authentication method supported and accepted by both the server and the client.
Prerequisites
-
The
dovecotpackage is installed on the system
Procedure
Set up Dovecot:
Include the following lines in the
/etc/dovecot/conf.d/10-master.conffile:Copy to Clipboard Copied! Toggle word wrap Toggle overflow The previous example uses UNIX-domain sockets for communication between Postfix and Dovecot. The example also assumes default Postfix SMTP server settings, which include the mail queue located in the
/var/spool/postfix/directory, and the application running under thepostfixuser and group.Optional: Set up Dovecot to listen for Postfix authentication requests through TCP:
service auth { inet_listener { port = <port-number> } }service auth { inet_listener { port = <port-number> } }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Specify the method that the email client uses to authenticate with Dovecot by editing the
auth_mechanismsparameter in/etc/dovecot/conf.d/10-auth.conffile:auth_mechanisms = plain login
auth_mechanisms = plain loginCopy to Clipboard Copied! Toggle word wrap Toggle overflow The
auth_mechanismsparameter supports different plaintext and non-plaintext authentication methods.
Set up Postfix by modifying the
/etc/postfix/main.cffile:Enable SMTP Authentication on the Postfix SMTP server:
smtpd_sasl_auth_enable = yes
smtpd_sasl_auth_enable = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the use of Dovecot SASL implementation for SMTP Authentication:
smtpd_sasl_type = dovecot
smtpd_sasl_type = dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow Provide the authentication path relative to the Postfix queue directory. Note that the use of a relative path ensures that the configuration works regardless of whether the Postfix server runs in
chrootor not:smtpd_sasl_path = private/auth
smtpd_sasl_path = private/authCopy to Clipboard Copied! Toggle word wrap Toggle overflow This step uses UNIX-domain sockets for communication between Postfix and Dovecot.
To configure Postfix to look for Dovecot on a different machine in case you use TCP sockets for communication, use configuration values similar to the following:
smtpd_sasl_path = inet: <IP_address> : <port_number>
smtpd_sasl_path = inet: <IP_address> : <port_number>Copy to Clipboard Copied! Toggle word wrap Toggle overflow In the previous example, replace the ip-address with the IP address of the Dovecot machine and port-number with the port number specified in Dovecot’s
/etc/dovecot/conf.d/10-master.conffile.Specify SASL mechanisms that the Postfix SMTP server makes available to clients. Note that you can specify different mechanisms for encrypted and unencrypted sessions.
smtpd_sasl_security_options = noanonymous, noplaintext smtpd_sasl_tls_security_options = noanonymous
smtpd_sasl_security_options = noanonymous, noplaintext smtpd_sasl_tls_security_options = noanonymousCopy to Clipboard Copied! Toggle word wrap Toggle overflow The previous directives specify that during unencrypted sessions, no anonymous authentication is allowed and no mechanisms that transmit unencrypted user names or passwords are allowed. For encrypted sessions that use TLS, only non-anonymous authentication mechanisms are allowed.
Chapter 9. Configuring and maintaining a Dovecot IMAP and POP3 server Link kopierenLink in die Zwischenablage kopiert!
Dovecot is a high-performance mail delivery agent (MDA) with a focus on security. You can use IMAP or POP3-compatible email clients to connect to a Dovecot server and read or download emails.
Key features of Dovecot:
- The design and implementation focuses on security
- Two-way replication support for high availability to improve the performance in large environments
-
Supports the high-performance
dboxmailbox format, but alsomboxandMaildirfor compatibility reasons - Self-healing features, such as fixing broken index files
- Compliance with the IMAP standards
- Workaround support to bypass bugs in IMAP and POP3 clients
9.1. Setting up a Dovecot server with PAM Setting up a Dovecot server with PAM authenticationauthentication Link kopierenLink in die Zwischenablage kopiert!
Dovecot supports the Name Service Switch (NSS) interface as a user database and the Pluggable Authentication Modules (PAM) framework as an authentication backend. With this configuration, Dovecot can provide services to users who are available locally on the server through NSS.
Use PAM authentication if accounts:
-
Are defined locally in the
/etc/passwdfile - Are stored in a remote database but they are available locally through the System Security Services Daemon (SSSD) or other NSS plugins.
9.1.1. Installing Dovecot Link kopierenLink in die Zwischenablage kopiert!
The dovecot package provides:
-
The
dovecotservice and the utilities to maintain it - Services that Dovecot starts on demand, such as for authentication
- Plugins, such as server-side mail filtering
-
Configuration files in the
/etc/dovecot/directory -
Documentation in the
/usr/share/doc/dovecot/directory
Procedure
Install the
dovecotpackage:yum install dovecot
# yum install dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteIf Dovecot is already installed and you require clean configuration files, rename or remove the
/etc/dovecot/directory. Afterwards, reinstall the package. Without removing the configuration files, theyum reinstall dovecotcommand does not reset the configuration files in/etc/dovecot/.
9.1.2. Configuring TLS encryption on a Dovecot server Link kopierenLink in die Zwischenablage kopiert!
Dovecot provides a secure default configuration. For example, TLS is enabled by default to transmit credentials and data encrypted over networks. To configure TLS on a Dovecot server, you only need to set the paths to the certificate and private key files. Additionally, you can increase the security of TLS connections by generating and using Diffie-Hellman parameters to provide perfect forward secrecy (PFS).
Prerequisites
- Dovecot is installed.
The following files have been copied to the listed locations on the server:
-
The server certificate:
/etc/pki/dovecot/certs/server.example.com.crt -
The private key:
/etc/pki/dovecot/private/server.example.com.key -
The Certificate Authority (CA) certificate:
/etc/pki/dovecot/certs/ca.crt
-
The server certificate:
-
The hostname in the
Subject DNfield of the server certificate matches the server’s Fully-qualified Domain Name (FQDN).
Procedure
Set secure permissions on the private key file:
chown root:root /etc/pki/dovecot/private/server.example.com.key chmod 600 /etc/pki/dovecot/private/server.example.com.key
# chown root:root /etc/pki/dovecot/private/server.example.com.key # chmod 600 /etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Generate a file with Diffie-Hellman parameters:
openssl dhparam -out /etc/dovecot/dh.pem 4096
# openssl dhparam -out /etc/dovecot/dh.pem 4096Copy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on the hardware and entropy on the server, generating Diffie-Hellman parameters with 4096 bits can take several minutes.
Set the paths to the certificate and private key files in the
/etc/dovecot/conf.d/10-ssl.conffile:Update the
ssl_certandssl_keyparameters, and set them to use the paths of the server’s certificate and private key:ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.key
ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_caparameter, and set it to use the path to the CA certificate:ssl_ca = </etc/pki/dovecot/certs/ca.crt
ssl_ca = </etc/pki/dovecot/certs/ca.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_dhparameter, and set it to use the path to the Diffie-Hellman parameters file:ssl_dh = </etc/dovecot/dh.pem
ssl_dh = </etc/dovecot/dh.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow
ImportantTo ensure that Dovecot reads the value of a parameter from a file, the path must start with a leading
<character.
9.1.3. Preparing Dovecot to use virtual users Link kopierenLink in die Zwischenablage kopiert!
By default, Dovecot performs many actions on the file system as the user who uses the service. However, configuring the Dovecot back end to use one local user to perform these actions has several benefits:
- Dovecot performs file system actions as a specific local user instead of using the user’s ID (UID).
- Users do not need to be available locally on the server.
- You can store all mailboxes and user-specific files in one root directory.
- Users do not require a UID and group ID (GID), which reduces administration efforts.
- Users who have access to the file system on the server cannot compromise their mailboxes or indexes because they cannot access these files.
- Setting up replication is easier.
Prerequisites
- Dovecot is installed.
Procedure
Create the
vmailuser:useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmail
# useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmailCopy to Clipboard Copied! Toggle word wrap Toggle overflow Dovecot will later use this user to manage the mailboxes. For security reasons, do not use the
dovecotordovenullsystem users for this purpose.If you use a different path than
/var/mail/, set themail_spool_tSELinux context on it, for example:semanage fcontext -a -t mail_spool_t "<path>(/.*)?" restorecon -Rv <path>
# semanage fcontext -a -t mail_spool_t "<path>(/.*)?" # restorecon -Rv <path>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Grant write permissions on
/var/mail/only to thevmailuser:chown vmail:vmail /var/mail/ chmod 700 /var/mail/
# chown vmail:vmail /var/mail/ # chmod 700 /var/mail/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
mail_locationparameter in the/etc/dovecot/conf.d/10-mail.conffile, and set it to the mailbox format and location:mail_location = sdbox:/var/mail/%n/
mail_location = sdbox:/var/mail/%n/Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting:
-
Dovecot uses the high-performant
dboxmailbox format insinglemode. In this mode, the service stores each mail in a separate file, similar to themaildirformat. -
Dovecot resolves the
%nvariable in the path to the username. This is required to ensure that each user has a separate directory for its mailbox.
-
Dovecot uses the high-performant
9.1.4. Using PAM as the Dovecot authentication backend Link kopierenLink in die Zwischenablage kopiert!
By default, Dovecot uses the Name Service Switch (NSS) interface as the user database and the Pluggable Authentication Modules (PAM) framework as the authentication backend.
Customize the settings to adapt Dovecot to your environment and to simplify administration by using the virtual users feature.
Prerequisites
- Dovecot is installed.
- The virtual users feature is configured.
Procedure
Update the
first_valid_uidparameter in the/etc/dovecot/conf.d/10-mail.conffile to define the lowest user ID (UID) that can authenticate to Dovecot:first_valid_uid = 1000
first_valid_uid = 1000Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, users with a UID greater than or equal to
1000can authenticate. If required, you can also set thelast_valid_uidparameter to define the highest UID that Dovecot allows to log in.In the
/etc/dovecot/conf.d/auth-system.conf.extfile, add theoverride_fieldsparameter to theuserdbsection as follows:userdb { driver = passwd override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }userdb { driver = passwd override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Due to the fixed values, Dovecot does not query these settings from the
/etc/passwdfile. As a result, the home directory defined in/etc/passwddoes not need to exist.
9.1.5. Completing the Dovecot configuration Link kopierenLink in die Zwischenablage kopiert!
Once you have installed and configured Dovecot, open the required ports in the firewalld service, and enable and start the service. Afterwards, you can test the server.
Prerequisites
The following has been configured in Dovecot:
- TLS encryption
- An authentication backend
- Clients trust the Certificate Authority (CA) certificate.
Procedure
If you want to provide only an IMAP or POP3 service to users, uncomment the
protocolsparameter in the/etc/dovecot/dovecot.conffile, and set it to the required protocols. For example, if you do not require POP3, set:protocols = imap lmtp
protocols = imap lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the
imap,pop3, andlmtpprotocols are enabled.Open the ports in the local firewall. For example, to open the ports for the IMAPS, IMAP, POP3S, and POP3 protocols, enter:
firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 firewall-cmd --reload
# firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
dovecotservice:systemctl enable --now dovecot
# systemctl enable --now dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a mail client, such as Mozilla Thunderbird, to connect to Dovecot and read emails. The settings for the mail client depend on the protocol you want to use:
Expand Table 9.1. Connection settings to the Dovecot server Protocol Port Connection security Authentication method IMAP
143
STARTTLS
PLAIN[a]
IMAPS
993
SSL/TLS
PLAIN[a]
POP3
110
STARTTLS
PLAIN[a]
POP3S
995
SSL/TLS
PLAIN[a]
[a] The client transmits data encrypted through the TLS connection. Consequently, credentials are not disclosed.Note that this table does not list settings for unencrypted connections because, by default, Dovecot does not accept plain text authentication on connections without TLS.
Display configuration settings with non-default values:
doveconf -n
# doveconf -nCopy to Clipboard Copied! Toggle word wrap Toggle overflow
9.2. Setting up a Dovecot server with LDAP authentication Link kopierenLink in die Zwischenablage kopiert!
If your infrastructure uses an LDAP server to store accounts, you can authenticate Dovecot users against it. In this case, you manage accounts centrally in the directory and, users do not required local access to the file system on the Dovecot server.
Centrally-managed accounts are also a benefit if you plan to set up multiple Dovecot servers with replication to make your mailboxes high available.
9.2.1. Installing Dovecot Link kopierenLink in die Zwischenablage kopiert!
The dovecot package provides:
-
The
dovecotservice and the utilities to maintain it - Services that Dovecot starts on demand, such as for authentication
- Plugins, such as server-side mail filtering
-
Configuration files in the
/etc/dovecot/directory -
Documentation in the
/usr/share/doc/dovecot/directory
Procedure
Install the
dovecotpackage:yum install dovecot
# yum install dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteIf Dovecot is already installed and you require clean configuration files, rename or remove the
/etc/dovecot/directory. Afterwards, reinstall the package. Without removing the configuration files, theyum reinstall dovecotcommand does not reset the configuration files in/etc/dovecot/.
9.2.2. Configuring TLS encryption on a Dovecot server Link kopierenLink in die Zwischenablage kopiert!
Dovecot provides a secure default configuration. For example, TLS is enabled by default to transmit credentials and data encrypted over networks. To configure TLS on a Dovecot server, you only need to set the paths to the certificate and private key files. Additionally, you can increase the security of TLS connections by generating and using Diffie-Hellman parameters to provide perfect forward secrecy (PFS).
Prerequisites
- Dovecot is installed.
The following files have been copied to the listed locations on the server:
-
The server certificate:
/etc/pki/dovecot/certs/server.example.com.crt -
The private key:
/etc/pki/dovecot/private/server.example.com.key -
The Certificate Authority (CA) certificate:
/etc/pki/dovecot/certs/ca.crt
-
The server certificate:
-
The hostname in the
Subject DNfield of the server certificate matches the server’s Fully-qualified Domain Name (FQDN).
Procedure
Set secure permissions on the private key file:
chown root:root /etc/pki/dovecot/private/server.example.com.key chmod 600 /etc/pki/dovecot/private/server.example.com.key
# chown root:root /etc/pki/dovecot/private/server.example.com.key # chmod 600 /etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Generate a file with Diffie-Hellman parameters:
openssl dhparam -out /etc/dovecot/dh.pem 4096
# openssl dhparam -out /etc/dovecot/dh.pem 4096Copy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on the hardware and entropy on the server, generating Diffie-Hellman parameters with 4096 bits can take several minutes.
Set the paths to the certificate and private key files in the
/etc/dovecot/conf.d/10-ssl.conffile:Update the
ssl_certandssl_keyparameters, and set them to use the paths of the server’s certificate and private key:ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.key
ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_caparameter, and set it to use the path to the CA certificate:ssl_ca = </etc/pki/dovecot/certs/ca.crt
ssl_ca = </etc/pki/dovecot/certs/ca.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_dhparameter, and set it to use the path to the Diffie-Hellman parameters file:ssl_dh = </etc/dovecot/dh.pem
ssl_dh = </etc/dovecot/dh.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow
ImportantTo ensure that Dovecot reads the value of a parameter from a file, the path must start with a leading
<character.
9.2.3. Preparing Dovecot to use virtual users Link kopierenLink in die Zwischenablage kopiert!
By default, Dovecot performs many actions on the file system as the user who uses the service. However, configuring the Dovecot back end to use one local user to perform these actions has several benefits:
- Dovecot performs file system actions as a specific local user instead of using the user’s ID (UID).
- Users do not need to be available locally on the server.
- You can store all mailboxes and user-specific files in one root directory.
- Users do not require a UID and group ID (GID), which reduces administration efforts.
- Users who have access to the file system on the server cannot compromise their mailboxes or indexes because they cannot access these files.
- Setting up replication is easier.
Prerequisites
- Dovecot is installed.
Procedure
Create the
vmailuser:useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmail
# useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmailCopy to Clipboard Copied! Toggle word wrap Toggle overflow Dovecot will later use this user to manage the mailboxes. For security reasons, do not use the
dovecotordovenullsystem users for this purpose.If you use a different path than
/var/mail/, set themail_spool_tSELinux context on it, for example:semanage fcontext -a -t mail_spool_t "<path>(/.*)?" restorecon -Rv <path>
# semanage fcontext -a -t mail_spool_t "<path>(/.*)?" # restorecon -Rv <path>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Grant write permissions on
/var/mail/only to thevmailuser:chown vmail:vmail /var/mail/ chmod 700 /var/mail/
# chown vmail:vmail /var/mail/ # chmod 700 /var/mail/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
mail_locationparameter in the/etc/dovecot/conf.d/10-mail.conffile, and set it to the mailbox format and location:mail_location = sdbox:/var/mail/%n/
mail_location = sdbox:/var/mail/%n/Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting:
-
Dovecot uses the high-performant
dboxmailbox format insinglemode. In this mode, the service stores each mail in a separate file, similar to themaildirformat. -
Dovecot resolves the
%nvariable in the path to the username. This is required to ensure that each user has a separate directory for its mailbox.
-
Dovecot uses the high-performant
9.2.4. Using LDAP as the Dovecot authentication backend Link kopierenLink in die Zwischenablage kopiert!
Users in an LDAP directory can usually authenticate themselves to the directory service. Dovecot can use this to authenticate users when they log in to the IMAP and POP3 services. This authentication method has a number of benefits, such as:
- Administrators can manage users centrally in the directory.
- The LDAP accounts do not require any special attributes. They only need to be able to authenticate to the LDAP server. Consequently, this method is independent from the password storage scheme used on the LDAP server.
- Users do not need to be available locally on the server through the Name Service Switch (NSS) interface and the Pluggable Authentication Modules (PAM) framework.
Prerequisites
- Dovecot is installed.
- The virtual users feature is configured.
- Connections to the LDAP server support TLS encryption.
- RHEL on the Dovecot server trusts the Certificate Authority (CA) certificate of the LDAP server.
- If users are stored in different trees in the LDAP directory, a dedicated LDAP account for Dovecot exists to search the directory. This account requires permissions to search for Distinguished Names (DNs) of other users.
Procedure
Configure the authentication backends in the
/etc/dovecot/conf.d/10-auth.conffile:Comment out
includestatements forauth-*.conf.extauthentication backend configuration files that you do not require, for example:#!include auth-system.conf.ext
#!include auth-system.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable LDAP authentication by uncommenting the following line:
!include auth-ldap.conf.ext
!include auth-ldap.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Edit the
/etc/dovecot/conf.d/auth-ldap.conf.extfile, and add theoverride_fieldsparameter as follows to theuserdbsection:userdb { driver = ldap args = /etc/dovecot/dovecot-ldap.conf.ext override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }userdb { driver = ldap args = /etc/dovecot/dovecot-ldap.conf.ext override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Due to the fixed values, Dovecot does not query these settings from the LDAP server. Consequently, these attributes also do not have to be present.
Create the
/etc/dovecot/dovecot-ldap.conf.extfile with the following settings:Depending on the LDAP structure, configure one of the following:
If users are stored in different trees in the LDAP directory, configure dynamic DN lookups:
dn = cn=dovecot_LDAP,dc=example,dc=com dnpass = password pass_filter = (&(objectClass=posixAccount)(uid=%n))
dn = cn=dovecot_LDAP,dc=example,dc=com dnpass = password pass_filter = (&(objectClass=posixAccount)(uid=%n))Copy to Clipboard Copied! Toggle word wrap Toggle overflow Dovecot uses the specified DN, password, and filter to search the DN of the authenticating user in the directory. In this search, Dovecot replaces
%nin the filter with the username. Note that the LDAP search must return only one result.If all users are stored under a specific entry, configure a DN template:
auth_bind_userdn = cn=%n,ou=People,dc=example,dc=com
auth_bind_userdn = cn=%n,ou=People,dc=example,dc=comCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Enable authentication binds to the LDAP server to verify Dovecot users:
auth_bind = yes
auth_bind = yesCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the URL to the LDAP server:
uris = ldaps://LDAP-srv.example.com
uris = ldaps://LDAP-srv.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow For security reasons, only use encrypted connections using LDAPS or the
STARTTLScommand over the LDAP protocol. For the latter, additionally addtls = yesto the settings.For a working certificate validation, the hostname of the LDAP server must match the hostname used in its TLS certificate.
Enable the verification of the LDAP server’s TLS certificate:
tls_require_cert = hard
tls_require_cert = hardCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the base DN to the DN where to start searching for users:
base = ou=People,dc=example,dc=com
base = ou=People,dc=example,dc=comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Set the search scope:
scope = onelevel
scope = onelevelCopy to Clipboard Copied! Toggle word wrap Toggle overflow Dovecot searches with the
onelevelscope only in the specified base DN and with thesubtreescope also in subtrees.
Set secure permissions on the
/etc/dovecot/dovecot-ldap.conf.extfile:chown root:root /etc/dovecot/dovecot-ldap.conf.ext chmod 600 /etc/dovecot/dovecot-ldap.conf.ext
# chown root:root /etc/dovecot/dovecot-ldap.conf.ext # chmod 600 /etc/dovecot/dovecot-ldap.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow
9.2.5. Completing the Dovecot configuration Link kopierenLink in die Zwischenablage kopiert!
Once you have installed and configured Dovecot, open the required ports in the firewalld service, and enable and start the service. Afterwards, you can test the server.
Prerequisites
The following has been configured in Dovecot:
- TLS encryption
- An authentication backend
- Clients trust the Certificate Authority (CA) certificate.
Procedure
If you want to provide only an IMAP or POP3 service to users, uncomment the
protocolsparameter in the/etc/dovecot/dovecot.conffile, and set it to the required protocols. For example, if you do not require POP3, set:protocols = imap lmtp
protocols = imap lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the
imap,pop3, andlmtpprotocols are enabled.Open the ports in the local firewall. For example, to open the ports for the IMAPS, IMAP, POP3S, and POP3 protocols, enter:
firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 firewall-cmd --reload
# firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
dovecotservice:systemctl enable --now dovecot
# systemctl enable --now dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a mail client, such as Mozilla Thunderbird, to connect to Dovecot and read emails. The settings for the mail client depend on the protocol you want to use:
Expand Table 9.2. Connection settings to the Dovecot server Protocol Port Connection security Authentication method IMAP
143
STARTTLS
PLAIN[a]
IMAPS
993
SSL/TLS
PLAIN[a]
POP3
110
STARTTLS
PLAIN[a]
POP3S
995
SSL/TLS
PLAIN[a]
[a] The client transmits data encrypted through the TLS connection. Consequently, credentials are not disclosed.Note that this table does not list settings for unencrypted connections because, by default, Dovecot does not accept plain text authentication on connections without TLS.
Display configuration settings with non-default values:
doveconf -n
# doveconf -nCopy to Clipboard Copied! Toggle word wrap Toggle overflow
9.3. Setting up a Dovecot server with MariaDB SQL authentication Link kopierenLink in die Zwischenablage kopiert!
If you store users and passwords in a MariaDB SQL server, you can configure Dovecot to use it as the user database and authentication backend. With this configuration, you manage accounts centrally in a database, and users have no local access to the file system on the Dovecot server.
Centrally managed accounts are also a benefit if you plan to set up multiple Dovecot servers with replication to make your mailboxes highly available.
9.3.1. Installing Dovecot Link kopierenLink in die Zwischenablage kopiert!
The dovecot package provides:
-
The
dovecotservice and the utilities to maintain it - Services that Dovecot starts on demand, such as for authentication
- Plugins, such as server-side mail filtering
-
Configuration files in the
/etc/dovecot/directory -
Documentation in the
/usr/share/doc/dovecot/directory
Procedure
Install the
dovecotpackage:yum install dovecot
# yum install dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow NoteIf Dovecot is already installed and you require clean configuration files, rename or remove the
/etc/dovecot/directory. Afterwards, reinstall the package. Without removing the configuration files, theyum reinstall dovecotcommand does not reset the configuration files in/etc/dovecot/.
9.3.2. Configuring TLS encryption on a Dovecot server Link kopierenLink in die Zwischenablage kopiert!
Dovecot provides a secure default configuration. For example, TLS is enabled by default to transmit credentials and data encrypted over networks. To configure TLS on a Dovecot server, you only need to set the paths to the certificate and private key files. Additionally, you can increase the security of TLS connections by generating and using Diffie-Hellman parameters to provide perfect forward secrecy (PFS).
Prerequisites
- Dovecot is installed.
The following files have been copied to the listed locations on the server:
-
The server certificate:
/etc/pki/dovecot/certs/server.example.com.crt -
The private key:
/etc/pki/dovecot/private/server.example.com.key -
The Certificate Authority (CA) certificate:
/etc/pki/dovecot/certs/ca.crt
-
The server certificate:
-
The hostname in the
Subject DNfield of the server certificate matches the server’s Fully-qualified Domain Name (FQDN).
Procedure
Set secure permissions on the private key file:
chown root:root /etc/pki/dovecot/private/server.example.com.key chmod 600 /etc/pki/dovecot/private/server.example.com.key
# chown root:root /etc/pki/dovecot/private/server.example.com.key # chmod 600 /etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Generate a file with Diffie-Hellman parameters:
openssl dhparam -out /etc/dovecot/dh.pem 4096
# openssl dhparam -out /etc/dovecot/dh.pem 4096Copy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on the hardware and entropy on the server, generating Diffie-Hellman parameters with 4096 bits can take several minutes.
Set the paths to the certificate and private key files in the
/etc/dovecot/conf.d/10-ssl.conffile:Update the
ssl_certandssl_keyparameters, and set them to use the paths of the server’s certificate and private key:ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.key
ssl_cert = </etc/pki/dovecot/certs/server.example.com.crt ssl_key = </etc/pki/dovecot/private/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_caparameter, and set it to use the path to the CA certificate:ssl_ca = </etc/pki/dovecot/certs/ca.crt
ssl_ca = </etc/pki/dovecot/certs/ca.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
ssl_dhparameter, and set it to use the path to the Diffie-Hellman parameters file:ssl_dh = </etc/dovecot/dh.pem
ssl_dh = </etc/dovecot/dh.pemCopy to Clipboard Copied! Toggle word wrap Toggle overflow
ImportantTo ensure that Dovecot reads the value of a parameter from a file, the path must start with a leading
<character.
9.3.3. Preparing Dovecot to use virtual users Link kopierenLink in die Zwischenablage kopiert!
By default, Dovecot performs many actions on the file system as the user who uses the service. However, configuring the Dovecot back end to use one local user to perform these actions has several benefits:
- Dovecot performs file system actions as a specific local user instead of using the user’s ID (UID).
- Users do not need to be available locally on the server.
- You can store all mailboxes and user-specific files in one root directory.
- Users do not require a UID and group ID (GID), which reduces administration efforts.
- Users who have access to the file system on the server cannot compromise their mailboxes or indexes because they cannot access these files.
- Setting up replication is easier.
Prerequisites
- Dovecot is installed.
Procedure
Create the
vmailuser:useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmail
# useradd --home-dir /var/mail/ --shell /usr/sbin/nologin vmailCopy to Clipboard Copied! Toggle word wrap Toggle overflow Dovecot will later use this user to manage the mailboxes. For security reasons, do not use the
dovecotordovenullsystem users for this purpose.If you use a different path than
/var/mail/, set themail_spool_tSELinux context on it, for example:semanage fcontext -a -t mail_spool_t "<path>(/.*)?" restorecon -Rv <path>
# semanage fcontext -a -t mail_spool_t "<path>(/.*)?" # restorecon -Rv <path>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Grant write permissions on
/var/mail/only to thevmailuser:chown vmail:vmail /var/mail/ chmod 700 /var/mail/
# chown vmail:vmail /var/mail/ # chmod 700 /var/mail/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the
mail_locationparameter in the/etc/dovecot/conf.d/10-mail.conffile, and set it to the mailbox format and location:mail_location = sdbox:/var/mail/%n/
mail_location = sdbox:/var/mail/%n/Copy to Clipboard Copied! Toggle word wrap Toggle overflow With this setting:
-
Dovecot uses the high-performant
dboxmailbox format insinglemode. In this mode, the service stores each mail in a separate file, similar to themaildirformat. -
Dovecot resolves the
%nvariable in the path to the username. This is required to ensure that each user has a separate directory for its mailbox.
-
Dovecot uses the high-performant
9.3.4. Using a MariaDB SQL database as the Dovecot authentication backend Link kopierenLink in die Zwischenablage kopiert!
Dovecot can read accounts and passwords from a MariaDB database and use it to authenticate users when they log in to the IMAP or POP3 service. The benefits of this authentication method include:
- Administrators can manage users centrally in a database.
- Users have no access locally on the server.
Prerequisites
- Dovecot is installed.
- The virtual users feature is configured.
- Connections to the MariaDB server support TLS encryption.
-
The
dovecotDBdatabase exists in MariaDB, and theuserstable contains at least ausernameandpasswordcolumn. -
The
passwordcolumn contains passwords encrypted with a scheme that Dovecot supports. -
The passwords either use the same scheme or have a
{pw-storage-scheme}prefix. -
The
dovecotMariaDB user has read permission on theuserstable in thedovecotDBdatabase. -
The certificate of the Certificate Authority (CA) that issued the MariaDB server’s TLS certificate is stored on the Dovecot server in the
/etc/pki/tls/certs/ca.crtfile.
Procedure
Install the
dovecot-mysqlpackage:yum install dovecot-mysql
# yum install dovecot-mysqlCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the authentication backends in the
/etc/dovecot/conf.d/10-auth.conffile:Comment out
includestatements forauth-*.conf.extauthentication backend configuration files that you do not require, for example:#!include auth-system.conf.ext
#!include auth-system.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable SQL authentication by uncommenting the following line:
!include auth-sql.conf.ext
!include auth-sql.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Edit the
/etc/dovecot/conf.d/auth-sql.conf.extfile, and add theoverride_fieldsparameter to theuserdbsection as follows:userdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }userdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext override_fields = uid=vmail gid=vmail home=/var/mail/%n/ }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Due to the fixed values, Dovecot does not query these settings from the SQL server.
Create the
/etc/dovecot/dovecot-sql.conf.extfile with the following settings:Copy to Clipboard Copied! Toggle word wrap Toggle overflow To use TLS encryption to the database server, set the
ssl_caoption to the path of the certificate of the CA that issued the MariaDB server certificate. For a working certificate validation, the hostname of the MariaDB server must match the hostname used in its TLS certificate.If the password values in the database contain a
{pw-storage-scheme}prefix, you can omit thedefault_pass_schemesetting.The queries in the file must be set as follows:
-
For the
user_queryparameter, the query must return the username of the Dovecot user. The query must also return only one result. -
For the
password_queryparameter, the query must return the username and the password, and Dovecot must use these values in theuserandpasswordvariables. Therefore, if the database uses different column names, use theASSQL command to rename a column in the result. -
For the
iterate_queryparameter, the query must return a list of all users.
-
For the
Set secure permissions on the
/etc/dovecot/dovecot-sql.conf.extfile:chown root:root /etc/dovecot/dovecot-sql.conf.ext chmod 600 /etc/dovecot/dovecot-sql.conf.ext
# chown root:root /etc/dovecot/dovecot-sql.conf.ext # chmod 600 /etc/dovecot/dovecot-sql.conf.extCopy to Clipboard Copied! Toggle word wrap Toggle overflow
9.3.5. Completing the Dovecot configuration Link kopierenLink in die Zwischenablage kopiert!
Once you have installed and configured Dovecot, open the required ports in the firewalld service, and enable and start the service. Afterwards, you can test the server.
Prerequisites
The following has been configured in Dovecot:
- TLS encryption
- An authentication backend
- Clients trust the Certificate Authority (CA) certificate.
Procedure
If you want to provide only an IMAP or POP3 service to users, uncomment the
protocolsparameter in the/etc/dovecot/dovecot.conffile, and set it to the required protocols. For example, if you do not require POP3, set:protocols = imap lmtp
protocols = imap lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the
imap,pop3, andlmtpprotocols are enabled.Open the ports in the local firewall. For example, to open the ports for the IMAPS, IMAP, POP3S, and POP3 protocols, enter:
firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 firewall-cmd --reload
# firewall-cmd --permanent --add-service=imaps --add-service=imap --add-service=pop3s --add-service=pop3 # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start the
dovecotservice:systemctl enable --now dovecot
# systemctl enable --now dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a mail client, such as Mozilla Thunderbird, to connect to Dovecot and read emails. The settings for the mail client depend on the protocol you want to use:
Expand Table 9.3. Connection settings to the Dovecot server Protocol Port Connection security Authentication method IMAP
143
STARTTLS
PLAIN[a]
IMAPS
993
SSL/TLS
PLAIN[a]
POP3
110
STARTTLS
PLAIN[a]
POP3S
995
SSL/TLS
PLAIN[a]
[a] The client transmits data encrypted through the TLS connection. Consequently, credentials are not disclosed.Note that this table does not list settings for unencrypted connections because, by default, Dovecot does not accept plain text authentication on connections without TLS.
Display configuration settings with non-default values:
doveconf -n
# doveconf -nCopy to Clipboard Copied! Toggle word wrap Toggle overflow
9.4. Configuring replication between two Dovecot servers Link kopierenLink in die Zwischenablage kopiert!
With two-way replication, you can make your Dovecot server high-available, and IMAP and POP3 clients can access a mailbox on both servers. Dovecot keeps track of changes in the index logs of each mailbox and solves conflicts in a safe way.
Perform this procedure on both replication partners.
Replication works only between server pairs. Consequently, in a large cluster, you need multiple independent backend pairs.
Prerequisites
- Both servers use the same authentication backend. Preferably, use LDAP or SQL to maintain accounts centrally.
-
The Dovecot user database configuration supports user listing. Use the
doveadm user '*'command to verify this. -
Dovecot accesses mailboxes on the file system as the
vmailuser instead of the user’s ID (UID).
Procedure
Create the
/etc/dovecot/conf.d/10-replication.conffile and perform the following steps in it:Enable the
notifyandreplicationplug-ins:mail_plugins = $mail_plugins notify replication
mail_plugins = $mail_plugins notify replicationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add a
service replicatorsection:Copy to Clipboard Copied! Toggle word wrap Toggle overflow With these settings, Dovecot starts at least one replicator process when the
dovecotservice starts. Additionally, this section defines the settings on thereplicator-doveadmsocket.Add a
service aggregatorsection to configure thereplication-notify-fifopipe andreplication-notifysocket:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add a
service doveadmsection to define the port of the replication service:service doveadm { inet_listener { port = 12345 } }service doveadm { inet_listener { port = 12345 } }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Set the password of the
doveadmreplication service:doveadm_password = replication_password
doveadm_password = replication_passwordCopy to Clipboard Copied! Toggle word wrap Toggle overflow The password must be the same on both servers.
Configure the replication partner:
plugin { mail_replica = tcp:server2.example.com:12345 }plugin { mail_replica = tcp:server2.example.com:12345 }Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Define the maximum number of parallel
dsyncprocesses:replication_max_conns = 20
replication_max_conns = 20Copy to Clipboard Copied! Toggle word wrap Toggle overflow The default value of
replication_max_connsis10.
Set secure permissions on the
/etc/dovecot/conf.d/10-replication.conffile:chown root:root /etc/dovecot/conf.d/10-replication.conf chmod 600 /etc/dovecot/conf.d/10-replication.conf
# chown root:root /etc/dovecot/conf.d/10-replication.conf # chmod 600 /etc/dovecot/conf.d/10-replication.confCopy to Clipboard Copied! Toggle word wrap Toggle overflow Enable the
nis_enabledSELinux Boolean to allow Dovecot to open thedoveadmreplication port:setsebool -P nis_enabled on
setsebool -P nis_enabled onCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure
firewalldrules to allow only the replication partner to access the replication port, for example:firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv4" source address="192.0.2.1/32" port protocol="tcp" port="12345" accept" firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv6" source address="2001:db8:2::1/128" port protocol="tcp" port="12345" accept" firewall-cmd --reload
# firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv4" source address="192.0.2.1/32" port protocol="tcp" port="12345" accept" # firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv6" source address="2001:db8:2::1/128" port protocol="tcp" port="12345" accept" # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow The subnet masks
/32for the IPv4 and/128for the IPv6 address limit the access to the specified addresses.- Perform this procedure also on the other replication partner.
Reload Dovecot:
systemctl reload dovecot
# systemctl reload dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
- Perform an action in a mailbox on one server and then verify if Dovecot has replicated the change to the other server.
Display the replicator status:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Display the replicator status of a specific user:
doveadm replicator status example_user
# doveadm replicator status example_user username priority fast sync full sync success sync failed example_user none 02:05:28 04:19:07 02:05:28 -Copy to Clipboard Copied! Toggle word wrap Toggle overflow
9.5. Automatically subscribing users to IMAP mailboxes Link kopierenLink in die Zwischenablage kopiert!
Typically, IMAP server administrators want Dovecot to automatically create certain mailboxes, such as Sent and Trash, and subscribe the users to them. You can set this in the configuration files.
Additionally, you can define special-use mailboxes. IMAP clients often support defining mailboxes for special purposes, such as for sent emails. To avoid that the user has to manually select and set the correct mailboxes, IMAP servers can send a special-use attribute in the IMAP LIST command. Clients can then use this attribute to identify and set, for example, the mailbox for sent emails.
Prerequisites
- Dovecot is configured.
Procedure
Update the
inboxnamespace section in the/etc/dovecot/conf.d/15-mailboxes.conffile:Add the
auto = subscribesetting to each special-use mailbox that should be available to users, for example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow If your mail clients support more special-use mailboxes, you can add similar entries. The
special_useparameter defines the value that Dovecot sends in thespecial-useattribute to the clients.Optional: If you want to define other mailboxes that have no special purpose, add
mailboxsections for them in the user’s inbox, for example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow You can set the
autoparameter to one of the following values:-
subscribe: Automatically creates the mailbox and subscribes the user to it. -
create: Automatically creates the mailbox without subscribing the user to it. -
no(default): Dovecot neither creates the mailbox nor does it subscribe the user to it.
-
Reload Dovecot:
systemctl reload dovecot
# systemctl reload dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use an IMAP client and access your mailbox.
Mailboxes with the setting
auto = subscribeare automatically visible. If the client supports special-use mailboxes and the defined purposes, the client automatically uses them.
9.6. Configuring an LMTP socket and LMTPS listener Link kopierenLink in die Zwischenablage kopiert!
SMTP servers, such as Postfix, use the Local Mail Transfer Protocol (LMTP) to deliver emails to Dovecot. If the SMTP server runs:
- On the same host as Dovecot, use an LMTP socket
On a different host, use an LMTP service
By default, the LMTP protocol is not encrypted. However, if you configured TLS encryption, Dovecot uses the same settings automatically for the LMTP service. SMTP servers can then connect to it using the LMTPS protocol or the
STARTTLScommand over LMTP.
Prerequisites
- Dovecot is installed.
- If you want to configure an LMTP service, TLS encryption is configured in Dovecot.
Procedure
Verify that the LMTP protocol is enabled:
doveconf -a | grep -E "^protocols"
# doveconf -a | grep -E "^protocols" protocols = imap pop3 lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow The protocol is enabled, if the output contains
lmtp.If the
lmtpprotocol is disabled, edit the/etc/dovecot/dovecot.conffile, and appendlmtpto the values in theprotocolsparameter:protocols = ... lmtp
protocols = ... lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Depending on whether you need an LMTP socket or service, make the following changes in the
service lmtpsection in the/etc/dovecot/conf.d/10-master.conffile:LMTP socket: By default, Dovecot automatically creates the
/var/run/dovecot/lmtpsocket.Optional: Customize the ownership and permissions:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow LMTP service: Add a
inet_listenersub-section:Copy to Clipboard Copied! Toggle word wrap Toggle overflow
Configure
firewalldrules to allow only the SMTP server to access the LMTP port, for example:firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv4" source address="192.0.2.1/32" port protocol="tcp" port="24" accept" firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv6" source address="2001:db8:2::1/128" port protocol="tcp" port="24" accept" firewall-cmd --reload
# firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv4" source address="192.0.2.1/32" port protocol="tcp" port="24" accept" # firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv6" source address="2001:db8:2::1/128" port protocol="tcp" port="24" accept" # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow The subnet masks
/32for the IPv4 and/128for the IPv6 address limit the access to the specified addresses.Reload Dovecot:
systemctl reload dovecot
# systemctl reload dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
If you configured the LMTP socket, verify that Dovecot has created the socket and that the permissions are correct:
ls -l /var/run/dovecot/lmtp
# ls -l /var/run/dovecot/lmtp srw-------. 1 postfix postfix 0 Nov 22 17:17 /var/run/dovecot/lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow Configure the SMTP server to submit emails to Dovecot using the LMTP socket or service.
When you use the LMTP service, ensure that the SMTP server uses the LMTPS protocol or sends the
STARTTLScommand to use an encrypted connection.
9.7. Disabling the IMAP or POP3 service in Dovecot Link kopierenLink in die Zwischenablage kopiert!
By default, Dovecot provides IMAP and POP3 services. If you require only one of them, you can disable the other to reduce the surface for attack.
Prerequisites
- Dovecot is installed.
Procedure
Uncomment the
protocolsparameter in the/etc/dovecot/dovecot.conffile, and set it to use the required protocols. For example, if you do not require POP3, set:protocols = imap lmtp
protocols = imap lmtpCopy to Clipboard Copied! Toggle word wrap Toggle overflow By default, the
imap,pop3, andlmtpprotocols are enabled.Reload Dovecot:
systemctl reload dovecot
# systemctl reload dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow Close the ports that are no longer required in the local firewall. For example, to close the ports for the POP3S and POP3 protocols, enter:
firewall-cmd --remove-service=pop3s --remove-service=pop3 firewall-cmd --reload
# firewall-cmd --remove-service=pop3s --remove-service=pop3 # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display all ports in
LISTENmode opened by thedovecotprocess:ss -tulp | grep dovecot
# ss -tulp | grep dovecot tcp LISTEN 0 100 0.0.0.0:993 0.0.0.0:* users:(("dovecot",pid=1405,fd=44)) tcp LISTEN 0 100 0.0.0.0:143 0.0.0.0:* users:(("dovecot",pid=1405,fd=42)) tcp LISTEN 0 100 [::]:993 [::]:* users:(("dovecot",pid=1405,fd=45)) tcp LISTEN 0 100 [::]:143 [::]:* users:(("dovecot",pid=1405,fd=43))Copy to Clipboard Copied! Toggle word wrap Toggle overflow In this example, Dovecot listens only on the TCP ports
993(IMAPS) and143(IMAP).Note that Dovecot only opens a port for the LMTP protocol if you configure the service to listen on a port instead of using a socket.
9.8. Enabling server-side email filtering using Sieve on a Dovecot IMAP server Link kopierenLink in die Zwischenablage kopiert!
You can upload Sieve scripts to a server using the ManageSieve protocol. Sieve scripts define rules and actions that a server should validate and perform on incoming emails. For example, users can use Sieve to forward emails from a specific sender, and administrators can create a global filter to move mails flagged by a spam filter into a separate IMAP folder.
The ManageSieve plugin adds support for Sieve scripts and the ManageSieve protocol to a Dovecot IMAP server.
Use only clients that support using the ManageSieve protocol over TLS connections. Disabling TLS for this protocol causes clients to send credentials in plain text over the network.
Prerequisites
- Dovecot is configured and provides IMAP mailboxes.
- TLS encryption is configured in Dovecot.
- The mail clients support the ManageSieve protocol over TLS connections.
Procedure
Install the
dovecot-pigeonholepackage:yum install dovecot-pigeonhole
# yum install dovecot-pigeonholeCopy to Clipboard Copied! Toggle word wrap Toggle overflow Uncomment the following line in
/etc/dovecot/conf.d/20-managesieve.confto enable thesieveprotocol:protocols = $protocols sieve
protocols = $protocols sieveCopy to Clipboard Copied! Toggle word wrap Toggle overflow This setting activates Sieve in addition to the other protocols that are already enabled.
Open the ManageSieve port in
firewalld:firewall-cmd --permanent --add-service=managesieve firewall-cmd --reload
# firewall-cmd --permanent --add-service=managesieve # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow Reload Dovecot:
systemctl reload dovecot
# systemctl reload dovecotCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a client and upload a Sieve script. Use the following connection settings:
- Port: 4190
- Connection security: SSL/TLS
- Authentication method: PLAIN
- Send an email to the user who has the Sieve script uploaded. If the email matches the rules in the script, verify that the server performs the defined actions.
9.9. How Dovecot processes configuration files Link kopierenLink in die Zwischenablage kopiert!
The dovecot package provides the main configuration file /etc/dovecot/dovecot.conf and multiple configuration files in the /etc/dovecot/conf.d/ directory. Dovecot combines the files to build the configuration when you start the service.
The main benefit of multiple config files is to group settings and increase readability. If you prefer a single configuration file, you can instead maintain all settings in /etc/dovecot/dovecot.conf and remove all include and include_try statements from that file.
Chapter 10. Configuring printing Link kopierenLink in die Zwischenablage kopiert!
The Common UNIX Printing System (CUPS) manages printing on Red Hat Enterprise Linux. Users configure printers in CUPS on their host to print. Additionally, you can share printers in CUPS to use the host as a print server.
CUPS supports printing to:
- AirPrint™ and IPP Everywhere™ printers
- Network and local USB printers with legacy PostScript Printer Description (PPD)-based drivers
10.1. Installing and configuring CUPS Link kopierenLink in die Zwischenablage kopiert!
You can use CUPS to print from a local host. You can also use this host to share printers in the network and act as a print server.
Procedure
Install the
cupspackage:yum install cups
# yum install cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you configure CUPS as a print server, edit the
/etc/cups/cupsd.conffile, and make the following changes:If you want to remotely configure CUPS or use this host as a print server, configure on which IP addresses and ports the service listens:
Listen 192.0.2.1:631 Listen [2001:db8:1::1]:631
Listen 192.0.2.1:631 Listen [2001:db8:1::1]:631Copy to Clipboard Copied! Toggle word wrap Toggle overflow By default, CUPS listens only on
localhostinterfaces (127.0.0.1and::1). Specify IPv6 addresses in square brackets.ImportantDo not configure CUPS to listen on interfaces that allow access from untrustworthy networks, such as the internet.
Configure which IP ranges can access the service by allowing the respective IP ranges in the
<Location />directive:<Location /> Allow from 192.0.2.0/24 Allow from [2001:db8:1::1]/32 Order allow,deny </Location>
<Location /> Allow from 192.0.2.0/24 Allow from [2001:db8:1::1]/32 Order allow,deny </Location>Copy to Clipboard Copied! Toggle word wrap Toggle overflow In the
<Location /admin>directive, configure which IP addresses and ranges can access the CUPS administration services:<Location /admin> Allow from 192.0.2.15/32 Allow from [2001:db8:1::22]/128 Order allow,deny </Location>
<Location /admin> Allow from 192.0.2.15/32 Allow from [2001:db8:1::22]/128 Order allow,deny </Location>Copy to Clipboard Copied! Toggle word wrap Toggle overflow With these settings, only the hosts with the IP addresses
192.0.2.15and2001:db8:1::22can access the administration services.Optional: Configure IP addresses and ranges that are allowed to access the configuration and log files in the web interface:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
If you run the
firewalldservice and want to configure remote access to CUPS, open the CUPS port infirewalld:firewall-cmd --permanent --add-port=631/tcp firewall-cmd --reload
# firewall-cmd --permanent --add-port=631/tcp # firewall-cmd --reloadCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you run CUPS on a host with multiple interfaces, consider limiting the access to the required networks.
Enable and start the
cupsservice:systemctl enable --now cups
# systemctl enable --now cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a browser, and access
http://<hostname>:631. If you can connect to the web interface, CUPS works.Note that certain features, such as the
Administrationtab, require authentication and an HTTPS connection. By default, CUPS uses a self-signed certificate for HTTPS access and, consequently, the connection is not secure when you authenticate.
10.2. Configuring TLS encryption on a CUPS server Link kopierenLink in die Zwischenablage kopiert!
CUPS supports TLS-encrypted connections and, by default, the service enforces encrypted connections for all requests that require authentication. If no certificates are configured, CUPS creates a private key and a self-signed certificate. This is only sufficient if you access CUPS from the local host itself. For a secure connection over the network, use a server certificate that is signed by a certificate authority (CA).
Without encryption or with a self-signed certificates, a man-in-the-middle (MITM) attack can disclose, for example:
- Credentials of administrators when configuring CUPS using the web interface
- Confidential data when sending print jobs over the network
Prerequisites
- CUPS is configured.
- You created a private key, and a CA issued a server certificate for it.
- If an intermediate certificate is required to validate the server certificate, attach the intermediate certificate to the server certificate.
- The private key is not protected by a password because CUPS provides no option to enter the password when the service reads the key.
The Canonical Name (
CN) or Subject Alternative Name (SAN) field in the certificate matches one of the following:- The fully-qualified domain name (FQDN) of the CUPS server
- An alias that the DNS resolves to the server’s IP address
- The private key and server certificate files use the Privacy Enhanced Mail (PEM) format.
- Clients trust the CA certificate.
Procedure
Edit the
/etc/cups/cups-files.conffile, and add the following setting to disable the automatic creation of self-signed certificates:CreateSelfSignedCerts no
CreateSelfSignedCerts noCopy to Clipboard Copied! Toggle word wrap Toggle overflow Remove the self-signed certificate and private key:
rm /etc/cups/ssl/<hostname>.crt /etc/cups/ssl/<hostname>.key
# rm /etc/cups/ssl/<hostname>.crt /etc/cups/ssl/<hostname>.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the FQDN of the server:
hostname -f
# hostname -f server.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow Store the private key and server certificate in the
/etc/cups/ssl/directory, for example:mv /root/server.key /etc/cups/ssl/server.example.com.key mv /root/server.crt /etc/cups/ssl/server.example.com.crt
# mv /root/server.key /etc/cups/ssl/server.example.com.key # mv /root/server.crt /etc/cups/ssl/server.example.com.crtCopy to Clipboard Copied! Toggle word wrap Toggle overflow ImportantCUPS requires that you name the private key
<fqdn>.keyand the server certificate file<fqdn>.crt. If you use an alias, you must name the files<alias>.keyand<alias>.crt.Set secure permissions on the private key that enable only the
rootuser to read this file:chown root:root /etc/cups/ssl/server.example.com.key chmod 600 /etc/cups/ssl/server.example.com.key
# chown root:root /etc/cups/ssl/server.example.com.key # chmod 600 /etc/cups/ssl/server.example.com.keyCopy to Clipboard Copied! Toggle word wrap Toggle overflow Because certificates are part of the communication between a client and the server before they establish a secure connection, any client can retrieve the certificates without authentication. Therefore, you do not need to set strict permissions on the server certificate file.
Restore the SELinux context:
restorecon -Rv /etc/cups/ssl/
# restorecon -Rv /etc/cups/ssl/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the
CNand SAN fields of the certificate:Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the
CNor SAN fields in the server certificate contains an alias that is different from the server’s FQDN, add theServerAliasparameter to the/etc/cups/cupsd.conffile:ServerAlias alternative_name.example.com
ServerAlias alternative_name.example.comCopy to Clipboard Copied! Toggle word wrap Toggle overflow In this case, use the alternative name instead of the FQDN in the rest of the procedure.
By default, CUPS enforces encrypted connections only if a task requires authentication, for example when performing administrative tasks on the
/adminpage in the web interface.To enforce encryption for the entire CUPS server, add
Encryption Requiredto all<Location>directives in the/etc/cups/cupsd.conffile, for example:<Location /> ... Encryption Required </Location>
<Location /> ... Encryption Required </Location>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart CUPS:
systemctl restart cups
# systemctl restart cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
-
Use a browser, and access
https://<hostname>:631/admin/. This requires that your browser trusts the CA certificate. If the connection succeeds, you configured TLS encryption in CUPS correctly. -
If you configured that encryption is required for the entire server, access
http://<hostname>:631/. CUPS returns anUpgrade Requirederror in this case.
Troubleshooting
Display the
systemdjournal entries of thecupsservice:journalctl -u cups
# journalctl -u cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the journal contains an
Unable to encrypt connection: Error while reading fileerror after you failed to connect to the web interface by using the HTTPS protocol, verify the name of the private key and server certificate file.
10.3. Granting administration permissions to manage a CUPS server in the web interface Link kopierenLink in die Zwischenablage kopiert!
By default, members of the sys, root, and wheel groups can perform administration tasks in the web interface. However, certain other services use these groups as well. For example, members of the wheel groups can, by default, execute commands with root permissions by using sudo. To avoid that CUPS administrators gain unexpected permissions in other services, use a dedicated group for CUPS administrators.
Prerequisites
- CUPS is configured.
- The IP address of the client you want to use has permissions to access the administration area in the web interface.
Procedure
Create a group for CUPS administrators:
groupadd cups-admins
# groupadd cups-adminsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Add the users who should manage the service in the web interface to the
cups-adminsgroup:usermod -a -G cups-admins <username>
# usermod -a -G cups-admins <username>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Update the value of the
SystemGroupparameter in the/etc/cups/cups-files.conffile, and append thecups-admingroup:SystemGroup sys root wheel cups-admins
SystemGroup sys root wheel cups-adminsCopy to Clipboard Copied! Toggle word wrap Toggle overflow If only the
cups-admingroup should have administrative access, remove the other group names from the parameter.Restart CUPS:
systemctl restart cups
# systemctl restart cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Use a browser, and access
https://<hostname_or_ip_address>:631/admin/.NoteYou can access the administration area in the web UI only if you use the HTTPS protocol.
-
Start performing an administrative task. For example, click
Add printer. The web interface prompts for a username and password. To proceed, authenticate by using credentials of a user who is a member of the
cups-adminsgroup.If authentication succeeds, this user can perform administrative tasks.
10.4. Overview of packages with printer drivers Link kopierenLink in die Zwischenablage kopiert!
Red Hat Enterprise Linux (RHEL) provides different packages with printer drivers for CUPS. The following is a general overview of these packages and for which vendors they contain drivers:
| Package name | Drivers for printers |
|---|---|
|
| Zebra, Dymo |
|
| Kodak |
|
| Brother, Canon, Epson, Gestetner, HP, Infotec, Kyocera, Lanier, Lexmark, NRG, Ricoh, Samsung, Savin, Sharp, Toshiba, Xerox, and others |
|
| Brother, Canon, Epson, Fujitsu, HP, Infotec, Kyocera, Lanier, NRG, Oki, Minolta, Ricoh, Samsung, Savin, Xerox, and others |
|
| HP |
|
| HP |
|
| Samsung, Xerox, and others |
Note that some packages can contain drivers for the same printer vendor or model but with different functionality.
After installing the required package, you can display the list of drivers in the CUPS web interface or by using the lpinfo -m command.
10.5. Determining whether a printer supports driverless printing Link kopierenLink in die Zwischenablage kopiert!
CUPS supports driverless printing, which means that you can print without providing any hardware-specific software for the printer model. For this, the printer must inform the client about its capabilities and use one of the following standards:
- AirPrint™
- IPP Everywhere™
- Mopria®
- Wi-Fi Direct Print Services
You can use the ipptool utility to find out whether a printer supports driverless printing.
Prerequisites
- The printer or remote print server supports the Internet Printing Protocol (IPP).
- The host can connect to the IPP port of the printer or remote print server. The default IPP port is 631.
Procedure
Query the
ipp-versions-supportedanddocument-format-supportedattributes, and ensure that theget-printer-attributestest passes:For a remote printer, enter:
ipptool -tv ipp://<ip_address_or_hostname>:631/ipp/print get-printer-attributes.test | grep -E "ipp-versions-supported|document-format-supported|get-printer-attributes"
# ipptool -tv ipp://<ip_address_or_hostname>:631/ipp/print get-printer-attributes.test | grep -E "ipp-versions-supported|document-format-supported|get-printer-attributes" Get printer attributes using get-printer-attributes [PASS] ipp-versions-supported (1setOf keyword) = ... document-format-supported (1setOf mimeMediaType) = ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow For a queue on a remote print server, enter:
ipptool -tv ipp://<ip_address_or_hostname>:631/printers/<queue_name> get-printer-attributes.test | grep -E "ipp-versions-supported|document-format-supported|get-printer-attributes"
# ipptool -tv ipp://<ip_address_or_hostname>:631/printers/<queue_name> get-printer-attributes.test | grep -E "ipp-versions-supported|document-format-supported|get-printer-attributes" Get printer attributes using get-printer-attributes [PASS] ipp-versions-supported (1setOf keyword) = ... document-format-supported (1setOf mimeMediaType) = ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow
To ensure that driverless printing works, verify in the output:
-
The
get-printer-attributestest returnsPASS. - The IPP version that the printer supports is 2.0 or higher.
The list of formats contains one of the following:
-
application/pdf -
image/urf -
image/pwg-raster
-
-
For color printers, the output contains one of the mentioned formats and, additionally,
image/jpeg.
10.6. Adding a printer to CUPS by using the web interface Link kopierenLink in die Zwischenablage kopiert!
Before users can print through CUPS, you must add printers. You can use both network printers and printers that are directly attached to the CUPS host, for example over USB.
You can add printers by using the CUPS driverless feature or by using a PostScript Printer Description (PPD) file.
CUPS prefers driverless printing, and using drivers is deprecated.
Red Hat Enterprise Linux (RHEL) does not provide the name service switch multicast DNS plug-in (nss-mdns), which resolves requests by querying an mDNS responder. Consequently, automatic discovery and installation for local driverless printers by using mDNS is not available in RHEL. To work around this problem, install single printers manually or use cups-browsed to automatically install a high amount of print queues that are available on a remote print server.
Prerequisites
- CUPS is configured.
- You have permissions in CUPS to manage printers.
- If you use CUPS as a print server, you configured TLS encryption to securely transmit data over the network.
- The printer supports driverless printing, if you want to use this feature.
Procedure
Use a browser, and access
https://<hostname>:631/admin/.You must connect to the web interface by using the HTTPS protocol. Otherwise, CUPS prevents you from authenticating in a later step for security reasons.
- Click .
- If you are not already authenticated, CUPS prompts for credentials of an administrative user. Enter the username and password of an authorized user.
- If you decide to not use driverless printing and the printer you want to add is detected automatically, select it, and click .
If the printer was not detected:
Select the protocol that the printer supports.
If your printer supports driverless printing and you want to use this feature, select the
ipporippsprotocol.- Click .
Enter the URL to the printer or to the queue on a remote print server.
- Click .
Enter a name and, optionally, a description and location. If you use CUPS as a print server, and other clients should be able to print through CUPS on this printer, select also Share this printer.
- Select the printer manufacturer in the Make list. If the printer manufacturer is not on the list, select Generic or upload a PPD file for the printer.
- Click .
Select the printer model:
- If the printer supports driverless printing, select IPP Everywhere. Note that, if you previously installed printer-specific drivers locally, it is possible that the list also contains entries such as <printer_name> - IPP Everywhere.
- If the printer does not support driverless printing, select the model or upload the PPD file for the printer.
- Click
The settings and tabs on the Set printer options page depend on the driver and the features the printer supports. Use this page to set default options, such as for the paper size.
- Click .
Verification
- Open the Printers tab in the web interface.
- Click on the printer’s name.
- In the Maintenance list, select Print test page.
Troubleshooting
-
If you use driverless printing, and printing does not work, use the
lpadminutility to add the printer on the command line. For details, see Adding a printer to CUPS by using the lpadmin utility.
10.7. Adding a printer to CUPS by using the lpadmin utility Link kopierenLink in die Zwischenablage kopiert!
Before users can print through CUPS, you must add printers. You can use both network printers and printers that are directly attached to the CUPS host, for example over USB.
You can add printers by using the CUPS driverless feature or by using a PostScript Printer Description (PPD) file.
CUPS prefers driverless printing, and using drivers is deprecated.
Red Hat Enterprise Linux (RHEL) does not provide the name service switch multicast DNS plug-in (nss-mdns), which resolves requests by querying an mDNS responder. Consequently, automatic discovery and installation for local driverless printers by using mDNS is not available in RHEL. To work around this problem, install single printers manually or use cups-browsed to automatically install a high amount of print queues that are available on a remote print server.
Prerequisites
- CUPS is configured.
- The printer supports driverless printing, if you want to use this feature.
- The printer accepts data on port 631 (IPP), 9100 (socket), or 515 (LPD). The port depends on the method you use to connect to the printer.
Procedure
Add the printer to CUPS:
To add a printer with driverless support, enter:
lpadmin -p Demo-printer -E -v ipp://192.0.2.200/ipp/print -m everywhere
# lpadmin -p Demo-printer -E -v ipp://192.0.2.200/ipp/print -m everywhereCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
-m everywhereoption does not work for your printer, try-m driverless:<uri>, for example:-m driverless:ipp://192.0.2.200/ipp/print.To add a queue from a remote print server with driverless support, enter:
lpadmin -p Demo-printer -E -v ipp://192.0.2.201/printers/example-queue -m everywhere
# lpadmin -p Demo-printer -E -v ipp://192.0.2.201/printers/example-queue -m everywhereCopy to Clipboard Copied! Toggle word wrap Toggle overflow If the
-m everywhereoption does not work for your printer, try-m driverless:<uri>, for example:-m driverless:ipp://192.0.2.200/printers/example-queue.To add a printer with a driver in file, enter:
lpadmin -p Demo-printer -E -v socket://192.0.2.200/ -P /root/example.ppd
# lpadmin -p Demo-printer -E -v socket://192.0.2.200/ -P /root/example.ppdCopy to Clipboard Copied! Toggle word wrap Toggle overflow To add a queue from a remote print server with a driver in a file, enter:
lpadmin -p Demo-printer -E -v ipp://192.0.2.201/printers/example-queue -P /root/example.ppd
# lpadmin -p Demo-printer -E -v ipp://192.0.2.201/printers/example-queue -P /root/example.ppdCopy to Clipboard Copied! Toggle word wrap Toggle overflow To add a printer with a driver in the local driver database:
List the drivers in the database:
lpinfo -m
# lpinfo -m ... drv:///sample.drv/generpcl.ppd Generic PCL Laser Printer ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow Add the printer with the URI to the driver in the database:
lpadmin -p Demo-printer -E -v socket://192.0.2.200/ -m drv:///sample.drv/generpcl.ppd
# lpadmin -p Demo-printer -E -v socket://192.0.2.200/ -m drv:///sample.drv/generpcl.ppdCopy to Clipboard Copied! Toggle word wrap Toggle overflow
These commands uses the following options:
-
-p <printer_name>: Sets the name of the printer in CUPS. -
-E: Enables the printer and CUPS accepts jobs for it. Note that you must specify this option after-p. See the option’s description in the man page for further details. -
-v <uri>: Sets the URI to the printer or remote print server queue. -
-m <driver_uri>: Sets the PPD file based on the provided driver URI obtained from the local driver database. -
-P <PPD_file>: Sets the path to the PPD file.
Verification
Display the available printers:
lpstat -p
# lpstat -p printer Demo-printer is idle. enabled since Fri 23 Jun 2023 09:36:40 AM CESTCopy to Clipboard Copied! Toggle word wrap Toggle overflow Print a test page:
lp -d Demo-printer /usr/share/cups/data/default-testpage.pdf
# lp -d Demo-printer /usr/share/cups/data/default-testpage.pdfCopy to Clipboard Copied! Toggle word wrap Toggle overflow
10.8. Performing maintenance and administration tasks on CUPS printers by using the web interface Link kopierenLink in die Zwischenablage kopiert!
Printer administrators sometimes need to perform different tasks on a print server. For example:
- Maintenance tasks, such as temporary pausing a printer while a technician repairs a printer
- Administrative tasks, such as changing a printer’s default settings
You can perform these tasks by using the CUPS web interface.
Prerequisites
- CUPS is configured.
- You have permissions in CUPS to manage printers.
- If you use CUPS as a print server, you configured TLS encryption to not send credentials in plain text over the network.
- The printer already exists in CUPS.
Procedure
Use a browser, and access
https://<hostname>:631/printers/.You must connect to the web interface by using the HTTPS protocol. Otherwise, CUPS prevents you from authenticating in a later step for security reasons.
- Click on the name of the printer that you want to configure.
- Depending on whether you want to perform a maintenance or administration task, select the required action from the list.
- If you are not already authenticated, CUPS prompts for credentials of an administrative user. Enter the username and password of an authorized user.
- Perform the task.
10.9. Using Samba to print to a Windows print server with Kerberos authentication Link kopierenLink in die Zwischenablage kopiert!
With the samba-krb5-printing wrapper, Active Directory (AD) users who are logged in to Red Hat Enterprise Linux (RHEL) can authenticate to Active Directory (AD) by using Kerberos and then print to a local CUPS print server that forwards the print job to a Windows print server.
The benefit of this configuration is that the administrator of CUPS on RHEL does not need to store a fixed user name and password in the configuration. CUPS authenticates to AD with the Kerberos ticket of the user that sends the print job.
Red Hat supports only submitting print jobs to CUPS from your local system, and not to re-share a printer on a Samba print server.
Prerequisites
- The printer that you want to add to the local CUPS instance is shared on an AD print server.
- You joined the RHEL host as a member to the AD.
-
CUPS is installed on RHEL, and the
cupsservice is running. -
The PostScript Printer Description (PPD) file for the printer is stored in the
/usr/share/cups/model/directory.
Procedure
Install the
samba-krb5-printing,samba-client, andkrb5-workstationpackages:yum install samba-krb5-printing samba-client krb5-workstation
# yum install samba-krb5-printing samba-client krb5-workstationCopy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Authenticate as a domain administrator and display the list of printers that are shared on the Windows print server:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Optional: Display the list of CUPS models to identify the PPD name of your printer:
lpinfo -m ... samsung.ppd Samsung M267x 287x Series PXL ...
lpinfo -m ... samsung.ppd Samsung M267x 287x Series PXL ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow You require the name of the PPD file when you add the printer in the next step.
Add the printer to CUPS:
lpadmin -p "example_printer" -v smb://win_print_srv.ad.example.com/Example -m samsung.ppd -o auth-info-required=negotiate -E
# lpadmin -p "example_printer" -v smb://win_print_srv.ad.example.com/Example -m samsung.ppd -o auth-info-required=negotiate -ECopy to Clipboard Copied! Toggle word wrap Toggle overflow The command uses the following options:
-
-p printer_namesets the name of the printer in CUPS. -
-v URI_to_Windows_printersets the URI to the Windows printer. Use the following format:smb://host_name/printer_share_name. -
-m PPD_filesets the PPD file the printer uses. -
-o auth-info-required=negotiateconfigures CUPS to use Kerberos authentication when it forwards print jobs to the remote server. -
-Eenables the printer and CUPS accepts jobs for the printer.
-
Verification
- Log into the RHEL host as an AD domain user.
Authenticate as an AD domain user:
kinit domain_user_name@AD_KERBEROS_REALM
# kinit domain_user_name@AD_KERBEROS_REALMCopy to Clipboard Copied! Toggle word wrap Toggle overflow Print a file to the printer you added to the local CUPS print server:
lp -d example_printer file
# lp -d example_printer fileCopy to Clipboard Copied! Toggle word wrap Toggle overflow
10.10. Using cups-browsed to locally integrate printers from a remote print server Link kopierenLink in die Zwischenablage kopiert!
The cups-browsed service uses DNS service discovery (DNS-SD) and CUPS browsing to make all or a filtered subset of shared remote printers automatically available in a local CUPS service.
For example, administrators can use this feature on workstations to make only printers from a trusted print server available in a print dialog of applications. It is also possible to configure cups-browsed to filter the browsed printers by certain criteria to reduce the number of listed printers if a print server shares a large number of printers.
If the print dialog in an application uses other mechanisms than, for example DNS-SD, to list remote printers, cups-browsed has no influence. The cups-browsed service also does not prevent users from manually accessing non-listed printers.
Prerequisites
- The CUPS service is configured on the local host.
A remote CUPS print server exists, and the following conditions apply to this server:
- The server listens on an interface that is accessible from the client.
-
The
Allow fromparameter in the server’s<Location />directive in the/etc/cups/cups.conffile allows access from the client’s IP address. - The server shares printers.
- Firewall rules allow access from the client to the CUPS port on the server.
Procedure
Edit the
/etc/cups/cups-browsed.conffile, and make the following changes:Add
BrowsePollparameters for each remote CUPS server you want to poll:BrowsePoll remote_cups_server.example.com BrowsePoll 192.0.2.100:1631
BrowsePoll remote_cups_server.example.com BrowsePoll 192.0.2.100:1631Copy to Clipboard Copied! Toggle word wrap Toggle overflow Append
:<port>to the hostname or IP address if the remote CUPS server listens on a port different from 631.Optional: Configure a filter to limit which printers are shown in the local CUPS service. For example, to filter for queues whose name contain
sales_, add:BrowseFilter name sales_
BrowseFilter name sales_Copy to Clipboard Copied! Toggle word wrap Toggle overflow You can filter by different field names, negate the filter, and match the exact values. For further details, see the parameter description and examples in the
cups-browsed.conf(5)man page on your system.Optional: Change the polling interval and timeout to limit the number of browsing cycles:
BrowseInterval 1200 BrowseTimeout 6000
BrowseInterval 1200 BrowseTimeout 6000Copy to Clipboard Copied! Toggle word wrap Toggle overflow Increase both
BrowseIntervalandBrowseTimeoutin the same ratio to avoid situations in which printers disappear from the browsing list. This mean, multiply the value ofBrowseIntervalby 5 or a higher integer, and use this result value forBrowseTimeout.By default,
cups-browsedpolls remote servers every 60 seconds and the timeout is 300 seconds. However, on print servers with many queues, these default values can cost many resources.
Enable and start the
cups-browsedservice:systemctl enable --now cups-browsed
# systemctl enable --now cups-browsedCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
List the available printers:
lpstat -v
# lpstat -v device for Demo-printer: implicitclass://Demo-printer/ ...Copy to Clipboard Copied! Toggle word wrap Toggle overflow If the output for a printer contains
implicitclass, thecups-browsedservice manages the printer in CUPS.
10.11. Accessing the CUPS logs in the systemd journal Link kopierenLink in die Zwischenablage kopiert!
By default, CUPS stores log messages in the systemd journal. This includes:
- Error messages
- Access log entries
- Page log entries
Prerequisites
Procedure
Display the log entries:
To display all log entries, enter:
journalctl -u cups
# journalctl -u cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow To display the log entries for a specific print job, enter:
journalctl -u cups JID=<print_job_id>
# journalctl -u cups JID=<print_job_id>Copy to Clipboard Copied! Toggle word wrap Toggle overflow To display log entries within a specific time frame, enter:
journalectl -u cups --since=<YYYY-MM-DD> --until=<YYYY-MM-DD>
# journalectl -u cups --since=<YYYY-MM-DD> --until=<YYYY-MM-DD>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Replace
YYYYwith the year,MMwith the month, andDDwith the day.
10.12. Configuring CUPS to store logs in files instead of the systemd journal Link kopierenLink in die Zwischenablage kopiert!
By default, CUPS stores log messages in the systemd journal. Alternatively, you can configure CUPS to store log messages in files.
Prerequisites
Procedure
Edit the
/etc/cups/cups-files.conffile, and set theAccessLog,ErrorLog, andPageLogparameters to the paths where you want to store these log files:AccessLog /var/log/cups/access_log ErrorLog /var/log/cups/error_log PageLog /var/log/cups/page_log
AccessLog /var/log/cups/access_log ErrorLog /var/log/cups/error_log PageLog /var/log/cups/page_logCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you configure CUPS to store the logs in a directory other than
/var/log/cups/, set thecupsd_log_tSELinux context on this directory, for example:semanage fcontext -a -t cupsd_log_t "/var/log/printing(/.*)?" restorecon -Rv /var/log/printing/
# semanage fcontext -a -t cupsd_log_t "/var/log/printing(/.*)?" # restorecon -Rv /var/log/printing/Copy to Clipboard Copied! Toggle word wrap Toggle overflow Restart the
cupsservice:systemctl restart cups
# systemctl restart cupsCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display the log files:
cat /var/log/cups/access_log cat /var/log/cups/error_log cat /var/log/cups/page_log
# cat /var/log/cups/access_log # cat /var/log/cups/error_log # cat /var/log/cups/page_logCopy to Clipboard Copied! Toggle word wrap Toggle overflow If you configured CUPS to store the logs in a directory other than
/var/log/cups/, verify that the SELinux context on the log directory iscupsd_log_t:ls -ldZ /var/log/printing/
# ls -ldZ /var/log/printing/ drwxr-xr-x. 2 lp sys unconfined_u:object_r:cupsd_log_t:s0 6 Jun 20 15:55 /var/log/printing/Copy to Clipboard Copied! Toggle word wrap Toggle overflow
10.13. Setting up a high-availability CUPS print server environment Link kopierenLink in die Zwischenablage kopiert!
If your clients require access to printers without interruption, you can set up CUPS on multiple hosts and use the print queue browsing feature to provide high availability. Print clients then automatically configure print queues shared by the different print servers. If a client sends a print job to its local print queue, CUPS on the client routes the job to one of the print servers which processes the job and sends it to the printer.
Procedure
Set up CUPS on two or more servers:
- Install and configure CUPS.
- Enable TLS encryption.
Add print queues to all CUPS instances by using the lpadmin utility or the web interface. If you use the web interface, ensure that you select the Share this printer option while you add the printer. The
lpadminutility enables this setting by default.ImportantFor the high-availability scenario, each queue on one print server requires a queue with exactly the same queue name on the other servers. You can display the queue names on each server by using the
lpstat -ecommand.Optional: You can configure the queues on each server to refer to different printers.
On print clients:
Edit the
/etc/cups/cups-browsed.conffile, and addBrowsePolldirectives for each CUPS print server:BrowsePoll print_server_1.example.com:631 BrowsePoll print_server_2.example.com:631
BrowsePoll print_server_1.example.com:631 BrowsePoll print_server_2.example.com:631Copy to Clipboard Copied! Toggle word wrap Toggle overflow Enable and start both the
cupsandcups-browsedservice:systemctl enable --now cups cups-browsed
# systemctl enable --now cups cups-browsedCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Verification
Display the available printers on a client:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow The example output shows that the Demo-printer queue uses the
implicitclassback end. As a result,cups-browsedroutes print jobs for this queue to the hosts specified in theBrowsePolldirectives on this client.
10.14. Accessing the CUPS documentation Link kopierenLink in die Zwischenablage kopiert!
CUPS provides browser-based access to the service’s documentation that is installed on the CUPS server. This documentation includes:
- Administration documentation, such as for command-line printer administration and accounting
- Man pages
- Programming documentation, such as the administration API
- References
- Specifications
Prerequisites
- CUPS is installed and running.
- The IP address of the client you want to use has permissions to access the web interface.
Procedure
-
Use a browser, and access
http://<hostname_or_ip_address>:631/help/. -
Expand the entries in
Online Help Documents, and select the documentation you want to read.