How to install mail server (postfix, dovecot, webmail and spamassasin) on Centos 8 with selinux enabled

Introduction

In order to set up a full simple mail server, this guide takes advantage of Postfix as an SMTP server, Dovecot to provide POP/IMAP functionality, and RoundCube as a webmail program or client so that users can check and receive email from their favorite web browsers.

Dovecot: Dovecot is an open-source IMAP and POP3 email server for Linux/UNIX-like systems, written with security primarily in mind.
Postfix: Postfix is a free and open-source mail transfer agent (MTA) that routes and delivers electronic mail from one server to another over the internet.
Roundcube: Once the mails have been delivered into a mailbox, most users would need an easy to use interface to read their mails. Roundcube does this pretty well. It is a browser-based multilingual IMAP client with an application-like user interface. It provides full functionality you expect from an email client, including MIME support, address book, folder manipulation, message searching and spell checking.

So, at first, as usual, we use fully updated system:

dnf update -y

Now, configure some prerequisites.

Before proceeding further, also ensure that no other MTAs such as Sendmail are existing as this will cause conflict with Postfix configuration. To remove Sendmail, for example, run the command:

dnf remove sendmail

Now set FQDN (Fully Qualifed Domain Name) and set hostname:

hostnamectl set-hostname mail.example.com
exec bash
vim /etc/hosts
192.0.2.1 mail.example.com

How to install mariadb server, apache web server and php version 7.3 (or 7.4) you can find at another post, like: https://www.gonscak.sk/?p=530

So, now, we can install out MTA Postfix, very simple, with mysql support (our users will be stored in mysql database):

dnf install postfix postfix-mysql -y
systemctl start postfix
systemctl enable postfix

To check postfix status, write this command:

systemctl status postfix

Now, we enable some ports of firewall. If you want use POP3, enable it. I prefer not to use. In order to send emails from your server, port 25 (outbound) must be open. To be able to send emails using a desktop email client (Thunderbird or Outlook), we need to enable the submission service in Postfix. And to encrypt our communications, we need a TLS certificate.

firewall-cmd --permanent --add-service={http,https,smtp-submission,smtps,imap,imaps}
systemctl reload firewalld

sudo firewall-cmd --permanent --add-service={pop3,pop3s}
systemctl reload firewalld

When we configure a desktop email client, enabling encryption is always a good idea. We can easily obtain a free TLS certificate from Let’s Encrypt. Issue the following commands to install Let’s Encrypt client (certbot) on CentOS 8/RHEL 8 from the EPEL repository. If you don’t have a web server running yet, I recommend you install one (Apache).

dnf install epel-release -y
dnf install certbot python3-certbot-apache
dnf install httpd
systemctl start httpd
systemctl enable httpd

We create and simple virtual host for Apache to obtain certificate. Like this:

vim /etc/httpd/conf.d/mail.gonscak.sk.conf

        
        ServerName mail.gonscak.sk

        DocumentRoot /var/www/html/


systemctl reload httpd

Now, if everything is ok (Apache is realoaded), we can obtain our TLS certificate for postfix/dovecot in future settings:

certbot --apache --email you@example.com -d mail.example.com

and the results:

Congratulations! You have successfully enabled https://mail.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/mail.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/mail.example.com/privkey.pem

Configuring Postfix

To send emails from a desktop email client, we need to enable the submission service of Postfix so that the email client can submit emails to Postfix SMTP server. Edit the master.cf file.

vim /etc/postfix/master.cf

In submission section, uncomment or add the following lines. Please allow at least one whitespace (tab or spacebar) before each -o.  In postfix configurations, a preceding whitespace character means that this line is continuation of the previous line.

submission inet n - n - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_tls_wrappermode=no
-o smtpd_sasl_auth_enable=yes
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth

The above configuration enables the submission daemon of Postfix and requires TLS encryption. So later on our desktop email client can connect to the submission daemon in TLS encryption. The submission daemon listens on TCP port 587. STARTTLS is used to encrypt communications between email client and the submission daemon.

Microsoft Outlook only supports submission over port 465. If you are going to use Microsoft outlook mail client, then you also need to enable submission service on port 465 by adding the following lines in the file.

smtps inet n - n - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_relay_restrictions=permit_sasl_authenticated,reject
-o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth

Save and close this file for the moment. Now we configure main configurations of Postfix. open file and edit this lines as mine. If you dont have these lines, please add they.

cp /etc/postfix/main.cf /etc/postfix/main.cf.orig
vim /etc/postfix/main.cf

smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem
smtpd_tls_loglevel = 1
smtp_tls_loglevel = 1

#Force TLSv1.3 or TLSv1.2 
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1 
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1 
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1 
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1

myhostname = mail.example.com
mydomain = example.com
message_size_limit = 31457280

Save and close file. Now restart postfix to ensure, that the change of settings take effect:

systemctl restart postfix

If you run the following command, you will see Postfix is now listening on port 587 and 465.

netstat -lnpt | grep master

bash: netstat: command not found
#if we havent's these command, check who provide it:

dnf provides netstat

Output:

net-tools-2.0-0.51.20160912git.el8.x86_64 : Basic networking tools
Repo : BaseOS
Matched from:
Filename : /usr/bin/netstat

So install it:

dnf install net-tools
netstat -lnpt | grep master

tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 62343/master
tcp 0 0 127.0.0.1:587 0.0.0.0:* LISTEN 62343/master
tcp 0 0 127.0.0.1:465 0.0.0.0:* LISTEN 62343/master

Installing Dovecot IMAP Server and configuring

So, as usual, install imap server dovecot with mysql support:

dnf install dovecot dovecot-mysql
dovecot --version

2.3.8 (9df20d2db)

Now start it and enable after boot:

systemctl start dovecot
systemctl enable dovecot

Open dovecot config and edit or add this line:

cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig
vim /etc/dovecot/dovecot.con

protocols = imap

Save and close file. then restart dovecot:

systemctl restart dovecot.service

systemctl status dovecot.service
● dovecot.service - Dovecot IMAP/POP3 email server
Loaded: loaded (/usr/lib/systemd/system/dovecot.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2020-09-18 11:32:49 CEST; 28s ago

For storing messages, we use Maildir format. Every mail is stored in separate file in precise directory structure. So, create a directory for your domain/domains and edit line/lines like next:

mkdir -p /var/vmail/vhosts/example.com
cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig
vim /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:/var/vmail/vhosts/%d/%n
mail_privileged_group = mail

Save file and exit. Now assign user dovecot to group mail and vmail, for reading Inbox and writing to folder destinations:

groupadd -g 5000 vmail
useradd -u 5000 -g vmail -s /usr/bin/nologin -d /var/vmail -m vmail
gpasswd -a dovecot mail
usermod -a -G vmail dovecot
semanage fcontext --add --type mail_home_rw_t --range s0 '/var/vmail/vhosts(/.*)?'
restorecon -Rv /var/vmail/vhosts

Set a database for users, domains and aliases

So, log in mysql as root and create a database, in which we will be storring informations about used domains, users, passwords and mail aliases for users. Then create tables, for this informations. Adjust your informations…

mysql -u root -p

CREATE DATABASE maildb;
GRANT SELECT ON maildb.* TO 'usermail'@'localhost' IDENTIFIED BY 'PASSWORD';
GRANT update ON maildb.* TO 'usermail'@'localhost' IDENTIFIED BY 'PASSWORD';
FLUSH PRIVILEGES;

USE maildb;

CREATE TABLE virtual_domains (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE virtual_users (
id INT NOT NULL AUTO_INCREMENT,
domain_id INT NOT NULL,
password VARCHAR(106) NOT NULL,
email VARCHAR(120) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE virtual_aliases (
id INT NOT NULL AUTO_INCREMENT,
domain_id INT NOT NULL,
source varchar(200) NOT NULL,
destination varchar(100) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO maildb.virtual_domains
(id ,name)
VALUES
('1', 'example.com');

INSERT INTO maildb.virtual_users
(id, domain_id, password , email)
VALUES
('1', '7', 'UserPassword', 'user1@example.com');

INSERT INTO maildb.virtual_aliases
(id, domain_id, source, destination)
VALUES
('1', '1', 'alias1@example.com', 'user1@example.com');

Now, we can see, that the password is stored in our databases in plaintext:

MariaDB [maildb]> select * from virtual_users;
+----+-----------+------------+----------------------+
| id | domain_id | password | email |
+----+-----------+------------+----------------------+
| 1 | 7 | UserPassword | user1@example.com |
+----+-----------+------------+----------------------+
1 row in set (0.000 sec)

So we change it:

update virtual_users set password = ENCRYPT('UserPassword', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))) where email = 'user1@example.com';

select * from virtual_users;

MariaDB [maildb]> select * from virtual_users;
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+
| id | domain_id | password | email |
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+
| 1 | 7 | $6$b308975352080ba6$TFt0bZNCPZdgLtn2S9hHMQSdxFikxGDpLqNVap7r/q9OgHGP/EddEzc9Oc3Ww4nvinbrR2pGNgLUpK.PQ1JVD/ | user1@example.com |
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+
1 row in set (0.000 sec)

And if you want, now you can add your user right with shit encrypt form:

INSERT INTO maildb.virtual_users
(id, domain_id, password , email)
VALUES
('2', '7', ENCRYPT('password2', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'user2@example.com');

And now, we can see:

select * from virtual_users;
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+
| id | domain_id | password | email |
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+
| 1 | 7 | $6$b308975352080ba6$TFt0bZNCPZdgLtn2S9hHMQSdxFikxGDpLqNVap7r/q9OgHGP/EddEzc9Oc3Ww4nvinbrR2pGNgLUpK.PQ1JVD/ | user1@example.com |
| 2 | 7 | $6$93809b2da2242ede$toapOIav4kqmLiFl03xvZiEe9LXvqDs.nT5Ristkmy0zCyk6fc.JjjlekElcJ9MczPv5e9b4eH/lumkgOpZq6/ | user2@example.com |
+----+-----------+------------------------------------------------------------------------------------------------------------+----------------------+

Now we can exit from mariadb server with command “exit;”and continue

Now, we add som configuration files for postfix to be sure, that postfix will understand, where our information about users, domains and aliases are and how to connect to them:

cat > /etc/postfix/mysql-virtual-mailbox-domains.cf << EOF
user = usermail
password = PASSWORD
hosts = 127.0.0.1
dbname = maildb
query = SELECT 1 FROM virtual_domains WHERE name='%s'
EOF

cat > /etc/postfix/mysql-virtual-mailbox-maps.cf << EOF
user = usermail
password = PASSWORD
hosts = 127.0.0.1
dbname = maildb
query = SELECT 1 FROM virtual_users WHERE email='%s'
EOF

cat > /etc/postfix/mysql-virtual-alias-maps.cf << EOF
user = usermail
password = PASSWORD
hosts = 127.0.0.1
dbname = maildb
query = SELECT destination FROM virtual_aliases WHERE source='%s'
EOF

cat > /etc/postfix/mysql-virtual-email2email.cf << EOF
user = usermail
password = PASSWORD
hosts = 127.0.0.1
dbname = maildb
query = SELECT email FROM virtual_users WHERE email='%s'
EOF

cat > mysql-virtual-sender-alias-maps.cf << EOF
user = usermail
password = PASSWORD
hosts = 127.0.0.1
dbname = maildb
query = select destination from virtual_aliases where source='%s'
EOF

Now, we can check, if postifx understand this:

postmap -q example.com mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
1

postmap -q user1@example.com mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
1

postmap -q alias1@example.com mysql:/etc/postfix/mysql-virtual-alias-maps.cf
user1@example.com

Now, we can continue with configuring again Postfix and Dovecot. In Postfix add these lines, we created before:

vim /etc/postfix/main.cf

virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf
smtpd_sender_login_maps = mysql:/etc/postfix/mysql-virtual-email2email.cf, mysql:/etc/postfix/mysql-virtual-sender-alias-maps.cf



smtpd_helo_restrictions =
 permit_sasl_authenticated,
 permit_mynetworks,
 reject_non_fqdn_hostname,
 reject_invalid_hostname,
 reject_unknown_hostname,
 permit

smtpd_recipient_restrictions =
 permit_sasl_authenticated,
 permit_mynetworks,
 reject_unauth_destination,
 reject_invalid_hostname,
 reject_unknown_recipient_domain,
 reject_non_fqdn_recipient,
 permit

smtpd_sender_restrictions =
 reject_authenticated_sender_login_mismatch,
 permit_sasl_authenticated,
 check_sender_access hash:/etc/postfix/access,
 reject_unknown_sender_domain,
 reject_non_fqdn_sender

Check, if ist Postfix properly configured and there is no syntax mistake:

postfix check
#if nothing is displayed, is OK and then:
systemctl restart postfix.service

Now, continue with dovecot. Uncoment lines, or modify/add:

cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig
vim /etc/dovecot/conf.d/10-auth.conf

disable_plaintext_auth = yes
auth_mechanisms = plain login
!include auth-sql.conf.ext

Now, edit /etc/dovecot/conf.d/auth-sql.conf.ext and adjust:

passdb {
driver = sql
args = /etc/dovecot/dovecot-sql.conf.ext
}

userdb {
driver = static
args = uid=vmail gid=vmail home=/var/vmail/vhosts/%d/%n
}

And edit/or add file:

/etc/dovecot/dovecot-sql.conf.ext

driver = mysql
connect = host=127.0.0.1 dbname=maildb user=usermail password=PASSWORD
default_pass_scheme = SHA512-CRYPT
password_query = SELECT email as user, password FROM virtual_users WHERE email='%u';

Next, edit an adjust dovecot ssl for using our LE certificate:

cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.orig
vim /etc/dovecot/conf.d/10-ssl.conf

ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem
ssl_dh = </etc/dovecot/dh.pem

ssl_min_protocol = TLSv1
ssl_prefer_server_ciphers = yes

save and close. Now generate dh.pem. It take a long time, in my case, 10minutes:

openssl dhparam -out /etc/dovecot/dh.pem 4096

Now, edit SASL authentication between Postfix and Dovecot:

cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig
vim /etc/dovecot/conf.d/10-master.conf

service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}

Then, we set Dovecot, to auto-create folders, after user first login. To enable this, edit lines like below:

cp /etc/dovecot/conf.d/15-mailboxes.conf  /etc/dovecot/conf.d/15-mailboxes.conf.orig
vim /etc/dovecot/conf.d/15-mailboxes.conf

mailbox Trash {
auto = create
special_use = \Trash
}

mailbox Drafts {
auto = create
special_use = \Drafts
}
...

Now, restart dovecot and check, if working, for now somehow 🙂

systemctl restart dovecot
systemctl restart postfix
netstat -lnpt | grep dovecot
tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 164849/dovecot
tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 164849/dovecot
tcp6 0 0 :::993 :::* LISTEN 164849/dovecot
tcp6 0 0 :::143 :::* LISTEN 164849/dovecot

#if problem, watch log why:
systemctl status dovecot

By default, Postfix uses its builtin local delivery agent (LDA) to move inbound emails to the message store (inbox, sent, trash, Junk, etc). We can configure it to use Dovecot to deliver emails, via the LMTP protocol, which is a simplified version of SMTP. LMTP allows for a highly scalable and reliable mail system. This step is required if you want to use the sieve plugin to filter inbound messages to different folders.

Edit Dovecot main configuration files, and next postfix configuration:

vim /etc/dovecot/dovecot.conf

protocols = imap lmtp
vim /etc/dovecot/conf.d/10-master.conf

service lmtp { 
unix_listener /var/spool/postfix/private/dovecot-lmtp { 
mode = 0600 
user = postfix 
group = postfix 
  }
}
vim /etc/postfix/main.cf

mailbox_transport = lmtp:unix:private/dovecot-lmtp
virtual_transport = lmtp:unix:private/dovecot-lmtp
smtputf8_enable = no
systemctl restart postfix dovecot

Now, we can set up our desktop clients for serving our mails. I prefer Mozilla Thunderbird. So , in settings, use this variables:

IMAP, port 993, SSL/TLS, normal password
or
IMAP, port 143, STARTTLS, normal password
or
SMTP, port 587, STARTTLS, normal password
or 
SMPT, port 465, SSL/TLS, normal password
username: user1@example.com
password: yours
server for incoming and outgoing: mail.example.com

I prefer using port 465/SSL and 993/SSL. Because this are native SSL ports.

Improoving email delivery with SPF and DKIM records

Until now, we have working mail server with Postfix and Dovecot with dekstop email clients (Thunderbird). We can send mail to the world, and world to us (of couse, we must have correct DNS names/records, like MX, A and PTR. But sometimes, may happend, that our email is mark as SPAM. So we are going to look at how to improve email delivery to recipient’s inbox by setting up SPF and DKIM on CentOS/RHEL server.

So, what is SPF?

I use wikipedia: Sender Policy Framework (SPF) is an email authentication method designed to detect forging sender addresses during the delivery of the email. SPF alone, though, is limited only to detect a forged sender claimed in the envelope of the email which is used when the mail gets bounced.

SPF record specifies which hosts or IP addresses are allowed to send emails on behalf of a domain. You should allow only your own email server or your ISP’s server to send emails for your domain.

Now, we must add SPF record to our domain. It is TXT record, like this:

TXT  @   "v=spf1 mx -all"

Where:

  • TXT indicates this is a TXT record.
  • @ in the name field represent the apex domain name.
  • v=spf1 indicates this is a SPF record and the SPF record version is SPF1.
  • mx means all hosts listed in the MX records are allowed to send emails for your domain and all other hosts are disallowed.
  • -all indicates that emails from your domain should only come from hosts specified in the SPF record. Emails sent from other hosts will be flagged as fail.

If we test for our domain MX record, this SPF record is pointing only to this one. So receiving mailserver can evaluate, that sender is authorized to use this mail server:

dig -t txt example.com
;; ANSWER SECTION:
example.com. 600 IN TXT "v=spf1 a mx -all"

dig -t mx example.com
;; ANSWER SECTION:
example.com. 600 IN MX 10 mail.example.com.

dig mail.example.com
;; ANSWER SECTION:
mail.example.com. 599 IN A 192.0.2.1

Of course, you can use online SPF validator such as https://mxtoolbox.com/SuperTool.aspx to see which hosts are allowed to send emails for your domain and debug your SPF record if any error occurs.

Configuring SPF Policy Agent

We also need to tell our Postfix SMTP server to check the SPF record of incoming emails to detect forged emails. First install required packages:

dnf install pypolicyd-spf

Then add a user for policyd-spf.

adduser policyd-spf --user-group --no-create-home -s /bin/false

And dit the Postfix master process configuration file. Add the following lines at the end of the file, which tells Postfix to start the SPF policy daemon when it’s starting itself. Policyd-spf will run as the policyd-spf user.

vim /etc/postfix/master.cf

policyd-spf unix - n n - 0 spawn 
  user=policyd-spf argv=/usr/libexec/postfix/policyd-spf

Save and close the file. Next, edit Postfix main configuration file. Append the following line at smtpd_recipient_restriction.

vim /etc/postfix/main.cf

smtpd_recipient_restrictions =
permit_sasl_authenticated,
permit_mynetworks,
reject_unauth_destination,
check_policy_service unix:private/policyd-spf

Save and close the file. Then restart Postfix.

systemctl restart postfix

Next time, when you receive an email from a domain that has an SPF record, you can see the SPF check results in the raw email header. The following header indicates the sender sent the email from an authorized host:

Received-SPF: Pass (mailfrom) identity=mailfrom;

If you see in log receiver=<UNKNOWN>, then you can add variable, to show receiver:

vim /etc/python-policyd-spf/policyd-spf.conf
Hide_Receiver = No

To test the SPF records with your domain, try:

https://vamsoft.com/support/tools/spf-policy-tester

So, what is DKIM?

According to wiki:

DomainKeys Identified Mail (DKIM) is an email authentication method designed to detect forged sender addresses in emails (email spoofing), a technique often used in phishing and email spam.

DKIM allows the receiver to check that an email claimed to have come from a specific domain was indeed authorized by the owner of that domain. It achieves this by affixing a digital signature, linked to a domain name, to each outgoing email message. The recipient system can verify this by looking up the sender’s public key published in the DNS. A valid signature also guarantees that some parts of the email (possibly including attachments) have not been modified since the signature was affixed. Usually, DKIM signatures are not visible to end-users, and are affixed or verified by the infrastructure rather than the message’s authors and recipients.

Simply: DKIM uses a private key to add a signature to emails sent from your domain. Receiving SMTP servers verify the signature by using the corresponding public key, which is published in your domain’s DNS records.

Now, we must install som package:

dnf install opendkim opendkim-tools

At beginig, we must edit main configuration file of opendkim and adjust the line:

/etc/opendkim.conf

Mode sv

By default, OpenDKIM runs in verification mode (v), which will verify the DKIM signature of incoming email messages. We need to sign outgoing emails, so change this line to the following to enable signing mode.

Find the following line and comment it out, because we will use separate keys for each domain name.

KeyFile /etc/opendkim/keys/default.private

Next, find the following 4 lines and uncomment them.


KeyTable /etc/opendkim/KeyTable
SigningTable refile:/etc/opendkim/SigningTable
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
InternalHosts refile:/etc/opendkim/TrustedHosts

Create Signing Table, Key Table and Trusted Hosts File

Edit the signing table file.

vim /etc/opendkim/SigningTable

Add the following line at the end of this file. This tells OpenDKIM that if a sender on your server is using a @your-domain.com address, then it should be signed with the private key identified by 20200925._domainkey.example.com.

*@example.com 20200925._domainkey.example.com

20200925 is the DKIM selector. A domain name might have multiple DKIM keys. The DKIM selector allows you to choose a particular DKIM key. You can use whatever name for the DKIM selector, but I found it’s convenient to use the current date (September 25, 2020) as the DKIM selector. Save and close the file. Then edit the key table file.

vim /etc/opendkim/KeyTable

Add the following line, which specifies the location of the DKIM private key.

20200925._domainkey.example.com example.com:20200925:/etc/opendkim/keys/example.com/20200925.private

Save and close the file. Next, edit the trusted hosts file.

vim /etc/opendkim/TrustedHosts

127.0.0.0.1 and ::1 are included in this file by default. Now add the following line. This tells OpenDKIM that if an email is coming from your own domain name, then OpenDKIM should not perform DKIM verification on the email.

*.example.com

Save and close the file.

Generate Private/Public Keypair

Since DKIM is used to sign outgoing messages and verify incoming messages, you need to generate a private key to sign outgoing emails and a public key for receiving SMTP servers to verify the DKIM signature of your email. Public key will be published in DNS.

Create a separate folder for the domain.

mkdir /etc/opendkim/keys/example.com

Generate keys using opendkim-genkey tool.

opendkim-genkey -b 2048 -d example.com -D /etc/opendkim/keys/example.com -s 20200925 -v

The above command will create 2048 bits keys. -d (domain) specifies the domain. -D (directory) specifies the directory where the keys will be stored. I use 20200925 as the DKIM selector. Once the command is executed, the private key will be written to 20200925.private file and the public key will be written to 20200925.txt file:

opendkim-genkey: generating private key
opendkim-genkey: private key written to 20200925.private
opendkim-genkey: extracting public key
opendkim-genkey: DNS TXT record written to 20200925.txt

And adjust ownership:

chown opendkim:opendkim /etc/opendkim/keys/ -R

Publish Your Public Key in DNS Records

Display the public key. The string after the p parameter is the public key:

cat /etc/opendkim/keys/example.com/20200925.txt

20200925._domainkey IN TXT ( "v=DKIM1; k=rsa; "
"p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4dFfxvjFLHGpPX4chiCrcq+88WkARccudstwfchyioXkzZOicB7cxRd992H3JQFYvdGXQ+KEAO8eEelcQBv4ee+SCQjzVH70k/gvVxbVwJ6IicYyMELy1Mh0alQ7oOAFNIhyafueEzy/sSefXva1dw7lYh6t4NjypFUbMpIWH/sUyLEZqkWBTYfbKzbj52kML8LbWeWoQJHB2a"
"7jd9GPRkXpwMpbumKPdLD+wINIyr9L4r31/TIVpVDq7ZP6JrksyBHVFSWZQsODLIHjLL2ln/o/VSUcPXxy8H/44Xpzw2RHwcGXrMdQ44IXenhel+4A3M/FTK3cLS8EuHVJ2YDwUQIDAQAB" ) ; ----- DKIM key 20200925 for example.com

In you DNS manager, create a TXT record, enter 20200925._domainkey in the name field. (You need to replace 20200925 with your own DKIM selector.) Then go back to the terminal window, copy everything in the parentheses and paste it into the value field of the DNS record. You need to delete all double quotes and line breaks in the value field. If you don’t delete them, then key test in the next step will probably fail.

Test DKIM Key

Enter the following command on your server to test your key.

sudo opendkim-testkey -d example.com -s 20200925 -vvv

If everything is OK, you will see the key OK message.

opendkim-testkey: using default configfile /etc/opendkim.conf
opendkim-testkey: checking key '20200925._domainkey.example.com'
opendkim-testkey: key OK

Now we can start the opendkim service.

systemctl start opendkim

And enable auto-start at boot time.

systemctl enable opendkim

OpenDKIM listens on 127.0.0.1:8891.

Connect Postfix to OpenDKIM

Edit Postfix main configuration file:

vim /etc/postfix/main.cf

Add the following lines at the end of this file, so Postfix will be able to call OpenDKIM via the milter protocol. Note that you should use 127.0.0.1 as the address. Don’t use localhost.

# Milter configuration 
milter_default_action = accept 
milter_protocol = 6 
smtpd_milters = inet:127.0.0.1:8891 
non_smtpd_milters = $smtpd_milters

Save and close the file. Then add postfix user to opendkim group.

 gpasswd -a postfix opendkim

Restart postfix service.

 systemctl restart postfix

Now, you can send email from gmail.com, maybe, to you. In maillog of your server, you will see that dkim works on incoming mails:

opendkim[]: : mail.example.comk [IP of domain] not internal
opendkim[]: : DKIM verification successful

Now, you can send email from you to anybody. In maillog of your server, you will see that dkim works on outcoming mails and that opendkim add signature:

opendkim[]: : DKIM-Signature field added (s=20200925, d=example.com)

Or you can send an empty mail to adress: check-auth@verifier.port25.com

And during few seconds, you will get back report with some things. If SPF is fine and if dkim works:

Summary of Results
SPF check: pass 
"iprev" check: pass 
DKIM check: pass 
SpamAssassin check: ham

Details:
SPF check details:
DNS record(s): example.com. 188 IN TXT "v=spf1 a mx -all"
example.com. 188 192.0.2.1

DKIM check details:
Result: pass (matches From: user1@example.com) 
ID(s) verified: header.d=example.com

How to fight with spam? I will use spamassasin

So what is Spamassasin? According the project web site:

SpamAssassin is a mature, widely-deployed open source project that serves as a mail filter to identify Spam. SpamAssassin uses a variety of mechanisms including header and text analysis, Bayesian filtering, DNS blocklists, and collaborative filtering databases. SpamAssassin runs on a server, and filters spam before it reaches your mailbox.

So we install it first:

dnf install spamassassin

The server binary installed by the spamassassin package is called spamd, which will be listening on TCP port 783 on localhost. Spamc is the client for SpamAssassin spam filtering daemon. By default, the spamassassin systemd service is disabled, you can enable auto start at boot time with:

systemctl enable spamassassin
systemctl start spamassassin

There are several ways you can use to integrate SpamAssassin with Postfix. I use SpamAssassin via the sendmail milter interface, because it allows me to reject an email when it gets a very high score such as 8, so it will never be seen by the recipient.

dnf install spamass-milter-postfix
systemctl start spamass-milter
systemctl enable spamass-milter

Now edit the Postfix main configuration file and add/edit this lines:

vim /etc/postfix/main.cf

# Milter configuration
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:127.0.0.1:8891,unix:/run/spamass-milter/postfix/sock
non_smtpd_milters = $smtpd_milters

Save and close the file. Now open the /etc/sysconfig/spamass-milter file and find the following line.

#EXTRA_FLAGS="-m -r 15"

Uncomment this line and change 15 to your preferred reject score such as 8.

EXTRA_FLAGS="-m -r 8"

In this tutorial, we are going to learn how to use SpamAssassin (SA) to detect spam on CentOS/RHEL mail server. SpamAssassin is a free, open-source, flexible and powerful spam-fighting tool.

SpamAssassin is a score-based system. It will check email message against a large set of rules. Each rule adds or removes points in the message’s score. If the score is high enough (by default 5.0), the message is considered spam.

Set Up SpamAssassin on CentOS RHEL to Block Email Spam

Install antivirus clamd and content filter amavis

What is amavis?

According to wiki:

Amavis is an open-source content filter for electronic mail, implementing mail message transfer, decoding, some processing and checking, and interfacing with external content filters to provide protection against spam and viruses and other malware. It can be considered an interface between a mailer (MTA, Mail Transfer Agent) and one or more content filters.

Amavis can be used to:

  • detect viruses, spam, banned content types or syntax errors in mail messages
  • block, tag, redirect (using sub-addressing), or forward mail depending on its content, origin or size
  • quarantine (and release), or archive mail messages to files, to mailboxes, or to a relational database
  • sanitize passed messages using an external sanitizer
  • generate DKIM signatures
  • verify DKIM signatures and provide DKIM-based whitelisting

And what is clamv?

ClamAV® is an open source antivirus engine for detecting trojans, viruses, malware & other malicious threats.

To install Amavisd and Clamav Server run:

dnf install amavis clamd -y
#it takes 250MB with dependencies

Now edit Clamav configuration file and adjust lines:

vim /etc/clamd.d/scan.conf

#Example
LogFile /var/log/clamd.scan
PidFile /run/clamd.scan/clamd.pid
TemporaryDirectory /var/tmp
LocalSocket /run/clamd.scan/clamd.sock

Save and close. Now create log file for Clamav and start it:

touch /var/log/clamd.scan
chown clamscan. /var/log/clamd.scan
restorecon -v /var/log/clamd.scan

systemctl start clamd@scan.service
systemctl enable clamd@

And now, allow Clamav to scan system for Selinux:

setsebool -P antivirus_can_scan_system on

Now configure Amavisd:

vim /etc/amavisd/amavisd.conf

$mydomain = 'example.com'; # a convenient default for other settings
$myhostname = 'host.example.com'; # must be a fully-qualified domain name!
$inet_socket_bind = '127.0.0.1';
$notify_method = 'smtp:[127.0.0.1]:10025';
$forward_method = 'smtp:[127.0.0.1]:10025'; # set to undef with milter!

And enable it and start it:

systemctl start amavisd.service
systemctl enable amavisd.service

Now edit Postfix main configuration file and add at the end of file:

vim /etc/postfix/main.cf

content_filter=smtp-amavis:[127.0.0.1]:10024

Now edit master.cf and add at the end there lines:

vim /etc/postfix/master.cf

smtp-amavis unix - - n - 2 smtp
 -o smtp_data_done_timeout=1200
 -o smtp_send_xforward_command=yes
 -o disable_dns_lookups=yes
127.0.0.1:10025 inet n - n - - smtpd
 -o content_filter=
 -o local_recipient_maps=
 -o relay_recipient_maps=
 -o smtpd_restriction_classes=
 -o smtpd_client_restrictions=
 -o smtpd_helo_restrictions=
 -o smtpd_sender_restrictions=
 -o smtpd_recipient_restrictions=permit_mynetworks,reject
 -o mynetworks=127.0.0.0/8
 -o strict_rfc821_envelopes=yes
 -o smtpd_error_sleep_time=0
 -o smtpd_soft_error_limit=1001
 -o smtpd_hard_error_limit=1000

And restart Postfix:

systemctl restart postfix.service

And if everything is OK, you can see in the detailed headers of mail, that it has been scanned:

X-Virus-Scanned: Amavisd-new at example.com

And in the maiilog:

amavis[]: () Passed CLEAN {RelayedInbound}
or
amavis[]: () Passed UNCHECKED-ENCRYPTED
or
amavis[]: () Blocked INFECTED (Win.Test.EICAR_HDB-1) {DiscardedInbound,Quarantined}

test: http://www.aleph-tec.com/eicar/index.php

Webmail roundcube 1.6.x

To use roundcube webmail, we download and extract downloaded package manually. Extract into apache web server folder (this is not included in this tutorial) You must create a database for roundcube, set permissions for LOG nad TMP folders for write and setup some steps for begin. I configure and explain only connect to database for user, to change their password by own on mailserver. You can connect roundcube from localhost, or from other web server throught imap/smtp ports for sending/receiving mails.

Do, edit roundcube config file config.inc.php and add plugin for password:

$config['plugins'] = ['password'];

Now, we can see a new page in our roundcube web, under settings > password. But changing password is not impossible, because roudcube doesnt know, how and where we store passwords. So, edit config file for our password plugin and add/change parameters below. We must create a user in our mariadb, who can edit (update) tables in our mail database. We there can enable more variables for new passwords: length, strengh and more…

#mariadb:
CREATE USER exampleuser@localhost IDENTIFIED BY 'sjfaADW34356';
GRANT SELECT,UPDATE ON maildb.virtual_users TO 'exampleuser'@'localhost';
FLUSH PRIVILEGES;
quit

#roundcube folder
cd plugins/password/
cp config.inc.php.dist config.inc.php
vi config.inc.php

$config['password_driver'] = 'sql';
$config['password_query'] = 'UPDATE virtual_users SET password = %P WHERE email = %u';
$config['password_crypt_hash'] = 'sha512';
$config['password_db_dsn'] = 'mysql://exampleuser:sjfaADW34356@localhost/maildb';
$config['password_hash_algorithm'] = 'sha512-crypt';
$config['password_algorithm'] = 'sha512-crypt';
Total Page Visits: 176689 - Today Page Visits: 96

How to install nextcloud v18 on Centos 8 Stream

I create a basic installation of Centos 8 stream from iso: CentOS-Stream-8-x86_64-20191219-boot.iso

During installation I choose minimal applications and standard utilities. Please, enable, network time and set lvm for virtio disk. I set password for root and create a new user, which have root privileges.

After instalation, I create and LVM encrypted partition, to store encrypted data of nextcloud on it. I will not use nextcloud data encryption. Command below creates encrypted disk. We must enter a passphrase twice

 cryptsetup -y -v luksFormat /dev/vdb

Now, we open this partition and look at status:

cryptsetup luksOpen /dev/vdb vdb_crypt
cryptsetup -v status vdb_crypt

/dev/mapper/vdb_crypt is active.
   type:    LUKS2
   cipher:  aes-xts-plain64
   keysize: 512 bits
   key location: keyring
   device:  /dev/vdb
   sector size:  512
   offset:  32768 sectors
   size:    209682432 sectors
   mode:    read/write
 Command successful.

Now, I write 4GB zeros to this device to see, if everything is OK. It is possible, to full-up tho whole device, but it can take a long time. But the true reason is, that this will allocate block data with zeros. This ensures that outside world will see this as random data i.e. it protect against disclosure of usage patterns.

dd if=/dev/zero of=/dev/mapper/vdb_crypt bs=4M count=1000
4194304000 bytes (4.2 GB, 3.9 GiB) copied, 130.273 s, 32.2 MB/s

Now try close and open this encrypted device. And then, I create an lvm above the luks encrypted disk:

cryptsetup luksClose vdb_crypt
cryptsetup luksOpen /dev/vdb vdb_crypt
cryptsetup -v status vdb_crypt
pvcreate /dev/mapper/vdb_crypt
vgcreate nextcloud /dev/mapper/vdb_crypt
lvcreate -n data -L+30G nextcloud
mkdir /mnt/test
mkfs.xfs /dev/mapper/nextcloud-data
mount /dev/mapper/nextcloud-data /mnt/test/
touch /mnt/test/hello 
ll /mnt/test/hello
umount /mnt/test/

Installing nextcloud and prerequisites

And now, we can start with preparing our Centos for nextcloud

At first, update system. Via dnf (DNF is the next upcoming major version of YUM, a package manager for RPM-based Linux distributions. It roughly maintains CLI compatibility with YUM and defines a strict API for extensions and plugins.)

dnf update -y

Next, we install and create empty database for our nextcloud. Then we start it and enable for autostart after boot.
If you wish, you can skip installations of MariaDB and you can use built-in SQLite. Then you can continue with installing apache web server.

dnf -y install mariadb-server
...
systemctl start mariadb
systemctl enable mariadb

Now, we run post installation script to finish setting up mariaDB server:

mysql_secure_installation
Set root password? [Y/n] y
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y

Now, we can create a database for nextcloud.

mysql -u root -p
...
CREATE DATABASE nextcloud;
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextclouduser'@'localhost' IDENTIFIED BY 'YOURPASSWORD';
FLUSH PRIVILEGES;
exit;

Now, we install Apache web server, and we start it and enable for autostart after boot:

dnf install httpd -y
systemctl start httpd.service
systemctl enable httpd.service

And set up firewall fow port http/80 and ssh/20 only:

systemctl status httpd
firewall-cmd --list-all
firewall-cmd --zone=public --permanent --remove-service=dhcpv6-client
firewall-cmd --zone=public --permanent --add-service=http
firewall-cmd --reload

Now point your browser to this server and look, if you see a Apache test page.

Now we can install php. Nextcloud (at this time is version 18.0.1) and support PHP (7.1, 7.2 or 7.3). So I use remi repositories and install php 7.3:

dnf -y install dnf-utils http://rpms.remirepo.net/enterprise/remi-release-8.rpm
dnf module list php
dnf module reset php
dnf module enable php:remi-7.3
dnf info php
dnf install php php-gd php-mbstring php-intl php-pecl-apcu php-mysqlnd php-pecl-imagick.x86_64 php-ldap php-pecl-zip.x86_64 php-process.x86_64
php -v
php --ini |grep Loaded
sed -i "s/post_max_size = 8M/post_max_size = 500M/" /etc/php.ini
sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 500M/" /etc/php.ini
sed -i "s/memory_limit = 128M/memory_limit = 512M/" /etc/php.ini
systemctl start php-fpm.service
systemctl enable php-fpm.service

And now, we can install nextcloud:

mkdir -p /var/www/html/nextcloud/data
cd /var/www/html/nextcloud/
mount /dev/mapper/nextcloud-data /var/www/html/nextcloud/data/
wget https://download.nextcloud.com/server/releases/nextcloud-18.0.1.zip
unzip nextcloud-18.0.1.zip
rm nextcloud-18.0.1.zip
mv nextcloud/* .
mv nextcloud/.htaccess .
mv nextcloud/.user.ini .
rmdir nextcloud/
mkdir /var/www/html/nextcloud/data
chown -R apache:apache /var/www/html/nextcloud/
find /var/www/html/nextcloud/ -type d -exec chmod 750 {} \; 
find /var/www/html/nextcloud/ -type f -exec chmod 640 {} \;

Now create configuration file for nextcloud in httpd:

vim /etc/httpd/conf.d/nextcloud.conf
<VirtualHost *:80>
  DocumentRoot /var/www/html/nextcloud/
  ServerName  your.server.com

  <Directory /var/www/html/nextcloud/>
    Require all granted
    AllowOverride All
    Options FollowSymLinks MultiViews

    <IfModule mod_dav.c>
      Dav off
    </IfModule>

  </Directory>
</VirtualHost>
apachectl graceful

Refer to nextcloud admin manual, you can run into permissions problems. Run these commands as root to adjust permissions:

semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/data(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/config(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/apps(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/.htaccess'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/.user.ini'
restorecon -Rv '/var/www/html/nextcloud/'

If you see error “-bash: semanage: command not found”, install packages:

dnf provides /usr/sbin/semanage
dnf install policycoreutils-python-utils-2.9-3.el8_1.1.noarch

Now, we can check via built-in php scripts, in what state we are:

cd /var/www/html/nextcloud/
sudo -u apache php occ -h
sudo -u apache php occ -V
sudo -u apache php occ status

And finally, we can access our nextcloud and set up administrators password via our web: http://you-ip/

If you see default httpd welcome page, disable all lines in: /etc/httpd/conf.d/welcome.conf
Now you must complete the installation via web interface. Set Administrator’s password and locate to MariaDB with used credentials:

Database user: nextclouduser
Database password: YOURPASSWORD
Database name: nextcloud
host: localhost

In settings of nextcloud, go to section Administration > Overview. You can see some problems. If so, try to fix it. I had three problems. No apcu memory cache configured. So add at nextcloud config.php:

'memcache.local' => '\OC\Memcache\APCu',

Then I must edit som php variables, to set properly opcache: edit and adjust:

vim /etc/php.d/10-opcache.ini

Then I must edit httpd setting, because .htaccess wont working. So change apache config:

vim /etc/httpd/conf/httpd.conf

section: Directory "/var/www/html"
AllowOverride None
change to: 
AllowOverride All

And gracefuly restart apache:

apachectl graceful

Next, I find out, that my nextcloud instance cannot connect to internet and checks for update. I think, that this is on selinux (enforcing mode). So run check and find out, what is happening:

sealert -a /var/log/audit/audit.log

And the result:

SELinux is preventing /usr/sbin/php-fpm from name_connect access on the tcp_socket port 80
Additional Information:
Source Context                system_u:system_r:httpd_t:s0
Source Path                   /usr/sbin/php-fpm
Port                          80
Selinux Enabled               True
Policy Type                   targeted
Enforcing Mode                Enforcing
---------
If you believe that php-fpm should be allowed name_connect access on the port 80 tcp_socket by default.
If you want to allow httpd to can network connect
Then you must tell SELinux about this by enabling the 'httpd_can_network_connect' boolean.

So I allow httpd to can network connect via:

setsebool -P httpd_can_network_connect 1

And that is complete. If you wont secure http (https), try to find out another post on this page.

Have fun

Total Page Visits: 176689 - Today Page Visits: 96

Install WordPress on Centos-8-stream with apache (httpd)

I started on clean centos-8 server, created from netinstall cd. It is minimal instalation. So, lets begun. Check the version, to be installed:

dnf info httpd
Name         : httpd
 Version      : 2.4.37
 Release      : 11.module_el8.0.0+172+85fc1f40

So, let install it and allow http port on firewalld. And start apache server itself.

dnf install httpd
firewall-cmd --add-service=http --permanent
firewall-cmd --reload
systemctl start httpd.service
systemctl enable httpd.service

Now, you can point you web browser to IP on this server and you should see the welcome page of apache web server on centos.

Now create a directory, where we place our content and simple web page to test, if its working.

mkdir -p /var/www/vhosts/com.example.www
vim /var/www/vhosts/com.example.www/index.html
<html>
  <head>
    <title>Welcome to www.example.com!</title>
  </head>
  <body>
    <h1>Success!  The www.example.com virtual host is working!</h1>
  </body>
</html>

And now, create for this page own configuration in httpd:

vim /etc/httpd/conf.d/com.example.www.conf
<VirtualHost *:80>
    ServerAdmin admin@example.com
    DocumentRoot "/var/www/vhosts/com.example.www"
    ServerName www.example.com

ErrorLog /var/log/httpd/com.example.www-error_log
CustomLog /var/log/httpd/com.example.www-access_log common
</VirtualHost>

And now, gracefully restart your web server and point your browser to you domain: www.example.com (I edit my /etc/hosts to point this domain at my internal IP).

apachectl graceful

If you test page is working, lets begin with more thinks. We must install additional packages (software) for wordpress. Its mysql server and php. As mysql server, I use mariadb. Then create an initial configuration for mysql and create database for wordpress. I set no password for mysql.

dnf install mariadb-server mariadb
systemctl start mariadb
systemctl enable mariadb
mysql_secure_installation
   Set root password? [Y/n] n
   Remove anonymous users? [Y/n] y
   Disallow root login remotely? [Y/n] y
   Remove test database and access to it? [Y/n] y
   Reload privilege tables now? [Y/n] y

mysql -u root -p
   CREATE DATABASE wordpress;
   CREATE USER wordpressuser@localhost IDENTIFIED BY 'BESTpassword';
   GRANT ALL PRIVILEGES ON wordpress.* TO wordpressuser@localhost IDENTIFIED BY 'BESTpassword';
   FLUSH PRIVILEGES;
   exit;

When we find, which version of php will be standard installed, I decided to use another package sources and install newer php version 7.3

dnf info php
 Available Packages
 Name         : php
 Version      : 7.2.11

dnf install http://rpms.remirepo.net/enterprise/remi-release-8.rpm
dnf update
dnf install php73
dnf install php73-php-fpm.x86_64 php73-php-mysqlnd.x86_64
systemctl start php73-php-fpm.service
systemctl enable php73-php-fpm.service
ln -s /usr/bin/php73 /usr/bin/php
php -v
   PHP 7.3.10 (cli) (built: Sep 24 2019 09:20:18) ( NTS )

Now, create simple test php page, to view php by apache if its working.

vim /var/www/vhosts/com.example.www/foo.php
<?php
  phpinfo();
?>

Restart apache web server and point your browser to php:

systemctl restart httpd.service
www.example.com/foo.php

And now you can see informationa page about php on system.

Now we can download wordpress and unpack it.

cd ~ 
wget http://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
rsync -avP wordpress/ /var/www/vhosts/com.example.www/
chown -R apache:apache /var/www/vhosts/

Now, we edit configuration and add directory variables about default loding index.php. And remove test files – foo.php, index.html.

rm /var/www/vhosts/com.example.www/foo.php
rm /var/www/vhosts/com.example.www/index.html
vim /etc/httpd/conf.d/com.example.www.conf
<Directory /var/www/vhosts/com.example.www>
DirectoryIndex index.php
</Directory>

And restart apache web server

systemctl restart httpd.service

Now we can continue with setting our wordpress via web browser and our www.example.com page (click refresh in your web browser). Follow the instructions and fill your variables (database name, user, password…).

My installation step 2 tells me, that it cannot write config.php in our content directory. So, I can manually creaty config.php, or find out, what happens. Install selinux troubleshoot packages and run command sealert, which tell us what happend.

dnf install setroubleshoot
sealert -a /var/log/audit/audit.log

I can see this messages:

SELinux is preventing /opt/remi/php73/root/usr/sbin/php-fpm from write access on the directory com.example.www.
If you want to allow php-fpm to have write access on the com.example.www directory
Then you need to change the label on 'com.example.www'
Do
# semanage fcontext -a -t httpd_sys_rw_content_t 'com.example.www'
# restorecon -v 'com.example.www'
Additional Information:
Source Context                system_u:system_r:httpd_t:s0
Target Context                unconfined_u:object_r:httpd_sys_content_t:s0
Target Objects                com.example.www [ dir ]

So I do, what it want. I adapt permissions, that apache/php can write into this diretory.

semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/vhosts/com.example.www(/.*)?'
restorecon -Rv /var/www/vhosts/com.example.www/

Now I can continue with installation. And everything works fine. Have a nice day.

Total Page Visits: 176689 - Today Page Visits: 96

How to install Nextcloud v 13 on Centos 7 with php 7

At first, please update your centos. Every command I used, is used as root user 😉

yum -y update

Installing database server MariaDB

Next, we install and create empty database for our nextcloud. Then we start it and enable for autostart after boot.
If you wish, you can skip installations of MariaDB and you can use built-in SQLite. Then you can continue with installing apache web server.

yum -y install mariadb mariadb-server
...
systemctl start mariadb
systemctl enable mariadb

Now, we run post installation script to finish setting up mariaDB server:

mysql_secure_installation
...
Enter current password for root (enter for none): ENTER
Set root password? [Y/n] Y
Remove anonymous users? [Y/n] Y
Disallow root login remotely? [Y/n] Y
Remove test database and access to it? [Y/n] Y
Reload privilege tables now? [Y/n] Y

Now, we can create a database for nextcloud.

mysql -u root -p
...
CREATE DATABASE nextcloud;
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextclouduser'@'localhost' IDENTIFIED BY 'YOURPASSWORD';
FLUSH PRIVILEGES;
exit;

Installing Apache Web Server with ssl (letsencrypt)

Now, we install Apache web server, and we start it and enable for autostart after boot:

yum install httpd -y
systemctl start httpd.service
systemctl enable httpd.service

Now, we install ssl for apache and allow https and httpd (for redirect) service for firewall:

yum -y install epel-release
yum -y install httpd mod_ssl
...
firewall-cmd --zone=public --permanent --add-service=https
firewall-cmd --zone=public --permanent --add-service=http
firewall-cmd --reload
systemctl restart httpd.service
systemctl status httpd

Now we can access our server via http://our.server.sk or self-signed certificate on https://our.server.sk

If we want signed certificate from letsencrypt, we can do it with next commands. Certboot will ask some questions, so answer them.

yum -y install python-certbot-apache
certbot --apache -d our.server.sk

If we are good, we can see:

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/example.com/fullchain.pem.
...

Then, we must edit our ssl.conf or our  virtual-host to see this certificates. And we can test our page with this.

https://www.ssllabs.com/ssltest/analyze.html?d=our.server.sk&latest

Install PHP 7

The creators of nextcloud recommends at minimal PHP 7.0.
Now we must add some additional repositories for php v. 7:

yum install https://$(rpm -E '%{?centos:centos}%{!?centos:rhel}%{rhel}').iuscommunity.org/ius-release.rpm
yum install yum-plugin-replace
yum repolist # show enabled repositories
yum repolist disabled #show disabled repositories

And we can install php 7.0:

yum install php70u php70u-dom php70u-mbstring php70u-gd php70u-pdo php70u-json php70u-xml php70u-zip php70u-curl php70u-mcrypt php70u-pear setroubleshoot-server bzip2 php70u-mysqlnd.x86_64 php70u-ldap.x86_64 unzip php70u-pecl-apcu.x86_64 mod_php70u.x86_64 php70u-opcache.x86_64 php70u-pecl-memcached.x86_64 php70u-process.x86_64

Check in:

php --ini |grep Loaded
Loaded Configuration File:         /etc/php.ini
php -v
PHP 7.0.27 (cli) (built: Apr 15 2017 07:09:11) ( NTS )
Copyright (c) 1997-2017 The PHP Group

In my case, I will use nextcloud as my backup device, so I increase the default upload limit to 200MB.

sed -i "s/post_max_size = 8M/post_max_size = 200M/" /etc/php.ini
sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 200M/" /etc/php.ini

Restart web server:

systemctl restart httpd

Installing Nextcloud

At first, I install wget tool for download and unzip:

 yum -y install wget unzip

Now we can download nextcloud (at this time the latest version is 11.0.3). And extract it from archive to final destination. Then we change ownership of this directory:

wget https://download.nextcloud.com/server/releases/nextcloud-13.0.0.zip
...
unzip nextcloud_konfs/nextcloud-13.0.0.zip -d /var/www/html/
...
chown -R apache:apache /var/www/html/nextcloud/

If you have enabled SELinux, refer to nextcloud admin manual, you can run into permissions problems. Run these commands as root to adjust permissions:

semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/data(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/config(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/apps(/.*)?'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/.htaccess'
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/.user.ini'
restorecon -Rv '/var/www/html/nextcloud/'

And finally, we can access our nextcloud and set up administrators password via our web: https://you-ip/nextcloud
Now you must complete the installation via web interface. Set Administrator’s password and locate to MariaDB with used credentials:

Database user: nextclouduser
Database password: YOURPASSWORD
Database name: nextcloud
host: localhost

In my case, I must create a DATA folder under out nextcloud, mount nfs backend for this data and set permissions.

mkdir /var/www/html/nextcloud/data
chown apache:apache data/ -R
setsebool -P httpd_use_nfs 1
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/nextcloud/data(/.*)?'
restorecon -Rv '/var/www/html/nextcloud/'

Now create an nextcloud configuration file fort apache:

vim /etc/httpd/conf.d/nextcloud.conf
<Directory /var/www/html/nextcloud/>
 Options +FollowSymlinks
 AllowOverride All

<IfModule mod_dav.c>
 Dav off
 </IfModule>

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/$ /index.php/login
 SetEnv HOME /var/www/html/nextcloud
 SetEnv HTTP_HOME /var/www/html/nextcloud
</Directory>

#####################################################
<VirtualHost _default_:80>
ServerName our.server.sk RewriteEngine On RewriteCond %{REQUEST_URI} ^/$ RewriteRule ^/$ /index.php/login LogLevel warn RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI}[END,NE,R=permanent] </VirtualHost> #################################################### <VirtualHost _default_:443> DocumentRoot "/var/www/html/nextcloud" ServerName our.server.sk RewriteEngine On RewriteCond %{REQUEST_URI} ^/$ RewriteRule ^/$ /index.php/login ErrorLog logs/ssl_error_log TransferLog logs/ssl_access_log LogLevel warn SSLEngine on SSLProtocol all -SSLv2 SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA SSLCertificateFile /var/lib/acme/live/our.server.sk/cert SSLCertificateKeyFile /var/lib/acme/live/our.server.sk/privkey SSLCertificateChainFile /var/lib/acme/live/our.server.sk/chain </VirtualHost>

For nicer access, I created a permanent rewrite rule for my  Nextcloud root folder.

Now restart apache and add permisions for apache, to sen emails and work with LDAP:

systemctl restart httpd.service
setsebool -P httpd_can_sendmail on
setsebool -P httpd_can_connect_ldap on

Enable updates via the web interface

To enable updates via the web interface, you may need this to enable writing to the directories:

setsebool httpd_unified on

When the update is completed, disable write access:

setsebool -P httpd_unified off
Total Page Visits: 176689 - Today Page Visits: 96