Should work ... if you find any errors / comments they are welcome at alo.peets@ut.ee
0.Make sure you did finish all the tasks of the previous weeks.
We expect here all personal domains are configured, VM is referable by its FDQN internally and externally from UT network (172.17.0.0/16 and 193.40.154.0/23) as well as from client machines ( over VPN ).
- Check that VPN is active in your personal machine
- From your personal machine command line
ping <vm_name>.est
andping student-test.est
should give positive response.- If it does not work remember that you need to edit you personal machine's DNS server info in order to access our custom/fake domain addresses.
PS! Before you continue lab instructors highly recommend to read a very good manual about how e-mail works and how to set it up, from Christoph Haas https://workaround.org/ispmail/stretch page.
1.Setting up personal mail server
Now our fake DNS domain est is ready and populated with individual sub-domains inside, VMs are reachable by FDQN. Moreover each student has full control of his own domain, which means we can add as many names as we wish into our domain. Ideally each service has conventional names, like www for web, mail for smtp or ftp for FTP server. As we start here with e-mail service, let's add the mail host name as well as Mail Exchanger pointer to our DNS configuration.
Understanding MX Records
DNS type MX (Mail eXchange) records are used to specify the mail server(s) 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>.est
domain will be directed to mail.<vm_name>.est
, which in turn points to our IP. So you will need to create a new type A
record, too. If AAAA IPv6 records are present the postfix will use them by default, since we have no IPv6 setup we will not use AAAA records.
Here are some extra materials for type MX records. The minimum you will need to know is: what are the priority values of MX records and how to set them in the zone file.
Edit the Zone <vm_name>.est in bind9
configuration:
- Add a type
A
record formail.<vm_name>.est
with your VM's external IP as a value. - In the same Zone file, add an
MX
record pointing to the hostnamemail.<vm_name>.est
. Set the priority value to 10.- Think about the order, how the records should be organized in the Zone files ?
- MX first then A record or vice-versa? Is there a difference?
- Think about the order, how the records should 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
bind9
service
To test, query for the A
and MX
records you have just created (use either VM itself or the client machine):
dig @193.40.154.X mail.<vm_name>.est
dig @193.40.154.X <vm_name>.est MX
The query should give the answer like (works only if you have set your DNS servers to be the Lab's ones):
teacher@teacher:~$ dig student-test.est -t MX ; <<>> DiG 9.10.3-P4-Debian <<>> -t mx student-test.est ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45912 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 3 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;student-test.est. IN MX ;; ANSWER SECTION: student-test.est. 900 IN MX 10 mail.student-test.est. ;; AUTHORITY SECTION: student-test.est. 900 IN NS ns1.student-test.est. ;; ADDITIONAL SECTION: mail.student-test.est. 900 IN A 193.40.155.0 ns1.student-test.est. 900 IN A 193.40.155.0 ;; Query time: 1 msec ;; SERVER: 127.0.0.1#53(127.0.0.1) ;; WHEN: Sun Mar 24 20:55:38 UTC 2019 ;; MSG SIZE rcvd: 116
Setting up NTP
Before you start, check current clock and timezone info,
$ date
$ timedatectl
update the apt-get (re-synchronize the package index files from their sources):
# apt update
- It is a good practice to do it each time you intend to install something with
apt
orapt-get
, because this makes sure you're installing the latest versions.
- It is a good practice to do it each time you intend to install something with
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 Debian the NTP is handled by the package called ntp
, so let's install it.
Use package manager and install ntp
package
Understanding ntp client configuration
By default the ntp
package comes with the list of predefined servers to sync against the following serves (according to /etc/ntp.conf
:
... pool 0.debian.pool.ntp.org iburst pool 1.debian.pool.ntp.org iburst pool 2.debian.pool.ntp.org iburst pool 3.debian.pool.ntp.org iburst ...
Let's make sure our VMs do also rely on university's NTP server:
ntp.ut.ee
Edit the /etc/ntp.conf
:
- Add the
ntp.ut.ee
into list of the NTP servers - Save the file
- Restart the
ntp
service - Check if that fixed time using
date
command. Probably the clock is not right, as VM's created in the ETAIS cloud come with a UTC timezone by default. Let's fix the timezone mismatch next.- use
timedatectl list-timezones
to identifyTallinn
timezone option - set with
timedatectl
command and correctset-timezone
parameter timezone toEurope/Tallinn
- use
Check if the time is sync using date
command:
$ timedatectl
$ date
Prepare for VM for mail service related packages
For the mail delivery services will want the hostname -f
to
return the FQDN of the VM. One option is to keep the line in /etc/hosts
file:
172.17.64.X yourhost.yourdomain.est yourhost
... we did this in the beginning.
Now we have our DNS fully functional and therefore there is no point of keeping these line in /etc/hosts
as the local DNS should resolve it anyway.
Moreover there is more intelligent way to keep the FQDN information. If you specify the FQDN into /etc/hostname
explicitly - the OS will be always provisioned with its FQDN irregardless of the entries in /etc/hosts
and the Zone records in DNS configuration.
Make sure your VM knows its FQDN
$ hostname -f
should return your yourhost.yourdomain.est
If it does not:
- Fix the
/etc/hostname
correspondingly - Update the
/etc/hosts
correspondingly - Restart the machine
Generating TLS/SSL Certificates
In this lab you will need programs that are not installed by default. Start by installing Postfix, Dovecot, SpamAssassin and Alpine packages. As we mentioned during the first lab session there are other package management tools. apt
can be very handy when you know exact package names and don't expect any complicated troubles with dependencies.
Install packages: Postfix, Dovecot and SpamAssassin with apt
:
# apt install postfix dovecot-imapd spamassassin alpine procmail
It will offer you to install given packages and all their dependencies. Postfix
will also require to remove exim
since there cannot be two mail systems.
After packages are installed, you would be asked to specify some configuration parameters:
- Postfix
- Choose Internet Site
- For System mail name: <hostname>.<your_domain>.est
We will use SMTP and IMAP based mechanisms to exchange messages and to access mailboxes. In "plain" versions, these mechanisms send user names and passwords in clear text across the Internet. In order to protect sensitive data, we will enable support TLS (Transport Layer Security), which will encrypt the traffic. The "plain" versions will still be used by default, so we need to enable TLS on the client-side, too. The predecessor for TLS was called SSL (Secure Sockets Layer).
First we will need a TLS certificate that will be used to identify our servers and start the encrypted connection. Certificate file contains a public key and the corresponding private key is stored in separate file. Our certificates will be self-signed, meaning that there will be no Certification Authority to prove our identity. Some client software will warn about this. (We will fix this later in Apace lab.)
We will use the same (identical) certificate for both SMTP (Postfix) and IMAP (Dovecot) server. It simplifies configuration and authentication slightly in the beginning. In Debian system there is a recommended location for all the certificates and the private keys:
Certificate files are stored under the:
- /etc/ssl/certs
- The files under this directory are having read permissions for all, therefore setting the ownership is not important (public certificates must be public to everyone).
- Check permission with
ls -la /etc/ssl/certs
command.
The private key files are stored under the:
- /etc/ssl/private
- The files under this directory
MUST HAVE
zero permissions for public, and only user and group can read. Additionally the group ownership is assigned to group ssl-cert. - Check permission with
ls -la /etc/ssl/private
command.
- The files under this directory
Generate a new certificate for your mail server:
# openssl req -new -x509 -days 3650 -nodes -out /etc/ssl/certs/dovecot.pem -keyout /etc/ssl/private/dovecot.key
- Use these values to answer the questions (if not listed here, use the default value):
- Country Name=EE
- State or Province Name=Tartumaa
- Locality Name=Tartu
- Organization Name=SA lab
- Organizational Unit Name=Mail Server
- Common Name=
mail.<your_domain>
- Use the same certificate as created in previous step for postfix
- In order to do that,
copy
key/cert pair files you generated for dovecot to the corresponding (/etc/ssl/private,/etc/ssl/certs) directories with namepostfix.pem
andpostfix.key
.cp /etc/ssl/certs/dovecot.pem /etc/ssl/certs/postfix.pem
cp /etc/ssl/private/dovecot.key /etc/ssl/private/postfix.key
- The above steps are needed because dovecot and postfix rely on specific key/pem filenames although in this case we are using same certs and keys.
- In order to do that,
- Be sure all 4 previously created certificate files have right permissions! (You should figure it out yourself)
The OpenSSL commands you may use to check the private keys and certificates:
# openssl rsa -in <private key> -text -noout
# openssl x509 -in <certificate> -text -noout
Additionally you may check if the certificate corresponds to private key, by checking if the modulus component matches:
# openssl x509 -noout -modulus -in <certificate> | openssl md5
# openssl rsa -noout -modulus -in <private key> | openssl md5
Those commands should show the same value.
Setting Up SMTP Service Using the Postfix Software
First you need to install the requiered software
Postfix is an SMTP server (Mail Transfer Agent) that is relatively easy to configure. However, you must still read and understand the "Postfix Configuration- Basics" document before you proceed.
The locations of the Postfix configuration and log file:
- Configuration file:
/etc/postfix/main.cf
- Log file for e-mail related log messages:
/var/log/mail.log
- also, keep on monitoring the
/var/log/messages
log file
In postfix the $mydomain
parameter specifies the parent domain of $myhostname
. By default, it is derived from $myhostname
by stripping off the first part (unless the result would be a top-level domain).
Modify the Postfix configuration file so that it meets the following criteria (most of the variables already exist, modify them instead of adding new lines):
myhostname
parameter should be set tomail.<your_domain>
mydomain
parameter should not be specified and it will be derived frommyhostname
- The domain name for the outbound mail is
<your_domain>
a.k.a$mydomain
myorigin
parameter should set to$mydomain
- Server listens on all the interfaces (
inet_interfaces=all
) - Server should handle mail for following addresses:
<your_domain>, <hostname>.<your_domain>, mail.<your_domain>, localhost.<your_domain>, localhost
- Better use variables like
$mydomain
, localhost.$mydomain ($paramName means that we take content of paramName defined in the current conf file; in postfix configuration file order is not important)
- Better use variables like
- Trusted networks style (
mynetworks_style
) is "host
"- Remove (add comment character in front of line)
relayhost
andmynetworks
parameters and addmynetworks_style
parameter. - Set
mynetworks_style = host
and that forces Postfix to "trust" only the networks the VM is directly attached to.
- Remove (add comment character in front of line)
- The TLS configuration parameters are set up in the following way (these you should replace/add if missing):
smtpd_tls_security_level = may
smtpd_tls_cert_file=/etc/ssl/certs/postfix.pem
smtpd_tls_key_file=/etc/ssl/private/postfix.key
smtpd_tls_loglevel = 1
smtp_tls_loglevel = 1
- The Internet protocols Postfix will attempt to use when making or accepting connections.
inet_protocols = ipv4
- In Debian file
/etc/mailname
might be used to determine your hostname so also change it tomail.<your_domain>
Canonical sender aliases
By default the the postfix will supplement FDQN of the machine it is running in From/To: field's host part. For example if user teacher is sending out and receiving mail from host05.teacher.est machine - the From: will look like:
- teacher@host05.teacher.est
The canonical email addresses however should contain only the domain information after the @ sign. Therefore we have to force the postfix to remove the undesired host information from the From field when sending out. This is done using canonical sender alias maps (or canonical table). According the documentation, the canonical map should contain the rewrite rules, as follows:
<original> <alias>
Here original is the original is the <real user>@<sender host> and the alias is what should be shown instead in the from field. For example if we would need to hide the real user teacher behind the alias SA.Teacher when sending out, the canonical map should contain following:
teacher@host05.teacher.est SA.Teacher@teacher.est
The postfix would rewrite the From field correspondingly for each mail that is sent out by teacher user.
In our setup we first of all will focus on rewriting the host part of the email addresses specified in From field. And the user names we take later (will hide the using both virtual and local aliases). In case only the host part needs to be replaced the canonical file will look like:
@host05.teacher.est @teacher.est
And with this setup any user sending an email from host host05.teacher.est will have his From field rewritten with @teacher.est (leaving his user name untouched).
In /etc/postfix directory:
- Create the empty file called canonical
- Edit the canonical file:
- Add configuration telling postfix to rewrite the From field as follows:
mail.yourdomain.est
->yourdomain.est
yourhostname.yourdomain.est
->yourdomain.est
- Only the host part of the e-mail address has to be rewritten, the user part we currently leave as it is
- Add configuration telling postfix to rewrite the From field as follows:
- Save the
canonical
file: - Compile the
canonical
file into binary hash table:# postmap /etc/postfix/canonical
- Check if the
canonical.db
file was properly created during the compilation process- canonical.db will be stored besides the textual canonical file
Now add the configuration to postfix
telling to use canonical map
Edit the main configuration file of the postfix
- Add the following line:
canonical_maps = hash:/etc/postfix/canonical
If everything is Ok, you can start up the Postfix server. SMTP port will need to be opened from the firewall, too.
- Check the
postfix
servicesystemctl status postfix.service
- Start 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
- You can also use legacy update-rc.d command (i.e.
update-rc.d postfix enable
) .
- You can also use legacy update-rc.d command (i.e.
- Add the firewall rules to accept packets on ports
tcp/25
. Don't forget to save the rules! - Create a new
Security group
inETAIS
calledSMTP
fortcp port 25
and add it 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 userNameHere
- Create a new user with login
mailuser
- Change your user to mail testing user (
sudo su - mailuser
). - Run
alpine
mail client. Send an email to your main user account. - Return to your previous session (and if not there) log in as user and check your
mailbox
. - If sending e-mails between the local users works, try to exchange e-mails with other lab systems (ask for their e-mail addresses).
- Alternatively you may exchange the email with lab assistant, sending mails to teacher@teacher.est.
- The correct configured postfix shall not put the FDQN of your host into from field, only the domain part.
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 the /etc/aliases
file. You can read more about aliases and its file format with command $ man aliases
.
- 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@<your_domain>
must be forwarded tomailuser
's mailbox) - You can also create an alias for non-existent users. To test it create a (local) alias
aliastest
->tester
(as a result of this alias, e-mails sent toaliastest@<your_domain>
must be forwarded totester
's mailbox)
- Create a (local) alias
- Re-generate alias database with command
# newaliases
- Reload postfix configuration with command
# postfix reload
If you might have noticed alpine
can autocomplete e-mail addresses so you could just write username and it will automatically add your hostname
to complete the address. The problem here is that you don't want to send out e-mails with your hostname in the header (i.e X-Original-To: aliastest@host06.teacher.est).In each users' home folder there is alpine configuration file (i.e /home/user/.pinerc
), but editing it will make changes only to particular user alpine
environment. Therefore we must create centralized an alpine configuration file and modify it to achieve our goal.
- Create alpine configuration file
# alpine -conf > /etc/pine.conf
- make sure its readable to everyone but writable only to
root
- make sure its readable to everyone but writable only to
- set parameter
user-domain
to to equal your<domain-name>
(i.e. teacher.est) so alpine will automatically add <your-domain> instead of hostname.<your-domain> to e-mail header.
Now you can test the alias by sending some e-mails:
- Send an e-mail to
root@<your_domain>
, and check if this mail ends up inmailuser
's mailbox. - Send e-mail to
aliastest
from useruser
(but write only "aliastest" intoTo :
line and then hit <DOWN> arrow key.- Aliastest e-mail should end up in
tester
userINBOX
)
- Aliastest e-mail should end up in
- You can send e-mail also from command line
# echo -e "Subject: Command line email-01 \n\nHello! \nThis is a e-mail sent with sendmail command from command line\nby $USER" from $HOSTNAME | /usr/sbin/sendmail aliastest
- You can also read e-mails without
alpine
program from command line# cat /var/mail/tester
- Try reading other user e-mail without
root
permission. Did it work? Why?
General check of the Postfix configuration
The following commands are useful to review the active configuration. Here active configuration means - the configuration from main.cf
loaded once service is restarted.
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:
- You may notice that till now we ask you to read
man
pages or manual, but if you tryman postconf
you get an errorman: command not found
... - so lets install
man
withapt install man
- try now
man postconf
- You may notice that till now we ask you to read
-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)
IMAP Service Using Dovecot Software
We did use 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. Actually, web-based solutions are the most popular by far, but even these often use IMAP behind the scenes.
We will now set up an easy-to-configure IMAP server called Dovecot (the package should be installed already).
Again, you should read and understand the configuration part of the Dovecot manual.
Dovecot Wiki. 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:
Dovecot Wiki
Configuring dovecot logging module
Configure the Dovecot IMAP server's logging module:
- Edit
/etc/dovecot/conf.d/10-logging.conf
file:- Set
log_path
to /var/log/dovecot/dovecot.log - Set
mail_debug
to yes
- Set
- Save file
- In
/var/log
directory- Create
dovecot
directory - Set correctly ownership and permissions (you are expected to figure them out on your own)
- hint: which user is running the dovecot process ?
- You should know it by now but here is the command
ps -aux | grep dovecot
- Create
- Restart the
dovecot
service
Make sure dovecot
writes its logs into /var/log/dovecot/dovecot.log file
Configuring dovecot ssl module
Make Dovecot use the certificate we have created for our server (this will automatically allow TLS):
- Edit
/etc/dovecot/conf.d/10-ssl.conf
file:- Set
ssl
variable toyes
: - Set
ssl_cert
andssl_key
as follows:ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.key
- Set
- Save the file
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.
Today however many people use SSL/TLS, and there's no problem with sending unencrypted password inside SSL secured connections. So if you're using SSL, you probably don't need to bother worrying about anything else than the PLAIN mechanism.
Another plaintext mechanism is LOGIN. It's typically used only by SMTP servers to let Outlook clients perform SMTP authentication. Note that LOGIN mechanism is not the same as IMAP's LOGIN command. The LOGIN command is internally handled using PLAIN mechanism.
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
- Take a look at the other variables, make sure authentication
plain
is only enable over secured connection (TLS/SSL). (PS! You have to find correct parameter name yourself. HINT: nano -> CTRL + w -> type: plain -> ENTER -> CTRL + w -> ENTER -> till you find right parameter.) - 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 tombox:~/mail:INBOX=/var/mail/%u
- Set
- Check default mail folder permissions
ls -ld /var/mail
- It means only the
root
and themail
group has write permission to the directory. You'll need to give Dovecot's mail processes ability to belong to thismail group
by- Setting
mail_privileged_group
variable tomail
- Setting
- Save the file
- Restart the
dovecot
service,- Check the logs, make sure the
dovecot
is running
- Check the logs, make sure the
- Set
dovecot
to autostart usingsystemctl
orupdate-rc.d
command
General check of the Dovecot configuration
Similar to postconf there is a doveconf
command for checking Dovecot configuration. The manual man doveconf
suggest that most of the switches are similar to the ones of the postconf
command (-n, -d, -P).
Firewall Configuration
If everything was set up properly the dovecot
service should now listen for 2 port in TCP stack. What are these ports ?
- Check the default ports used by
dovecot
when serving IMAP/IMAPS:- 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 or with TLS)
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.
If you know the answer, declare the ports in firewall configuration:
- Add the firewall rules to accept the packets on ports used by dovecot (TCP ports: 25, 143, 993)
- Don't forget to save the rules!
- Create a new
Security Group
with nameIMAPS
and add ports143
and993
to it.- Dont forget to add it to Virtual Machine!
Thunderbird configuration
In order to verify Dovecot functionality we can use popular e-mail client called Thunderbird https://www.mozilla.org/en-US/thunderbird/.
- In Linux hosts you can just install the corresponding package using package manager
- In your own/personal machine download and install Thunderbird
- Verify that you can access
<your-host>
i.e.ping mail.teacher.est
from own machine.- If not try:
ping 172.17.64.203
andping 172.17.64.X
if not YOUR VPN is misconfigurednslookup mail.teacher.est
andnslookup mail.<your-domain>
if WRONG ANSWER but ping is OK your host machine networking is messed up -> try:ipconfig /flushdns
or setting inc:/Windows/System32/drivers/etc/hosts
file mappings of IP addresses to host names manually. Restart might also help :)!
- If not try:
- Add a new e-mail address:
Thunderbird -> ALT key -> Tools -> Account settings -> Add mail account -> email address
username@<yourdomain>i.e.
teacher@teacher.est@@ -> add Name and Password -> verify settings (Thunderbird should automatically find configuration) -> Accept self-certificate - Check if you can see e-mail in your INBOX
- Try to send e-mails to other users in your domain
SMTP Authentication
You may have noticed while configuring the Thunderbird client, that the SMTP client was configured automatically along with IMAP client. The mail sending (submission) from Thunderbird is still partial as the SMTP is not authenticated by default as opposed to IMAP. The disadvantage of the unauthenticated SMTP is that it only allows the SMTP client to submit mails to the same domain the SMTP server is serving for. The cross-domain submission will be however impossible.
You may test it as follows:
Using the Thunderbird application on client machine:
- Compose the message to some user inside your domain
- Send the message
Example in teacher.est
domain:
- teacher and teacher2 accounts were in use
- email sent from teacher2@teacher.est to teacher@teacher.est The message header was as follows:
... From: teacher2@teacher.est To: teacher@teacher.est Subject: Test SMTP ...
Now destination user should have received the email (you may check it using the alpine
command of the destination user, or alternatively you may setup another IMAP/SMTP client in Thunderbird.
Now if you try to address mail to the destination in different domain, the SMTP server will respond with a message:
Let's fix the error by adding the authentication to SMTP, like we did with the IMAP:
- enabling STARTTLS and explicit TLS
- enabling PLAIN authentication only over encrypted channel
The differences are however in authentication backend:
- Dovecot relies by default on system
PAM
when authenticating clients, therefore all the user accounts in the host do have IMAP accounts automatically.- The other authentication back-ends possible for Dovecot are: Database, LDAP, Plain password file, etc.
- Postifx suggests using
SASL
protocol for authentication and the systemPAM
doesn't suggest any SASL implementation to use by default (should be configured separately by installing and configuring Cyrus SASL for example).- Alternatively a SASL implementation of the Dovecot may be used (in this case we do not have to install any additional software)
- In this case however the SASL needs to be enabled in the Dovecot
The SMTP authentication chain looks like:
- SMTP client -> SMTP server (postfix) -> Dovecot SASL -> System PAM
Let's start step by step enabling these features:
Configure Dovecot enabling SASL protocol
In /etc/dovecot/conf.d
directory:
- Edit
10-master.conf
file:- Find the smtp-auth block:
# Postfix smtp-auth #unix_listener /var/spool/postfix/private/auth { # mode = 0666 #}
- Enable the block (uncomment)
- Add the following variables
user
andgroup
with the valuepostfix
assigned to both of them.
- Add the following variables
- Enable the block (uncomment)
- Save the file
- Restart the
dovecot
service
Configure Postfix to use Dovecot's SASL back-end
In /etc/postfix
directory:
- Edit the
main.cf
file- Add the following lines:
smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes
Configure Postfix to enable submission port (587) for MUAs
SMTP communication between mail servers uses port 25. Mail clients on the other hand, often submit the outgoing emails to a mail server on port 587. Despite being deprecated, mail providers sometimes still permit the use of historic nonstandard port 465 for this purpose (i.e University of Tartu).
First let's enable the submission port with SASL authentication over STARTTLS. We also allow some certain limitations on email submission:
- Disable anonymous submission
noanonymous
- Restrict SMTP clients: only allow SASL authenticated
- Restrict Relaying: only allow SASL authenticated
- Restrict Originators: From may only contain the "domain" of the SMTP server
- SMTP client cannot put random values into From field
In /etc/postfix
directory:
- Edit the
master.cf
file:- Find the submission port declaration:
#submission inet n - - - - smtpd # -o syslog_name=postfix/submission # -o smtpd_tls_security_level=encrypt # -o smtpd_sasl_auth_enable=yes # -o smtpd_reject_unlisted_recipient=no # -o smtpd_client_restrictions=$mua_client_restrictions # -o smtpd_helo_restrictions=$mua_helo_restrictions # -o smtpd_sender_restrictions=$mua_sender_restrictions # -o smtpd_recipient_restrictions= # -o smtpd_relay_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING
(It is disabled by default)
- Enable the submission block (uncomment the header line)
- In the options list (lines starting with
-o
) in the submission block make sure the following options are enabled:- -o syslog_name=postfix/submission
- -o smtpd_tls_security_level=encrypt
- -o smtpd_sasl_auth_enable=yes
- -o smtpd_sasl_path=private/auth
- -o smtpd_sasl_security_options=noanonymous
- -o smtpd_client_restrictions=permit_sasl_authenticated,reject
- -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
- -o milter_macro_daemon_name=ORIGINATING
- In the options list (lines starting with
(In case some of the options are missing, you should add them)
Now let's also enable secure submission over explicit TLS (SMTPS). We will use the same limitation policies as in submission block
In /etc/postfix
directory:
- Edit the
master.cf
file:- Find the smtps port declaration:
#smtps inet n - - - - smtpd # -o syslog_name=postfix/smtps # -o smtpd_tls_wrappermode=yes # -o smtpd_sasl_auth_enable=yes # -o smtpd_reject_unlisted_recipient=no # -o smtpd_client_restrictions=$mua_client_restrictions # -o smtpd_helo_restrictions=$mua_helo_restrictions # -o smtpd_sender_restrictions=$mua_sender_restrictions # -o smtpd_recipient_restrictions= # -o smtpd_relay_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING
(It is disabled by default)
- Enable the submission block (uncomment the header line)
- In the options list (lines starting with
-o
) in the submission block make sure the following options are enabled:- -o syslog_name=postfix/smtps
- -o smtpd_tls_wrappermode=yes
- SMTPS connection runs in TLS pipe (see previous options) so we do not have to enroll any in-line TLS encryption, therefore we omit the tls_security_level option:
- The rest of the options you may configure as in the submission block
- -o smtpd_sasl_auth_enable=yes
- -o smtpd_sasl_path=private/auth
- -o smtpd_sasl_security_options=noanonymous
- -o smtpd_client_restrictions=permit_sasl_authenticated,reject
- -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
- -o milter_macro_daemon_name=ORIGINATING
- In the options list (lines starting with
- Save the file
- Restart the
postfix
service
Enable the submission port in firewall
Do not forget to enable the submission port on firewall (tcp/587) on firewall and in ETAIS
Testing
How to test: In Thunderbird compose an email to the domain other then yours:
- you may use:
teacher@teacher.est
- SMTP should ask for user name and password (may be stored in Thunderbird already)
- There should be no more error messages like Relay Access Denied and you should get an positive auto-reply from teacher@teacher.est addresses.
Spam Filtering with SpamAssassin and Procmail
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 through procmail
software. spamd
is a SpamAssassin service that calculates "spam scores" for the messages. spamc
is a client for the spamd
. procmail
is a rule-based mail processing tool. We will use procmail
to do the real filtering based on the spam scores set by SpamAssassin.
You can read more about how to set up SpamAssassin in Debian here https://wiki.debian.org/DebianSpamAssassin .
- As a mail test user (
mailuser
), create a.procmailrc
file (in the home directory), read the SpamAssassin/procmail tutorial on what rules to add to this file. Alternatively you can just take the content of the exampleprocmailrc
file and copy its content to mailuser's home folder into file.procmailrc
. The example configuration you may find in: /usr/share/doc/spamassassin/examples/procmailrc.example
After you copied the content, edit the file:
- in the first rule, replace
"|spamassassin"
with"|spamc"
- as the spam folders, use:
mail/almost-certainly-spam
instead ofalmost-certainly-spam
mail/probably-spam
instead ofprobably-spam
- in the first rule, replace
- Enable and start the "
spamassassin
" service (restart if running). Be surespamassassin
will be started at system start-up. - Make sure the
procmail
package is installed:apt-get install procmail
- Verify the
procmail
as the default mail delivery routine inpostfix
:- In directory
/etc/postfix
edit themain.cf
file (postfix main configuration file):- verify that the following line exists:
mailbox_command = procmail -a "$EXTENSION"
- verify that the following line exists:
- Save the file
- In directory
- Restart both
postfix
andspamassassin
services
Test the spam filter by sending some e-mails:
- Send e-mails to user for which you have just created the
.procmailrc
configuration file - Look at the e-mail headers, SpamAssassin should add some extra headers with spam score (
# cat /var/mail/mailuser
) - Read
/usr/share/doc/spamc/sample-spam.txt
on how to create a spam test message. Send such message tomailuser
- Check
/var/log/mail.info
(should be smth like this "spamd: identified spam (999.4/5.0) for mailuser") - If everything is correct, you'll see your spam message in:
$ cat mail/almost-certainly-spam
inmailuser
home directory.
- Check
Sometimes you need to modify SpamAssassin and its rules to customize its action. You can read more aboud how scores are calculated from here. https://www.clickz.com/understand-spamassassin-for-better-delivery-rates/69157/ Following example has been taken from http://www.informit.com/articles/article.aspx?p=375704&seqNum=6 with modifications but it has some more explanation of how it works.
- Take a look at files and rules in
/usr/share/spamassassin/
folder- Good file to start with is
/usr/share/spamassassin/50_scores.cf
- Good file to start with is
- Modify
/etc/spamassassin/local.cf
file and make SpamAssassin more strict by modifyingrequired_score
parameter to value4
- Also uncomment line
rewrite_header Subject *****SPAM*****
- At the end of file
/etc/spamassassin/local.cf
add custom SpamAssassin rule by adding following lines.
body MY_SPAMASSASSIN_RULE /this is a test text for custom spamassassin rule/is describe MY_SPAMASSASSIN_RULE Test of my spamassassin rule score MY_SPAMASSASSIN_RULE 10
- Reload
postfix
andspamassassin
services# service postfix reload
# service spamassassin reload
- Send e-mail to
mailuser
with a text "this is a test text for custom spamassassin rule
" as e-mail content, you can add more text before and/or after it. - Check its spam score and that it ended in spam folder.
Add auto-reply for tester account
If everything worked till now lets make it easy for our automated tester
scripts to white-box test your e-mail server functionality.
- Enable
spamassassin
for usertester
with default rules and custom rule you created in previous task. - Modify file with name
.procmailrc
in tester home folder.- add following lines at the end of it and change
teacher@teacher.est
e-mail totester@<yourdomain>.est
- add following lines at the end of it and change
LOGFILE=/home/tester/procmailrc.log VERBOSE=on #Autoreply for every incoming mail :0 c * !^FROM_DAEMON * !^X-Loop: teacher@teacher.est | (formail -rk -A "Precedence: junk" -A "X-Loop: teacher@teacher.est" ; echo "E-mail received at : " `date`) | /usr/sbin/sendmail -t -oi -oe
- Save the file
- Ask a fellow student to send test e-mail to
tester@<yourdomain>.est
- Check that it will get correct auto-response from your mail server
- Ask a fellow student to send test e-mail to
tester@<yourdomain>.est
with a text "this is a test text for custom SpamAssassin rule
" as e-mail content- This e-mail should get
NO
automatic response as you dont want to respond to spam messages.
- This e-mail should get