0. Overview of Lab 3
Welcome to 5th lab. Here is a short action list of what we will be doing in the lab:
- 1. Verifying previous lab tasks
- 2. Setting an MX record in your DNS
- 3. Setting up NTP
- 4. Setting up mail server software
- 4.1 Setting up an SMTP server
- 4.2 Setting up an IMAP server
- 4.3 Setting up a web service for mail box access
- 5. Setting up a mail client for mail box access
- 6. Setting up a spam filter
- 7. Creating an autoreply to the scoring server
1. Make sure you finished all the tasks of the previous weeks
What we expect here:
- Personal domains are configured. Machine is accessible over <machine_name>.sa.cs.ut.ee inside the University network.
- All the tests on scoring.sa.cs.ut.ee are green.
- The DNS of your personal computer is set up correctly and can resolve sa.cs.ut.ee domains
- Apache web server is up and running.
PS! There is a thorough guide available here
PPS! The guide also sets up TLS/SSL. We will do that in a later lab,
2. Creating an MX record
Now that each student has full control of their own domain, they can add as many names as they wish into their domain. Ideally each service has conventional names, like www for web, mail for SMTP or ftp for FTP. Now then, let's add the mail host name as well as Mail Exchanger pointer to our DNS configuration.
Setting up Dovecot DNS MX (Mail eXchange) records are used to specify the mail servers responsible for accepting e-mail messages on behalf of an entire domain. If there is no MX record for the domain, type A record will be queried for instead. If there is no A record either, it is not possible to send e-mails to the domain.
Our goal is to set up the MX records so that the e-mails for the <vm_name>.sa.cs.ut.ee domain will be directed to mail.<vm_name>.sa.cs.ut.ee, which in turn points to the IP of your virtual machine - this means that you will need to create another A record pointing to your mail server.
NOTE: If AAAA IPv6 records are present, then postfix(an SMTP server, more on that later) will use them by default. We, however, have not set up IPv6 and therefore we have no AAAA records.
Here are some extra materials for MX records:
The minimum you will need to know is:
- What are the priority values of MX records
- How to set them in the zone file.
Edit the Zone # <vm_name>.sa.cs.ut.ee
in bind9
configuration:
- Add a type
A
record formail.<vm_name>.sa.cs.ut.ee
pointing to your VM's external IP. - In the same Zone file, add an
# MX
record pointing to the hostnamemail.<vm_name>.sa.cs.ut.ee.
Set the priority value to10
.- Think about the order, how should the records be organized in the Zone files:
MX
first thenA
record or vice-versa? Is there a difference?
- Think about the order, how should the records be organized in the Zone files:
- Save the zone file
- Should we change the serial before closing ?
- Test the Zone syntax
- Remember
named-checkzone
command
- Remember
- If everything is OK, restart the
named
service
To test, query for the A
and MX
records you have just created:
dig mail.<vm_name>.sa.cs.ut.ee
dig <vm_name>.sa.cs.ut.ee MX
- NB! The DNS changes might take time to propagate
If you have set up the DNS server of your personal computer correctly, the answer should look something like:
[user@server ~]$ dig scoring.sa.cs.ut.ee -t MX ; <<>> DiG 9.10.6 <<>> scoring.sa.cs.ut.ee -t MX ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11447 ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4000 ;; QUESTION SECTION: ;scoring.sa.cs.ut.ee. IN MX ;; ANSWER SECTION: scoring.sa.cs.ut.ee. 64145 IN CNAME sa.cs.ut.ee. sa.cs.ut.ee. 86400 IN MX 10 mail.scoring.sa.cs.ut.ee. ;; Query time: 4 msec ;; SERVER: 172.17.0.217#53(172.17.0.217) ;; WHEN: Fri Mar 05 19:32:52 EET 2021 ;; MSG SIZE rcvd: 83
3. Setting up NTP
Before you start, check the current clock and timezone info:
$ date $ timedatectl
- Update
dnf
(re-synchronize the package index files from their sources):- It is a good practice to do it each time you intend to install something with
yum
ordnf
, because that makes sure you're installing the latest versions.
- It is a good practice to do it each time you intend to install something with
yum clean all yum makecache
Before we setup the SMTP service let's make sure our VM's time is in sync with the world time. As the mail delivery system stamps each mail with sent-out date and delivery-date it is very important that all servers have the timezone specified and the clock kept in sync. The Network Time Protocol (NTP) is used for that purpose, the details you may read here.
In CentOS 8 the NTP is handled by the package called chrony , so let's install it.
Use package manager and install chrony
package
Understanding ntp client configuration
By default the chrony
package comes with the list of predefined servers to sync against the following servers (according to /etc/chrony.conf
):
,.. pool 2.centos.pool.ntp.org iburst ...
But we will use the NTP server of University of Tartu( ntp.ut.ee
):
Edit /etc/chrony.conf
:
- Add
ntp.ut.ee
into the list of the NTP servers - Save the file
- Restart the
chrony
service - Check if that fixed time using
date
command. The clock is probably not right, as the VM's created in the ETAIS come with UTC timezone by default. Let's fix the timezone mismatch next.- Use
timedatectl list-timezones
to identifyTallinn
timezone option - With
timedatectl
and the correctset-timezone
parameter set the timezone toEurope/Tallinn
- Use
Check if the time is sync using commands:
$ timedatectl $ date
4. Setting up software
A mail server usually consists of multiple services:
- The least a mail server needs to send and receive e-mails is an SMTP(Simple Mail Transfer Protocol) service.
This service sends and receives mail messages. There are 3 ports that an SMTP server usually utilizes:
- 25 or SMTP port
- 465 or SMTPS port
- 587 or Submission port.
- However, more often than not, you would also like to read e-mail. For that, a separate service is used that can utilize the IMAP(Internet Message Access Protocol). Using this service, the e-mail clients can retrieve e-mail.
IMAP server usually listens either on
- port 143(IMAP)
- or port 993(IMAPS).
- Also, quite often, you would like to have a web client to read and send your mail from your browser instead of using a mail client such as Outlook, Apple Mail or Thunderbird.
For that there are several open source web mail clients that can be set up on your mail server. These clients need a web server such as Apache http server in front of them. A web server communicates over
- port 80(HTTP)
- and port 443(HTTPS)
You may have noticed that some of the port names are duplicated only wth the difference of an "S" being at the end of the name. The "S" in this context means "Secure" and communication using these protocols is encrypted. The unencrypted protocols send all data, including user names and passwords in clear text across the Internet, which is, obviously, insecure. However, this is how we will initially be setting up our mail server and we'll work on securing the mail traffic in the next lab.
Make sure your VM knows its FQDN:
$ hostname -f
should return <vm_name>.sa.cs.ut.ee
- If it does not:
- Configure
/etc/hostname
and/etc/hosts
- Restart the machine
- Configure
Now, using the package manager, install postfix
, alpine
, dovecot
, spamassassin
, epel-release
, spamass-milter
and dovecot-pigeonhole
4.1 Setting up Postfix
Postfix is one for the most widely used SMTP servers, so that is what we will use int lab5. Posfix's documentation is available here.
The locations of the Postfix configuration and log files:
- Configuration file:
/etc/postfix/main.cf
- Log file for e-mail related log messages:
/var/log/maillog
Before we continue, edit /etc/postfix/main.cf
and set inet_protocols
to ipv4
There are several variables Postfix expects to be defined. One of them is the $mydomain
. This parameter specifies the parent domain of $myhostname
, which, by default,
is set to be the FQDN of the mail server (the hostname -f
part before), but could also be set manually.
By default, $mydomain
is derived from $myhostname by stripping off the first part (unless the result would be a top-level domain), so, for example, mail.sa.cs.ut.ee
becomes sa.cs.ut.ee
(mail is stripped).
The postconf
command is used to print the active configuration variables loaded. If we refer to manual man postconf
we may discover couple of useful features:
- -n switch: Prints only the configuration alternated by user (omits default values)
- -d switch: Prints only the default configuration not alternated by user (good to check what was the initial value of the variable)
Modify postfix's main.cf
file so that it meets the following criteria (Most of the variables are already defined in the config file. Try not to define them multiple times. You can search for a string in nano
with Ctrl+W and in vi
and vim
by pressing /.):
- The output of
postconf | grep -e "^myhostname"
should returnmail.<vm_name>.sa.cs.ut.ee
.postconf
returns all of the values of the current configuration andgrep -e "^myhostname"
searches for a line that starts withmyhostname
- The command will probably return
<vm_name>.sa.cs.ut.ee
, why? - Set the correct
$myhostname
manually in the config file $mydomain
parameter should not be specified and it will be derived from$myhostname
- You can use
postconf
again to check the value of$mydomain
- You can use
- The command will probably return
- The domain name for the outbound mail should be
$mydomain
- Name of outbound mail parameter is
$myorigin
- Name of outbound mail parameter is
- Server has to listen on all interfaces (
inet_interfaces=all
) - Server should handle mail for following addresses (Read what
$mydestination
does):mail.<vm_name>.sa.cs.ut.ee
,localhost.<vm_name>.sa.cs.ut.ee
,
localhost
, <vm_name>.sa.cs.ut.ee
- You can use variables such as
$mydomain
,localhost.$mydomain
($paramName
means that we take content ofparamName
defined in the current conf file)
- You can use variables such as
- Ensure that the trusted networks style (
mynetworks_style
) ishost
- Make sure that
$relayhost
and$mynetworks
parameters are not used in the config and add$mynetworks_style
parameter. - Set
$mynetworks_style = host
- that forces Postfix to "trust" only the networks the VM is directly attached to.
- Make sure that
If everything is Ok, you can start up the postfix
server. Also make sure the smtp
port is opened on minu.etais.ee
. Also open ports for the smtp
service with firewall-cmd
.
- Check the
postfix
service withsystemctl
- Start the service if not running (restart if running),
- Set
postfix
service to start automatically at system start-up if not set yetsystemctl is-enabled postfix.service
systemctl enable postfix.service
- To enable smtp traffic from the minuetais firewall:
- Add the firewall rules to accept packets on ports
tcp/25
. Don't forget to save the rules! - Create a new
Security group
in ETAIS calledSMTP
fortcp port 25
and add the security group to you Virtual machine
- Add the firewall rules to accept packets on ports
Mail server can now be tested by sending mails from/to the different user accounts on your machine.
- You can add new user account using following command:
adduser newUserName
- Create a new user
mailuser
- Set a password that is secure and that you can remember.
- Do not reuse any of your own passwords, as currently the traffic is insecure an can be listened to by anyone
- Set a password that is secure and that you can remember.
- Change your user to mail testing user (
sudo su - mailuser
).
Run alpine
mail client. Send an email to centos
user
- Make sure that
centos
user has runalpine
before sending email. Otherwise the emails will not go to the proper folder, and will be not visible from the Message Index screen.
- Make sure that
- Log in to
centos
- If sending e-mails between the local users works, try to exchange e-mails with other lab systems (ask for their e-mail addresses).
- If sending the mail to another system fails, make sure its name resolves and that it answers with an MX record
- To pass Lab5: Test if
mailuser
has sent email tonagios@scoring.sa.cs.ut.ee
Nagios check, send an email frommailuser@<vm_name>.sa.cs.ut.ee
tonagios@scoring.sa.cs.ut.ee
.- If the email From: header matches the format of
mailuser@<vm_name>.sa.cs.ut.ee
, the check will pass. - If you have sent an email, and this does not turn green soon, then check your postfix logs to find possible issues. (
/var/log/maillog
)
- If the email From: header matches the format of
- You can also send e-mail from terminal
echo -e "Subject: terminal email-01 \n\nHello! \nthis is a e-mail sent with sendmail command from terminal\nby $USER" from $HOSTNAME | /usr/sbin/sendmail aliastest
- You can also read e-mails without
alpine
from command linecat /var/mail/$user
- Try reading other user e-mail without
root
permission. Did it work? Why? Should it?
4.2 Setting up Dovecot
Prelude: mail Aliases
Mail aliases are used to forward all e-mails sent to some address to some other address. Using aliases, you can also create an e-mail address that is not in strict connection
with any of the system's user accounts. Aliases are configured in /etc/aliases
file. You can read more about aliases and its file format with command man aliases
.
Since dovecot cannot access root
's user directory, an alias should be created that forwards e-mails sent to root
.
- You should already have an alias for
postmaster->root
. Change it topostmaster->mailuser
- Create a (local) alias
root->mailuser
(as a result of this alias, e-mails sent toroot@<vm_name>.sa.cs.ut.ee
must be forwarded tomailuser
's mailbox) - You can also create an alias for non-existent users. To test it create a (local) alias
aliastest->scoring
(as a result of this alias, e-mails sent toaliastest@<vm_name>.sa.cs.ut.ee
must be forwarded toscoring
's mailbox)
- Create a (local) alias
- Re-generate alias database with command
newaliases
- Reload postfix configuration with command
postfix reload
We used a "local mailbox" model for testing the e-mail service, but nowadays most of the e-mail reading is done over the network protocols such as IMAP
and POP3
.
Most popular, by far, are web-based solutins, but these also usually use IMAP
behind the scenes.
We will now set up an easy-to-configure IMAP
server called Dovecot. (If you didn't install dovecot
already with package manager, do it now).
Again, you should read and understand the configuration part of the dovecot
manual. Main configuration file for dovecot
is /etc/dovecot/dovecot.conf
and because of the modular design each module has separate configuration file under /etc/dovecot/conf.d
directory.
Details about Dovecot configuration files are available form
Dovecot documentation - Dovecot Config File Syntax
PS! Similar to postconf
there is a doveconf
command for checking Dovecot configuration. The manual man doveconf
suggests that most of the switches are similar to
the ones of the postconf
command ( -n
, -d
, -P
).
Configuring dovecot logging module
Configure the Dovecot IMAP server's logging module:
- Edit
/etc/dovecot/conf.d/10-logging.conf
file:- Set
mail_debug
toyes
- Set
- Save the file
- Restart the
dovecot
service
Allow imap prtocol
- Edit
dovecot
's main configuration file in/etc/dovecot/dovecot.conf
and allowimap
protocol (protocols
parameter)
Configuring dovecot authentication module
The simplest authentication mechanism is PLAIN
. The client simply sends the password unencrypted to Dovecot. All clients support the PLAIN
mechanism, but obviously there's the problem that anyone listening on the network can steal the password. For that reason (and some others) other mechanisms were implemented. But this week, for the sake of learning, we will set it up without any security mechanisms.
Allow dovecot to use PLAIN and LOGIN authentication methods:
- Edit
/etc/dovecot/conf.d/10-auth.conf
file:- Set
auth_mechanisms
variable to allowplain
andlogin
- set
auth_username_format
to%n
- Save the file
- Set
Configuring dovecot mail module
Setup the dovecot mail directory (~/mail) and mailbox (/var/mail).
- Edit
/etc/dovecot/conf.d/10-mail.conf
file:- Set
mail_location
variable tomaildir:~/mail
- Set
- Check default mail folder permissions
ls -ld /var/mail
- This is where the incoming mail is stored.
- You can see that only
root
and themail
group have write permission to the/var/mail
. You'll need to givedovecot
's mail processes ability to belong tomail
group by- Setting
mail_privileged_group
variable tomail
- Setting
- Save the file
- Now make sure that user
dovecot
is in themail
group- You can use
id $USER
to see which groups a user belongs to - You can add user to groups using
usermod
command. Find the correct flags to add user to a group.
- You can use
Auto create folders
- Edit
dovecot
's mailboxes module/etc/dovecot/conf.d/15-mailboxes.conf
- To each defined mailbox, add
auto = create
analougus to the following example: mailbox Trash { auto = create special_use = \Trash }
- To each defined mailbox, add
- Also define a mailbox called "Spam" with
special_use
set to\Junk
Testing dovecot login
Now that you have set up basic configuration for dovecot, it's time to test it.
- Make sure
dovecot
service is started (restarted if you have changed configurations in the meantime) - Make sure
mailuser
has its password set and you know it. - Using your package manager, install
telnet
- Connect to the
IMAP
port usingtelnet
- If the connection is successful, try loging in as
mailuser
by connecting to port143
oflocalhost
usingtelnet
$ telnet 127.0.0.1 143 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. * OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ STARTTLS AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
- Use IMAP commands to authenticate as mailuser in the format of
$COMMAND_ID login user password
. Command ID can be any string.A1 login mailuser mailuser A1 OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SNIPPET=FUZZY PREVIEW=FUZZY LITERAL+ NOTIFY SPECIAL-USE] Logged in
- Log out
A1 logout * BYE Logging out A1 OK Logout completed (0.001 + 0.000 secs).
dovecot
service should now listen on 2 ports in the TCP stack. What are these ports?
- Check the default ports used by
dovecot
:- Take look into file
10-master.conf
in the/etc/dovecot/conf.d/
configuration directory - Find the
imap-login
service block - the default ports should be stated there in commented blockstcp/143 (imap plain)
andtcp/993 (imaps - imap over explicit SSL/TLS pipe)
.
- Take look into file
- Use
netstat
command with proper options (TCP, numeric, listening, program name) to discover if these ports are in use. - Allow these ports in the firewall.
- Also, enable
tcp/587
(submission) from the ETAIS firewall, which we will be configuring later.
Also try connecting with telnet but instead of 127.0.0.1 connect to mail.<vm_name>.sa.cs.ut.ee As you can see, you get an error logging in:
* BAD [ALERT] Plaintext authentication not allowed without SSL/TLS, but your client did it anyway. If anyone was listening, the password was exposed. a1 NO [PRIVACYREQUIRED] Plaintext authentication disallowed on non-secure (SSL/TLS) connections.
This is because by default, dovecot requires encrypted connections from anyone who is trying to log in from outside. This of course is quite a sane thing to do to protect private info of the users from hackers, who might be listening to the network traffic. We, however, want to disable encrypted connections for now and tackle service encryption in a later lab, as mentioned before. To allow login from unencrypted connections:
- Edit
dovecot
's10-auth.conf
and setdisable_plaintext_auth
tono
- Edit
dovecot
's10-ssl.conf
and setssl
tono
- Restart
dovecot
and try to authenticate tomail.<vm_name>.sa.cs.ut.ee
withtelnet
. It should work now.
Give mailbox handling from postfix
to dovecot
SMTP communication between mail servers uses smtp
port 25
. Mail clients on the other hand, often submit the outgoing e-mails to a mail server on submission
port 587
.
The reason for that is that port 25 usually doesn't require authentication, which is fine , if you want to receive mail to the mail server from other mail servers,
since it is practically impossible to have every mail server authenticate themselves to yours. However relaying mail with no authentication is an absolutely horrible idea -
it would allow anyone to send e-mails via your mail server. So let's get to configuring now.
- Add
lmtp
protocol todovecot
's main configuration file
- Now define the
lmtp
listener in/etc/dovecot/conf.d/10-master.conf
- This creates an https://en.wikipedia.org/wiki/Local_Mail_Transfer_Protocol? socket through which
postfix
can comunicate withpostfix
. The socket is created as a file thatpostfix
can read and write to. - Define the
lmtp
listener as follows: service lmtp { unix_listener /var/spool/postfix/private/dovecot-lmtp { # unix_listener $PATH_TO_SOCKET mode = 0600 # Socket permissions user = postfix # Socket owner group = postfix # Socket group } }
- This creates an https://en.wikipedia.org/wiki/Local_Mail_Transfer_Protocol? socket through which
- In
/etc/postfix/main.cf
- Set
mailbox_transport
tolmtp:unix:private/dovecot-lmtp
- This tells postfix to hand all incoming mails to the
lmtp
socket we created before.
- This tells postfix to hand all incoming mails to the
- Set
- Restart
postfix
Set postfix
to also listen on submission
port 587
- In
postfix
'smaster.cf
configuresubmission
section as follows:
submission inet n - n - - smtpd -o syslog_name=postfix/submission -o smtpd_sasl_auth_enable=yes -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject -o smtpd_relay_restrictions=permit_sasl_authenticated,reject -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/auth # -o syslog_name=postfix/submission: The name with which submission related events are logged # -o smtpd_sasl_auth_enable=yes: Enable sasl authentication (`plain` in our case) # -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject: Permit recepients outside of $mynetworks only to authenticated users # -o smtpd_relay_restrictions=permit_sasl_authenticated,reject: Allow mail relaying only for authenticated users # -o smtpd_sasl_type=dovecot: Set dovecot as the SASL provider # -o smtpd_sasl_path=private/auth: Set authentication socket location
You'll also have to configure dovecot
to create a socket over which postfix
can communicate login information to dovecot for mail submisssion
- In
dovecot
's10-master.conf
file create a unix listener for theauth
service:service auth { unix_listener /var/spool/postfix/private/auth { mode = 0600 user = postfix group = postfix } }
- This creates a socket file into
/var/spool/postfix/private/auth
, where postfix can access it. - Now that everything is configured, restart
postfix
anddovecot
- Try sending a new e-mail from one user to another from within your system to test the setup.
- If the mail doesn't reach its destination, you can find debug information from
/var/log/maillog
- If the mail doesn't reach its destination, you can find debug information from
- Try sending a new e-mail from one user to another from within your system to test the setup.
Test if authentication works
- Create a base64 string of your
mailuser
and its password with the following command:printf '\0%s\0%s' 'mailuser' '$mailuser_password' | openssl base64
.
The output should something like this:
$ printf '\0%s\0%s' 'mailuser' 'mailuser' | openssl base64 AG1haWx1c2VyAG1haWx1c2Vy
- Now, using telnet connect to 127.0.0.1 port 587:
$ telnet 127.0.0.1 587 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. 220 mail.server.sa.cs.ut.ee ESMTP Postfix
- Say hello to the server:
ehlo server 250-mail.not-nice.sa.cs.ut.ee 250-PIPELINING 250-SIZE 10240000 250-VRFY 250-ETRN 250-STARTTLS 250-AUTH PLAIN LOGIN 250-ENHANCEDSTATUSCODES 250-8BITMIME 250-DSN 250 SMTPUTF8
- Try to authenticate using the base64 string created before:
auth plain AG1haWx1c2VyAG1haWx1c2Vy 235 2.7.0 Authentication successful
- If the authentication was successful, then everything is configured correctly this far.
4.3 Setting up Roundcube
Roundcube is an open-source web mail client that you can use to access your e-mail account with. As you probably noticed - reading e-mail from the terminal is quite monotonous, because of that we will be setting up something more graphical.
First install epel-release
and dnf-plugins-core
and run dnf update
. Then run dnf config-manager --set-enabled powertools
.
- Now you can install the following packages:
make
,ImageMagick
,ImageMagick-devel
,ImageMagick-perl
,pcre-devel
,zlib
,zlib-devel
,libzip
,libzip-devel
,libmcrypt-devel
,php
,php-fpm
,php-devel
,php-pear
,php-cli
,php-gd
,php-curl
,php-xml
,php-mysqlnd
,php-mbstring
,php-intl
,php-ldap
,mariadb
,mariadb-server
andhttpd
. Use your package manager to install them. - Install
imagick
,mcrypt
andzip
extensions with pecl:
pecl install $package
- For each of the extensions installed with
pecl
, create a file named20-<extension_name>.ini
into/etc/php.d/
and into the file writeextension=extension_name>.so
Now that all the necessary packages are there, make sure the following services are running and enabled:
httpd
mariadb
php-fpm
After that set up a database for Roundcube to use. We are using mariadb
, which is a fork of mysql
. The name of the tool command line tool, however, is still called mysql
.
- Generate a random password for the database user with
openssl rand -base64 16
- Connect to the database service
mysql -u root -p
- Now that you have entered the mariadb command line, Set up the database with the following commands:
MariaDB [(none)]> CREATE DATABASE roundcubemail /*!40101 CHARACTER SET utf8 COLLATE utf8_general_ci */; MariaDB [(none)]> CREATE USER 'roundcube'@'localhost' IDENTIFIED BY 'the_random_password'; MariaDB [(none)]> GRANT ALL PRIVILEGES ON roundcubemail.* TO 'roundcube'@'localhost'; MariaDB [(none)]> FLUSH PRIVILEGES; MariaDB [(none)]> exit;
Roundcube can be downloaded from its github repository. Currently the latest release is 4.11
, so lets
set it up in /var/www/html/roundcubemail
.
- Download the roundcube release
wget https://github.com/roundcube/roundcubemail/releases/download/1.4.11/roundcubemail-1.4.11-complete.tar.gz -O /var/www/html/roundcube.tar.gz
- Since the downloaded file is compressed, you need to uncompress it with
tar
. Useman tar
to learn the syntax of the program and the appropriate flags for uncompressing. - Remove the compressed file
- Rename the uncompressed directory to
roundcubemail
with themv
command - Set correct owner, group and permissions to
/var/www/html/roundcubemail
so thatapache
can access it. Make sure to use therecursive
flag so the changes also apply to files and directories within the/var/www /html/roundcubemail
directory. - Run
chcon -t httpd_sys_rw_content_t /var/www/html/roundcubemail -R
to get correctselinux
permissions for the directory
Now that we have set up the necessary files and a database, we can create a web server configuration for Roundcube.
- Create a configuration file called
mail.<vm_name>.sa.cs.ut.ee.conf
in/etc/httpd/conf.d/
- Populate the file with the following information:
<VirtualHost *:80> ServerAdmin root@<vm_name>.sa.cs.ut.ee ServerName mail.<vm_name>.sa.cs.ut.ee DocumentRoot /var/www/html/roundcubemail <Directory /var/www/html/roundcubemail> Allowoverride all </Directory> ErrorLog /var/log/httpd/mail.<vm_name>.sa.cs.ut.ee-error.log CustomLog /var/log/httpd/mail.<vm_name>.sa.cs.ut.ee-access.log combined ForensicLog /var/log/httpd/mail.<vm_name>.sa.cs.ut.ee-forensic.log </VirtualHost>
- Restart the httpd service and ensure it restarted successfully
After you have done all that, Roundcube setup page should be available from mail.<vm_name>.sa.cs.ut.ee/installer. Make sure that all the PHP extensions are OK . Once you have verified, that roundcube can find its extensions, click "Next" and set up Roundcube with the following information:
product_name
should beWebmail - <vm_name>.sa.cs.ut.ee
- In database setup:
- Set
Database type
toMySQL
- Set
Database server
tolocalhost
- Set
Database user
name toroundcube
- Set
Database password
to the random password you generated before - Set
db_prefix
torc
- Set
- In Logging & Debugging:
- Set
log_dir
to/var/log/roundcube
- Also ensure the
/var/log/roundcube
directory exists
- Set
- In IMAP settings:
- Set
default_host
tolocalhost
- Set
default_port
to143
- Set
- In SMTP settings:
- Set
smtp_server
tolocalhost
- Set
smtp_port
to587
- Set
- Click on
Create config
- This generates a text box with the configuration php inside it. Copy the config and save it into a file called
config.inc.php
into/var/www/html/roundcubemail/config
- Make sure the file permissions are correct
- The same outpput file could be used with ansible to automatically configure the roundcube installation
- Review the configuration on the
Test config page
- If everything else is okay, you can initialize the database
- If the configuration tests are good, make sure to remove the
installer
directory from/var/www/html/roundcubemail/
After this is all done, you should be able to access the mailboxes of the mail accounts you set up before by using the username and password of these users. If you cannot access the mailboxes, ensure that:
- The user exists
- Dovecot is running and configured correctly
If you were able to log in, try sending mail to another student's mailuser
account from your mailuser
. If you get an error, make sure that:
- The other student has their
postfix
up and running - That you have your
postfix
service up and running and configured correctly.
5. Mail client configuration
Let's now try to connect to our IMAP server from an external e-mail client called Thunderbird
- Download and install Thunderbird into your personal computer
- Verify that you can access
<vm_name>.sa.cs.ut.ee
i.e. pingmail.student-test.sa.cs.ut.ee
from own machine. - Add a new e-mail address: Thunderbird -> ALT key -> Edit -> Account settings -> Account Actions -> Add mail account i
mailuser
asYour name
mailuser@<vm_name>.sa.cs.ut.ee
asEmail address
- Password of your
mailuser
account as the password - Click
continue
- Click
Conficure manually
- Set SMTP
SSL
to "None" - Clock
Done
- If Thunderbird warns you about no encryption, click "I understand the risks" and
Done
- Check if you can see e-mail in your INBOX
- Try to send e-mails to other users in your domain
- Try to send e-mails to other users in other .sa.cs.ut.ee domains
6. Spam Filtering with SpamAssassin and dovecot-pigeonhole
Apache SpamAssassin is one of the best open source spam filters. It uses a robust scoring framework and plug-ins to integrate a wide range of advanced heuristic and
statistical analysis tests on email headers and body text including text analysis, Bayesian filtering, DNS blocklists, and collaborative filtering databases. We will use SpamAssassin spamd/spamc
model and dovecot-pigeonhole
's sieve
function to sort the incoming mail according to spam info about the incoming mails.
spamd
is a SpamAssassin service that calculates "spam scores" for the messages. spamc
is a client for the spamd
. sieve is a rule-based mail processing tool.
We will use dovecot sieve
to do the real filtering based on the spam scores set by SpamAssassin.
Do note taht dovecot sieve
can be used for a lot more than spam filtering.
You can read about SpamAssassin here
And about pigeonhole sieve here
Integrating spamassassin with postfix
If you didn't install spamassassin
and spamass-milter
(you have to have epel-release
installed to install this package) before, install them now using you package manager.
Enable and start these services using systemctl
.
You can find SpamAssassin documentation here
- After you have done that, edit
postfix
's main.cf file and add the following lines at the end:
# Milter configuration milter_default_action = accept milter_protocol = 6 smtpd_milters = unix:/run/spamass-milter/spamass-milter.sock non_smtpd_milters = $smtpd_milters
- Edit
/etc/sysconfig/spamass-milter
andset EXTRA_FLAGS to "-m -r 10 -g sa-milt -- --max-size=51200000"
-r
flag tellsspamassass-milter
to reject mails with higher score than10
-g
flag setsspamass-milter
socket writable by thesa-milt
group--
tellsspamass-milter
to pass remaining options tospamc
--max-size=5120000
tellsspamassassin
not to check e-mails larger than 50MB to reduce the server load.
- Using
usermod
addpostfix
tosa-milt
group - Uses
systemctl
to restartpostfix
andspamass-milter
- You can see default spam detection rules in
/usr/share/spamassassin/
. Try reading the20_head_tests.c
and understanding the syntax. - Default scores can be seen in
50_scores.cf
and72_scores.cf
Now let's edit some scores and also add a custom rule. Custom scores and rules can be defined in /etc/mail/spamassassin/local.cf
- For the syntax, consult SpamAssassin's configuration documentation
- Set
required_score
to4.0
- Set the score of
MISSING_FROM
to1.0
- Create a rule to test if
spamassassin
works. Read the
documentation for the correct syntax.
- Create a
body
rule and name itSPAMASSASSIN_TEST_SORTING
. Set the/pattern/mofiers
part to/this is a test text for spamassassin sorting rule/is
.- As the rule description set
Test if Spam sorting with dovecot sieve works
- Set the rule's
score
to5.0
- As the rule description set
- Create a
body
rule and name itSPAMASSASSIN_TEST_REJECT
. Set the/pattern/mofiers
part to/this is a test text for spamassassin reject rule/is
.- As the rule description set
Test if milter spam rejection works
- Set the rule's
score
to11.0
- As the rule description set
- Create a
- Restart
spamassassin
Sorting spam into a separate directory
If you didn't install dovecot-pigeonhole
before, install it now using you package manager.
Enable sieve:
- Add
sieve
toprotocols
indovecot
's main configuration file. - Set
mail_plugins = $mail_plugins sieve
indovecot
's15-lda.conf
'slda
protocol definition - Set
mail_plugins = $mail_plugins sieve
indovecot
's20-lmtp.conf
'slmtp
protocol definition - Restart
dovecot
As a mail test user ( mailuser
), create a .dovecot.sieve file in the users home directory and add the following:
require ["fileinto"]; if header :contains "X-Spam-Flag" "YES" { fileinto "Spam"; stop; }
After you have saved the file, run sievec .dovecot.sieve
to compile the sieve file
Restart dovecot
- After you have done that, you can test if spamassassin works by sending a mail, with the content
this is a test text for spamassassin sorting rule
- This should be sorted into the spam folder.
- If that works, test the second rule, by sending:
this is a test text for spamassassin reject rule
- This e-mail should be rejected, you should see the execution of the rejection in @@ /var/log/maillog@
7. Autoreply for every incoming mail from the scoring server
Use Pigeonhole Sieve: Vacation Extension to create an autoreply. Be sure to enable vacation-seconds
extension in sieve configuration. Also set sieve_vacation_min_period
and sieve_vacation_default_period
to 1s
. Restart dovecot
.
Now let's start creating the autoreply
- Add "vacation", "date" and "variables" to the requred extensions in
.dovecot.sieve
. - Using the examples provided here create an autoreply that replies to e-mails
with subject and body both containing E-mail received at: YYYY-mm-dd HH:MM:SS
where:
- YYYY is the year of the receiving date
- mm is the month of the receiving date
- dd is the day of the receiving date
- HH is the hour of the receiving time
- MM is the minute of the receiving time
- SS is the second of the receiving time
- Figure out, how to use currentdate extension from the examples
- You can also see an example on the usage of the vacation extension in the examples.
- Compile the sieve again and ensure there are no errors
Now you can test wether the vacation extension works. Send an e-mail from within the system (from root
for example) to mailuser
and ensure the autoreply works. Be sure to test it multiple times to ensure that vacation-seconds
plugin is enabled.
If the extension replies to sent e-mails as expected, it is time to restrict the auto replies to only root@scoring.sa.cs.ut.ee
.
- Check wether the header contains a
from
field and that that the field is set toroot@scoring.sa.cs.ut.ee
. Figure out how to do it using sieve examples.
8. Trying to get Alpine to work after setting up everything else
This part is technically necessary only if you're trying to get Alpine to work after setting up Dovecot. Sadly the newest Dovecot moves /var/spool/mail/<user>
emails to /home/<user>/mail/
directory, causing some issues with existing Alpine installations.
You can change where Alpine is searching emails from for mailuser
userby editing the following file: /home/mailuser/.pinerc
.
Set the maildir-location=
setting to /home/mailuser/mail
which causes Alpine to search for emails from there. Sadly setting up Dovecot, nowadays, with newer OSes, changes the email path.