Arvutiteaduse instituut
  1. Kursused
  2. 2020/21 kevad
  3. Süsteemihaldus (LTAT.06.003)
EN
Logi sisse

Süsteemihaldus 2020/21 kevad

  • Home
  • Practicals
  • FAQ
  • References

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:

  • MX Record
  • Wikipedia: MX Record

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 for mail.<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 hostname mail.<vm_name>.sa.cs.ut.ee. Set the priority value to 10 .
    • Think about the order, how should the records be organized in the Zone files: MX first then A record or vice-versa? Is there a difference?
  • Save the zone file
    • Should we change the serial before closing ?
  • Test the Zone syntax
    • Remember named-checkzone command
  • 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 or dnf , because that makes sure you're installing the latest versions.
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 identify Tallinn timezone option
    • With timedatectl and the correct set-timezone parameter set the timezone to Europe/Tallinn

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

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 return mail.<vm_name>.sa.cs.ut.ee . postconf returns all of the values of the current configuration and grep -e "^myhostname" searches for a line that starts with myhostname
    • 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
  • The domain name for the outbound mail should be $mydomain
    • Name of outbound mail parameter is $myorigin
  • 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 of paramName defined in the current conf file)
  • Ensure that the trusted networks style ( mynetworks_style ) is host
    • 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.

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 with systemctl
    • Start the service if not running (restart if running),
  • Set postfix service to start automatically at system start-up if not set yet
    • systemctl 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 called SMTP for tcp port 25 and add the security group to you Virtual machine

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
  • 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 run alpine before sending email. Otherwise the emails will not go to the proper folder, and will be not visible from the Message Index screen.
  • 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 to nagios@scoring.sa.cs.ut.ee Nagios check, send an email from mailuser@<vm_name>.sa.cs.ut.ee to nagios@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 )
  • 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 line cat /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 to postmaster->mailuser
    • Create a (local) alias root->mailuser (as a result of this alias, e-mails sent to root@<vm_name>.sa.cs.ut.ee must be forwarded to mailuser '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 to aliastest@<vm_name>.sa.cs.ut.ee must be forwarded to scoring 's mailbox)
  • 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 to yes
  • Save the file
  • Restart the dovecot service

Allow imap prtocol

  • Edit dovecot's main configuration file in /etc/dovecot/dovecot.conf and allow imap 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 allow plain and login
    • set auth_username_format to %n
    • Save the file

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 to maildir:~/mail
  • Check default mail folder permissions ls -ld /var/mail
    • This is where the incoming mail is stored.
  • You can see that only root and the mail group have write permission to the /var/mail. You'll need to give dovecot's mail processes ability to belong to mail group by
    • Setting mail_privileged_group variable to mail
  • Save the file
  • Now make sure that user dovecot is in the mail 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.

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
      }
      
  • 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 using telnet
  • If the connection is successful, try loging in as mailuser by connecting to port 143 of localhost using telnet
    • $ 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 blocks
      • tcp/143 (imap plain) and tcp/993 (imaps - imap over explicit SSL/TLS pipe) .
  • 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's 10-auth.conf and set disable_plaintext_auth to no
  • Edit dovecot's 10-ssl.conf and set ssl to no
  • Restart dovecot and try to authenticate to mail.<vm_name>.sa.cs.ut.ee with telnet. 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 to dovecot'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 with postfix. The socket is created as a file that postfix 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
        }
      }
      
  • In /etc/postfix/main.cf
    • Set mailbox_transport to lmtp:unix:private/dovecot-lmtp
      • This tells postfix to hand all incoming mails to the lmtp socket we created before.
  • Restart postfix

Set postfix to also listen on submission port 587

  • In postfix's master.cf configure submission 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's 10-master.conf file create a unix listener for the auth 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 and dovecot
    • 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

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 and httpd. Use your package manager to install them.
  • Install imagick, mcrypt and zip extensions with pecl:
pecl install $package
  • For each of the extensions installed with pecl, create a file named 20-<extension_name>.ini into /etc/php.d/ and into the file write extension=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. Use man 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 the mv command
  • Set correct owner, group and permissions to /var/www/html/roundcubemail so that apache can access it. Make sure to use the recursive 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 correct selinux 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 be Webmail - <vm_name>.sa.cs.ut.ee
  • In database setup:
    • Set Database type to MySQL
    • Set Database server to localhost
    • Set Database user name to roundcube
    • Set Database password to the random password you generated before
    • Set db_prefix to rc
  • In Logging & Debugging:
    • Set log_dir to /var/log/roundcube
    • Also ensure the /var/log/roundcube directory exists
  • In IMAP settings:
    • Set default_host to localhost
    • Set default_port to 143
  • In SMTP settings:
    • Set smtp_server to localhost
    • Set smtp_port to 587
  • 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. ping mail.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 as Your name
    • mailuser@<vm_name>.sa.cs.ut.ee as Email 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 and set EXTRA_FLAGS to "-m -r 10 -g sa-milt -- --max-size=51200000"
    • -r flag tells spamassass-milter to reject mails with higher score than 10
    • -g flag sets spamass-milter socket writable by the sa-milt group
    • -- tells spamass-milter to pass remaining options to spamc
    • --max-size=5120000 tells spamassassin not to check e-mails larger than 50MB to reduce the server load.
  • Using usermod add postfix to sa-milt group
  • Uses systemctl to restart postfix and spamass-milter
  • You can see default spam detection rules in /usr/share/spamassassin/. Try reading the 20_head_tests.c and understanding the syntax.
  • Default scores can be seen in 50_scores.cf and 72_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 to 4.0
  • Set the score of MISSING_FROM to 1.0
  • Create a rule to test if spamassassin works. Read the

documentation for the correct syntax.

  • Create a body rule and name it SPAMASSASSIN_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 to 5.0
  • Create a body rule and name it SPAMASSASSIN_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 to 11.0
  • 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 to protocols in dovecot's main configuration file.
  • Set mail_plugins = $mail_plugins sieve in dovecot's 15-lda.conf's lda protocol definition
  • Set mail_plugins = $mail_plugins sieve in dovecot's 20-lmtp.conf's lmtp 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 to root@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.

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused