How to set up a mail server on a GNU / Linux system
Step by step guide to install Postfix
Ubuntu + Postfix + Courier IMAP + MySQL + Amavisd-new + SpamAssassin + ClamAV + SASL + TLS + SquirrelMail/Roundcube + Postgrey
Easy to follow howto on setting up a mail server with unlimited users and domains, with IMAP/Pop access, anti-spam, anti-virus, secure authentication, encrypted traffic, web mail interface and more.
Based on an Ubuntu distribution platform, but instructions are distro generic. Examples are run on Amazon AWS ec2, but only for demonstration purposes.
To find out which packages you may have installed, you can use for example: sudo dpkg --list | grep postfix or sudo aptitude search postfix
Configuration
Simple mail server
Now lets configure a simple mail server using some of the packages installed.
Firewall
Shorewall
Not essential for an EC2 image. It is essential for a normal server. UFW is bundled with recent Ubuntu distributions, but I still prefer Shorewall for servers.
Basically at first you want to only allow SSH. Then SMTP and IMAP from your IP only.
When you are confident that the mail server is secure, you can open SMTP to the world. If you prefer you can also open IMAP to the world, unless you have a very small client IP range.
Later you may open web access to the webmail and admin gui. This you may also restrict to specific IPs.
SSH only
By default Shorewall in Ubuntu has an empty set up. You can find the default values for Shorewall in /usr/share/doc/shorwall-common/default-config. And examples in /usr/share/doc/shorwall-common/examples. We will create a basic set up.
First configure which network adapters we are accessing the net. cp /usr/share/doc/shorewall-common/default-config/interfaces /etc/shorewall/ vi /etc/shorewall/interfaces net eth0 detect dhcp,tcpflags,logmartians,nosmurfs
Then we will configure network zones cp /usr/share/doc/shorewall-common/default-config/zones /etc/shorewall/ vi /etc/shorewall/zones Add the firewall if not there and the internet as a zone. fw firewall # loc ipv4 net ipv4
Then if needed to specify hosts you can do it in this file. E.g. If you wanto specify what is your home IP etc. cp /usr/share/doc/shorewall-common/default-config/hosts /etc/shorewall/ vi /etc/shorewall/hosts # loc eth0:192.168.0.0/24
Then set what is the default policy for firewall access. cp /usr/share/doc/shorewall-common/default-config/policy /etc/shorewall/ vi /etc/shorewall/policy $FW net ACCEPT net $FW DROP info net all DROP info # The FOLLOWING POLICY MUST BE LAST all all REJECT info
For safety in case it goes down. cp /usr/share/doc/shorewall-common/default-config/routestopped /etc/shorewall/ vi /etc/shorewall/routestopped eth0 0.0.0.0 routeback You may put in a netmask of your ip range if you are more concerned.
Now for the main firewall rules. You can find predetermined macro rules for Shorewall in /usr/share/shorewall. cp /usr/share/doc/shorewall-common/default-config/rules /etc/shorewall/ vi /etc/shorewall/rules SSH/ACCEPT net $FW
Open for business
Once your server is working come back to this step and open up SMTP and Web access to others.
vi /etc/shorewall/rules Ping/ACCEPT net $FW # Permit all ICMP traffic FROM the firewall TO the net zone ACCEPT $FW net icmp # mail lines SMTP/ACCEPT net $FW SMTPS/ACCEPT net $FW Submission/ACCEPT net $FW IMAP/ACCEPT net $FW IMAPS/ACCEPT net $FW #web Web/ACCEPT net $FWFirewall configuring is always risky business, as it is easy to lock yourself out. To test the setup syntax, run shorewall check Restart it with /etc/init.d/shorewall restart
Then to switch it on during boot: vi /etc/default/shorewall startup=1
For more details on IP Tables and Shorewall, look up its website.
MTA
Postfix
You should put the name of your server in this file sudo vi /etc/mailname Could be something like smtp.domain.name, where domain name obviously is replaced with your domain name.
Now will open the main postfix configuration file: sudo vi /etc/postfix/main.cf Debian and Ubuntu already puts in some sensible default values in this file. You may need to comment some of them out if we put the same in as well.
First specify the name of your server. # This is already done in /etc/mailname #myhostname= mail.example.com Next is the origin which is the domain appended to email from this machine, this can be your full servername, or domain name. # myorigin=/etc/mailname myorigin=example.com
Then decide what the greeting text will be. Enough info so it is useful, but not divelge everything to potential hackers. smtpd_banner = $myhostname ESMTP $mail_name
Next you need to decide whether to send all outgoing mail via another SMTP server, or send them yourself. I send via my ISP’s server, so it has to worry about the queing etc. If you send it yourself then you are not reliant on 3rd party server. But you may risk more exposure and accidentally be blocked by spam blockers. And it is more work for your server. Also many servers block dynamic dns hosts, so you may find your server gets rejected. However choose whichever you are comfortable with. # leave blank to do it yourself relayhost =# or put it an accessible smtp server relayhost = smtp.yourisp.com
Next is network details. You will accept connection from anywhere, and you only trust this machine inet_interfaces = all mynetworks_style = host
Next you can masquerade some outgoing addresses. Say your machine’s name is mail.domain.com. You may not want outgoing mail to come from username@mail.example.com, as you’d prefer username@example.com. You can also state which domain not to masquerade. E.g. if you use a dynamic dns service, then your server address will be a subdomain. You can also specify which users not to masquerade. # masquerade_domains = mail.example.com www.example.com !sub.dyndomain.com # masquerade_exceptions = root
As we will be using virtual domains, these need to be empty. local_recipient_maps = mydestination =
Then will set a few numbers. # how long if undelivered before sending warning update to sender delay_warning_time = 4h # will it be a permanent error or temporary unknown_local_recipient_reject_code = 450 # how long to keep message on queue before return as failed. # some have 3 days, I have 16 days as I am backup server for some people # whom go on holiday with their server switched off. maximal_queue_lifetime = 7d # max and min time in seconds between retries if connection failed minimal_backoff_time = 1000s maximal_backoff_time = 8000s # how long to wait when servers connect before receiving rest of data smtp_helo_timeout = 60s # how many address can be used in one message. # effective stopper to mass spammers, accidental copy in whole address list # but may restrict intentional mail shots. smtpd_recipient_limit = 16 # how many error before back off. smtpd_soft_error_limit = 3 # how many max errors before blocking it. smtpd_hard_error_limit = 12
Now we can specify some restrictions. Be carefull that each setting is on one line only. # Requirements for the HELO statement smtpd_helo_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_hostname, reject_invalid_hostname, permit # Requirements for the sender details smtpd_sender_restrictions = permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit # Requirements for the connecting server smtpd_client_restrictions = reject_rbl_client sbl.spamhaus.org, reject_rbl_client blackholes.easynet.nl, reject_rbl_client dnsbl.njabl.org # Requirement for the recipient address smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, permit smtpd_data_restrictions = reject_unauth_pipelining
Further restrictions: # require proper helo at connections smtpd_helo_required = yes # waste spammers time before rejecting them smtpd_delay_reject = yes disable_vrfy_command = yes
Next we need to set some maps and lookups for the virtual domains. # not sure of the difference of the next two # but they are needed for local aliasing alias_maps = hash:/etc/postfix/aliases alias_database = hash:/etc/postfix/aliases # this specifies where the virtual mailbox folders will be located virtual_mailbox_base = /var/spool/mail/virtual # this is for the mailbox location for each user virtual_mailbox_maps = mysql:/etc/postfix/mysql_mailbox.cf # and their user id virtual_uid_maps = mysql:/etc/postfix/mysql_uid.cf # and group id virtual_gid_maps = mysql:/etc/postfix/mysql_gid.cf # and this is for aliases virtual_alias_maps = mysql:/etc/postfix/mysql_alias.cf # and this is for domain lookups virtual_mailbox_domains = mysql:/etc/postfix/mysql_domains.cf # this is how to connect to the domains (all virtual, but the option is there) # not used yet # transport_maps = mysql:/etc/postfix/mysql_transport.cf
You need to set up an alias file. This is only used locally, and not by your own mail domains. sudo cp /etc/aliases /etc/postfix/aliases # may want to view the file to check if ok. # especially that the final alias, eg root goes # to a real person sudo postalias /etc/postfix/aliases
Next you need to set up the folder where the virtual mail will be stored. This may have already been done by the apt-get. And also create the user whom will own the folders. # to add if there is not a virtual user sudo mkdir /var/spool/mail/virtual sudo groupadd virtual -g 5000 sudo useradd virtual -u 5000 -g 5000 sudo chown -R virtual:virtual /var/spool/mail/virtual
Note: If using Amazon ec2 you may want to move the mail spool to /mnt or an EBS location. You will need to symlink correctly afterwards.
Postfix’s MySQL configuration
Next we need to set up the files to access the lookups via the database. We will only set up a few now, and the rest later when/if needed:
Edit(create) how to find the users mailbox location sudo vi /etc/postfix/mysql_mailbox.cf
user=mail password=mailPASSWORD dbname=maildb table=users select_field=maildir where_field=id hosts=127.0.0.1 additional_conditions = and enabled = 1Create how to find the user id (this step I will eventualy remove) sudo vi /etc/postfix/mysql_uid.cf
user=mail password=mailPASSWORD dbname=maildb table=users select_field=uid where_field=id hosts=127.0.0.1Create how to find the group id. (this step I will eventualy remove) sudo vi /etc/postfix/mysql_gid.cf
user=mail password=mailPASSWORD dbname=maildb table=users select_field=gid where_field=id hosts=127.0.0.1Create how to find the email alias: sudo vi /etc/postfix/mysql_alias.cf
user=mail password=mailPASSWORD dbname=maildb table=aliases select_field=destination where_field=mail hosts=127.0.0.1 additional_conditions = and enabled = 1Create how to find the domains: sudo vi /etc/postfix/mysql_domains.cf
user=mail password=mailPASSWORD dbname=maildb table=domains select_field=domain where_field=domain hosts=127.0.0.1 additional_conditions = and enabled = 1As you can see the 3 first are very similar, only the select_field changes. If you specify an ip in hosts, (as opposed to ‘localhost’) then it will communicate over tcp and not the mysql socket. (chroot restriction). Actually you can avoid using separate uid and guid files as those details are the same for all, but I do anyway. Ps. remember to replace the password with your chosen mail user password.
Database
MySQL
Now we will need to create the tables for thos lookups just specified. First you need to create a user to use in MySQL for mail only. Then you need to create the database, Take note of your chosen mail username and password. You will need the password you specified for root during MySQL package installation.
# If not already done (in package installation)... mysqladmin -u root password new_password # log in as root mysql -u root -p # then enter password for the root account when prompted Enter password: # then we create the mail database create database maildb; # then we create a new user: "mail" GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON maildb.* TO 'mail'@'localhost' IDENTIFIED by 'mailPASSWORD'; GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON maildb.* TO 'mail'@'%' IDENTIFIED by 'mailPASSWORD'; exit; Obviously replace mailPASSWORD with your chosen password!
Then you will need to create these tables:
We will create more later on for further extensions, but only these are relevant now.Log in to mysql as the new mail user mysql -u mail -p maildb # enter the newly created password Enter password:
Then run this commands to create the tables:
CREATE TABLE `aliases` ( `pkid` smallint(3) NOT NULL auto_increment, `mail` varchar(120) NOT NULL default '', `destination` varchar(120) NOT NULL default '', `enabled` tinyint(1) NOT NULL default '1', PRIMARY KEY (`pkid`), UNIQUE KEY `mail` (`mail`) ) ; CREATE TABLE `domains` ( `pkid` smallint(6) NOT NULL auto_increment, `domain` varchar(120) NOT NULL default '', `transport` varchar(120) NOT NULL default 'virtual:', `enabled` tinyint(1) NOT NULL default '1', PRIMARY KEY (`pkid`) ) ; CREATE TABLE `users` ( `id` varchar(128) NOT NULL default '', `name` varchar(128) NOT NULL default '', `uid` smallint(5) unsigned NOT NULL default '5000', `gid` smallint(5) unsigned NOT NULL default '5000', `home` varchar(255) NOT NULL default '/var/spool/mail/virtual', `maildir` varchar(255) NOT NULL default 'blah/', `enabled` tinyint(3) unsigned NOT NULL default '1', `change_password` tinyint(3) unsigned NOT NULL default '1', `clear` varchar(128) NOT NULL default 'ChangeMe', `crypt` varchar(128) NOT NULL default 'sdtrusfX0Jj66', `quota` varchar(255) NOT NULL default '', `procmailrc` varchar(128) NOT NULL default '', `spamassassinrc` varchar(128) NOT NULL default '', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ;The last few fields in the users table are not required, but useful if you extend later.
# To visualise the tables created: describe aliases; describe domains; describe users; # then quit mysql exit;Next is to edit the MySQL’s my.cnf file. In Ubuntu/debian this is created by default. In Mandrake I had to manually create a blank one in /etc. But we need to configure it, so: sudo vi /etc/mysql/my.cnf In previous version you needed to comment out this line #skip-networking However in todays file the default is to bind the address to localhost, which is fine. bind-address = 127.0.0.1 It is very useful at the start to log any SQL calls that makes it to MySQL. So enable this line: log = /var/log/mysql/mysql.log Then in a few weeks comment it out when everything is working, as it slows mysql down
Restart MySQL to make sure its picking up the new settings. sudo /etc/init.d/mysql restart
Pop/IMAP
Courier IMAP
Please refer to previous edition for more explanations. But below is the details of what you need to change.
sudo vi /etc/courier/authdaemonrc Change to mysql mode. authmodulelist="authmysql" Further down enable logging. DEBUG_LOGIN=2
sudo vi /etc/courier/authmysqlrc Changed user MYSQL_USERNAME mail Changed password to whichever you have chosen MYSQL_PASSWORD mailPASSWORD Changed database MYSQL_DATABASE maildb Changed users table MYSQL_USER_TABLE users Keep commented in crypt pw MYSQL_CRYPT_PWFIELD crypt Keep commented out clear pw # MYSQL_CLEAR_PWFIELD clear Added maildir MYSQL_MAILDIR_FIELD concat(home,'/',maildir) Added where clause MYSQL_WHERE_CLAUSE enabled=1
Lastly you can have a look at the imapd file, but no changes is needed. vi /etc/courier/imapd
Summary
You now have a basic mail server!
Before continuing to the advanced and secure mail server you must ensure the basic setup works. This will save you from loads of pain further on.
It is very easy to make typos, miss tiny steps, unclear steps or simple actual errors in this howto.
- Insert stub data from data section
- Apply advice from test section judicously
- Ensure the mail server can receive email correctly first, then try sending.
- Once you are positive the mail has been received, the mail folders have been automatically created,
only then you should test if you can actually read the emails before proceding
Advanced mail server
Now lets extend this setup with more useful content checks , security and user interfaces.
Content Checks (Anti spam & anti virus)
Amavisd-new
Amavisd ties together all the different ways of checking email content for spam and viruses.
The defaults are pretty good and also the ubuntu documentation is pretty clear, and recommended.
Here is a tweaked version of it:
Initially we will not enable spam or virus detection! This is so we can get amavis set up to receive, check and pass on emails before we go on and over-complicate it.
All of amavis’ configuration files are in /etc/amavisd. They are now spread across several files in conf.d. Debian and Ubuntu defaults are now very sensible and spread into seperate files. cd /etc/amavis/conf.d
01-debian defaults are fine.
Have a look at less 05-domain_id but dont change anything in it.
Have a look at less 05-node_id but dont change anything in it.
Have a look at less 15-av_scanners but dont change anything in it.
Edit content check file sudo vi 15-content_filter_mode Comment out both virus and spam scans. (Default). # #@bypass_virus_checks_maps = ( # \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re); # @bypass_spam_checks_maps = ( # \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);
Have a look at less 20-debian_defaults but dont change anything in it.
25-amavis_helpers defaults are fine.
30-template-localization defaults are fine.
Edit user file sudo vi 50-user In the middle insert: @local_domains_acl = qw(.); $log_level = 2; $syslog_priority = 'debug'; $sa_kill_level_deflt = 8.0; # triggers spam evasive actions $final_spam_destiny = D_PASS; # $final_spam_destiny = D_DISCARD;
We have not setup amavis to scan and pass along incomming email. Next we will setup postfix to talk to amavis.
vi /etc/postfix/master.cf Append these lines to the end of the file (make sure they are not already present). (Note the -o lines have spaces in front of them. amavis unix - - - - 2 smtp -o smtp_data_done_timeout=1200 -o smtp_send_xforward_command=yes -o disable_dns_lookups=yes -o max_use=20 127.0.0.1:10025 inet n - - - - smtpd -o content_filter= -o local_recipient_maps= -o relay_recipient_maps= -o smtpd_restriction_classes= -o smtpd_delay_reject=no -o smtpd_client_restrictions=permit_mynetworks,reject -o smtpd_helo_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o smtpd_data_restrictions=reject_unauth_pipelining -o smtpd_end_of_data_restrictions= -o mynetworks=127.0.0.0/8 -o smtpd_error_sleep_time=0 -o smtpd_soft_error_limit=1001 -o smtpd_hard_error_limit=1000 -o smtpd_client_connection_count_limit=0 -o smtpd_client_connection_rate_limit=0 -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks Also add the following two lines immediately below the « pickup » transport service: -o content_filter= -o receive_override_options=no_header_body_checks
and then added to main.cf sudo vi /etc/postfix/main.cf content_filter = amavis:[127.0.0.1]:10024
Enable scanning by ClamAV of amavis’ temporary files. sudo adduser clamav amavis
This should be it to get amavis working. If emails are picked up by amavis and passed back to postfix then it looks okay. Next is to uncomment the anti virus and anti spam lines in sudo vi 15-content_filter_mode @bypass_virus_checks_maps = ( \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re); @bypass_spam_checks_maps = ( \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re); But do that after the next section (SpamAssassin).
When things are working we will turn down logging level, and start bouncing/discarding spam. sudo vi /etc/amavis/conf.d/50-user @local_domains_acl = qw(.); $log_level = 1; $syslog_priority = 'info'; $sa_kill_level_deflt = 8.0; # triggers spam evasive actions #$final_spam_destiny = D_PASS; $final_spam_destiny = D_DISCARD;
Anti-Spam
SpamAssassin
The default config of spam assassin is okay. You could refer to previous edition for more configuration options.
You do need to tell SpamAssassin to start smapd on boot. vi /etc/default/spamassassin ENABLED=1
One configuration option you could tweak is to enable Bayes and auto learning. vi /etc/spamassassin/local.rf
Anti Virus
ClamAV
ClamAV does not need setting up. Configuration files are in /etc/clamav, but they are automatically generated, so do not edit.
By default freshclam, the daemon that updates the virus definition database, is run 24 times a day. That seems a little excessive, so I tend to set that to once a day. sudo dpkg-reconfigure clamav-freshclam It will also ask if you want it to be daemon (yes) and which server is closest to you.
If needed, the command below will redefine the configuration with a lot of questions. Not needed unless you need to configure. sudo dpkg-reconfigure clamav-base
Postgrey
The default config of postgrey is okay. However you need to tell Postfix to use it. sudo vi /etc/postfix/main.cf And then edit the recipient restrictions: smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permit
You can tweak whitelisting in /etc/postgrey. You can tweak postgrey configuration by tweaking /etc/default/postgrey. E.g. delay, auto whitelisting, or reject message. POSTGREY_OPTS="--inet=10023 --max-age=365"
You know have an advanced mail server. You can use this, but Id recommend continuing. However this is a good point to test the set up so far and to insert some data in the db.
Secure mail server
Stopping hackers, phishers, spammers, your boss and your neighbour from accessing your server or the traffic in between is important, and easily done.
Authentication
Normal email traffic between clients and servers are in open plain text. That includes passwords and content of emails.
SASL
SASL secures the actual authentication (login), by encoding the passwords so that it can not be easily intercepted. The rest of the emails are however in clear plain text.
SASL can be a royal pain to set up, especially as it does not support storing encrypted passwords by default in Ubuntu.
Therefor my previous editions described how to configure SASL using plain text passwords in the database.
Obviously this is not ideal, so there are ways to combine SASL and storing encrypted passwords. In the future the packages that comes with Ubuntu may support the password_format configuration option for SASL. But until then you can configure SASL to ask PAM to compare the passwords:
Install packages if not all installed already:
sudo aptitude install sasl2-bin libpam-mysql libsasl2-modules libsasl2-modules-sqlEnable postfix to access SASL files:
sudo adduser postfix saslCreate sasl files accessibly even by chrooted Postfix:
sudo mkdir -p /var/spool/postfix/var/run/saslauthdAdd SASL configurations to Postfix:
sudo vi /etc/postfix/main.cf # SASL smtpd_sasl_auth_enable = yes # If your potential clients use Outlook Express or other older clients # this needs to be set to yes broken_sasl_auth_clients = no smtpd_sasl_security_options = noanonymous smtpd_sasl_local_domain =Modify these existing configurations:
# Add permit_sasl_authenticated to you existing smtpd_sender_restrictions smtpd_sender_restrictions = permit_sasl_authenticated, permit_mynetworks, warn_if_reject reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unauth_pipelining, permit # Add permit_sasl_authenticated to you existing smtpd_recipient_restrictions smtpd_recipient_restrictions = reject_unauth_pipelining, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, permitChange how SASLAUTHD is run:
sudo vi /etc/default/saslauthd # Toggle this to yes START=yes # Switch this to be under postfix's spool # And add -r so that the realm(domain) is part of the username OPTIONS="-r -c -m /var/spool/postfix/var/run/saslauthd"Tell postfix how to interact with SASL:
sudo vi /etc/postfix/sasl/smtpd.conf pwcheck_method: saslauthd mech_list: plain login cram-md5 digest-md5 log_level: 7 allow_plaintext: true auxprop_plugin: mysql sql_engine: mysql sql_hostnames: 127.0.0.1 sql_user: mail sql_passw : aPASSWORD sql_database: maildb sql_select: select crypt from users where id='%u@%r' and enabled = 1(When SASL is working you can remove the log_level line.)
Tell the pam how to to authenticate smtp via mysql:
sudo vi /etc/pam.d/smtpThese must be on 2 lines only, but I have broken them up for easier to read.
auth required pam_mysql.so user=mail passwd=aPASSWORD host=127.0.0.1 db=maildb table=users usercolumn=id passwdcolumn=crypt crypt=1 account sufficient pam_mysql.so user=mail passwd=aPASSWORD host=127.0.0.1 db=maildb table=users usercolumn=id passwdcolumn=crypt crypt=1In addition to tailing var/log/mail.log and /var/log/mysql/mysql.log it is quite usefull to tail the auth.log as well when testing SASL.
tail -f /var/log/auth.logRestart postfix and saslauthd to enable SASL for sending emails.
sudo /etc/init.d/saslauthd restart sudo /etc/init.d/postfix restart
Imap SASL / Courier
I tend not to have SASL for my courier authentication, as I enforce TLS for all my clients.
However if you have a more lenient access policy which is wise if you have many users, then you may want SASL in Courier as well:
sudo vi /etc/courier/imapdThis may already be avaiable as a commented out line. If not replace the current line by adding UTH=CRAM-MD5 AUTH=CRAM-SHA1 so it resembles something like this: (Again on one line)
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA AUTH=CRAM-MD5 AUTH=CRAM-SHA1 IDLE" sudo /etc/init.d/courier-authdaemon restart; sudo /etc/init.d/courier-imap restart
Encryption
TLS
Encrypting the traffic stops anyone else listening in on your email communications. And is very recommended. There are different types of communication to encrypt: The data traffic between your email applications and the server when you read emails or when you send emails, and communication between other email servers and your server.
For the encryption of reading emails, it is Courier you need to configure. For sending, and beetwen server encryption it is Postfix.
TLS in Postfix
To encrypt you need certificates. Ubuntu creates some for you for which you can use while setting up the server. However before you go live, it is recommended to create your own with your proper domain name etc. Please refer to previous edition for more detail.
vi /etc/postfix/main.cf There are already some TLS settings in the default debian/ubuntu version of this file. I moved these to the end, for clarity, but that is up to you. # TLS parameters #smtp_use_tls = no smtp_tls_security_level = may #smtpd_use_tls=yes smtpd_tls_security_level = may #smtpd_tls_auth_only = no smtp_tls_note_starttls_offer = yes smtpd_tls_loglevel = 1 smtpd_tls_received_header = yes smtpd_tls_session_cache_timeout = 3600s tls_random_source = dev:/dev/urandom smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key #smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache #smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
Next we have a look at the master.cf file. vi /etc/postfix/master.cf By default only the normal smtp service is enabled, which is fine. But I prefer to enable submission (port 587), so that clients can use it, and I can restrict them to TLS only. Also enabled smtps service (port 465), for some compatebility with some older clients (outlook express etc).
submission inet n - n - - smtpd -o smtpd_sasl_auth_enable=yes # if you do not want to restrict it encryption only, comment out next line -o smtpd_tls_auth_only=yes # -o smtpd_tls_security_level=encrypt # -o header_checks= # -o body_checks= -o smtpd_client_restrictions=permit_sasl_authenticated,reject_unauth_destination,reject -o smtpd_sasl_security_options=noanonymous,noplaintext -o smtpd_sasl_tls_security_options=noanonymous # -o milter_macro_daemon_name=ORIGINATING smtps inet n - - - - smtpd -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes -o smtpd_tls_auth_only=yes -o smtpd_client_restrictions=permit_sasl_authenticated,reject -o smtpd_sasl_security_options=noanonymous,noplaintext -o smtpd_sasl_tls_security_options=noanonymous # -o milter_macro_daemon_name=ORIGINATING
TLS in Courier
Again Ubuntu has created a certificate for you, but if you want to create your own, especially for a properly named server, then do this. cd /etc/courier openssl req -x509 -newkey rsa:1024 -keyout imapd.pem \ -out imapd.pem -nodes -days 999 For more details review last edition.
Then you need to edit vi /etc/courier/imapd-ssl By default Ubuntu already points to you certificate TLS_CERTFILE=/etc/courier/imapd.pem Modify this if needed.
Also you if want to restrict IMAP users to SSL/TLS only toggle this setting to 1. IMAP_TLS_REQUIRED=1
For maximum compatability it is not wise to restrict to TLS only for the traffic between servers. As this means not all valid emails sent by others can reach your server. However enabling them the option to encrypt is a good idea.
Be aware that the emails are not encrypted on your machine, nor on the server. For this type of client encryption, please refer to previous edition for more on GnuPG.
In some situations SASL and TLS do not play well together. Those situations are in combinations of storing encrypted passwords, using MD5 authentication over encrypted traffic. I recommend, insisting on TLS traffic with your authenticating clients, which then negates the need for SASL.
You know have an advanced secure mail server. Now is another good point to test the set up so far and to insert some data in the db.
Webmail
Using among others the https://help.ubuntu.com/community/Squirrelmail as an updated reference.
Alternative
If you prefer the prettier Roundcube, but less powerfull (at the moment), the follow the Roundcube section in the extention section.
Enable web access
You may need to enable web access in the firewall. Check the firewall configuration if this neccessary.
You need to copy a SquirrelMail configuration to apache. sudo cp /etc/squirrelmail/apache.conf /etc/apache2/sites-available/squirrelmail And enable with this: sudo ln -s /etc/apache2/sites-available/squirrelmail /etc/apache2/sites-enabled/500-squirrelmail Or as Florent recommends, use: sudo a2ensite squirrelmail
You may accept the default apache configuration where squirrelmail is folder in all sites. But I prefer virtual hosting. But you dont need to do these next steps. sudo vi /etc/apache2/sites-available/squirrelmail Comment out the alias. # alias /squirrelmail /usr/share/squirrelmail Uncomment the virtual settings., and insert your servers name. # users will prefer a simple URL like http://webmail.example.com DocumentRoot /usr/share/squirrelmail ServerName webmail.example.com If you have apache SSL enabled in apache, then you can also uncomment the mod_rewrite section for further security.
Reload apache to activate changes. First test if ok. sudo apache2ctl -t Then reload it. sudo /etc/init.d/apache2 reload
You can now go toyourdomain.com/squirrelmail/ or mail.yourdomain.com if you chose virtual host. This should show a squirrel mail page. Log in wont work yet though.
Start configuring squirrel mail.
sudo squirrelmail-configureInitially change nothing. You can customize more afterwards. You can browse, and exit sub menues by typing R.
Type 2 to edit server settings. Type A to edit IMAP settings.
Type 8 to edit server software. Enter courier. courier
Now they say using TLS over localhost is a waste of time. But I do anyway. Type 7 to edit secure IMAP. Type Y to enable it.
Type 5 to edit IMAP port. Enter 993
Type S to save your changes. Hit Enter.
Type Q to exit.
You can now go to yourdomain.com/squirrelmail/ or mail.yourdomain.com if you chose virtual host. This should show a squirrel mail page. Log in will now work. (Except you may not have defined users, check data section. And they may not have received an email which also means you can not view any IMAP info.)
Please refer to previous edition for more detail. E.g. creating address books and user preferences.
Administration
Enable web access
You may need to enable web access in the firewall. Check the firewall configuration if this neccessary.
You need to copy a phpMyAdmin configuration to apache. sudo cp /etc/phpmyadmin/apache.conf /etc/apache2/sites-available/phpmyadmin And enable with this: sudo ln -s /etc/apache2/sites-available/phpmyadmin /etc/apache2/sites-enabled/400-phpmyadmin Or as Florent recommends, use: sudo a2ensite phpmyadmin
You may choose to restrict phpMyAdmin to a spefic virtual host. If so you need to, edit sudo vi /etc/apache2/sites-available/phpmyadmin and comment out the alias. And insert the alias into a virtual host configuration. For this example we are not.
Reload apache to activate changes. First test if ok. sudo apache2ctl -t Then reload it. sudo /etc/init.d/apache2 reload
You can now go to http://yourdomain.com/phpmyadmin/, and login with the mail user. You can use it as it is, but I recommend securing it a bit more.
One simple way is adding apache’s .htaccess login requirement.
Further restrictions can be restricting to a specific virtual host. Or renaming the folder. Purely ubfuscating, but simple.
Or using the example in the webmail section, and adding SSL requirement to the connection. Or disabel mysql root’s access via phpMyAdmin.
Please refer to previous edition for example on htaccess, and mysql user restriction.
You know have a finished mail server. This is as far as the main guide goes. Hope it was clear enough to follow.
Now it is time to insert data, and to test how it works.
Feel free to extend it with my suggestions further down.
Data
Add users and domains
So we got a fully set up mail server… Well no, there is no users, domains, no nothing!
Okay, first you need add some default data, some which are required, some which make sense.
Then we’ll add your own users and domains.
Required domains and users
First the required domains for local mail
# Use phpMyAdmin or command line mysql INSERT INTO domains (domain) VALUES ('localhost'), ('localhost.localdomain');Then some default aliases. Some people say these are not needed, but I’d include them.
INSERT INTO aliases (mail,destination) VALUES ('postmaster@localhost','root@localhost'), ('sysadmin@localhost','root@localhost'), ('webmaster@localhost','root@localhost'), ('abuse@localhost','root@localhost'), ('root@localhost','root@localhost'), ('@localhost','root@localhost'), ('@localhost.localdomain','@localhost');Then a root user.
INSERT INTO users (id,name,maildir,crypt) VALUES ('root@localhost','root','root/', encrypt('apassword') );
Domains and users
Now lets add some proper data.
Say you want this machine to handle data for the fictional domains of « blobber.org », « whopper.nu » and « lala.com ».
Then say this machine’s name is « mail.blobber.org ».
All email to lala.com is to be forwarded to whupper.nu.
INSERT INTO domains (domain) VALUES ('blobber.org'), ('mail.blobber.org'), ('whopper.nu'), ('lala.com'); INSERT INTO aliases (mail,destination) VALUES ('@lala.com','@whupper.nu'), ('@mail.blobber.org','@blobber.org'), ('postmaster@whopper.nu','postmaster@localhost'), ('abuse@whopper.nu','abuse@localhost'), ('postmaster@blobber.org','postmaster@localhost'), ('abuse@blobber.org','abuse@localhost');You also have two users called « Xandros » and « Vivita ».
INSERT INTO users (id,name,maildir,crypt) VALUES ('xandros@blobber.org','xandros','xandros/', encrypt('apassword') ), ('vivita@blobber.org','vivita','vivita/', encrypt('anotherpassword') ); INSERT INTO aliases (mail,destination) VALUES ('xandros@blobber.org','xandros@blobber.org'), ('vivita@blobber.org','vivita@blobber.org');You want all mail for whooper.nu to go to xandros (catchall).
INSERT INTO aliases (mail,destination) VALUES ('@whopper.nu','xandros@blobber.org');There is also a « Karl » user, but he does want all mail forwarded to an external account.
INSERT INTO aliases (mail,destination) VALUES ('karl@blobber.org','karl.vovianda@gmail.com');So what does each of these lines actually do? Well the domains are pretty straight forward.
The users are as well, it requires four fields. ID is the email address of the user, and also its username when loggin in, described later on. NAME is optional description of the user. MAILDIR is the name of the folder inside /var/spool/mail/virtual. It must end in a /, otherwise it wont be used as a unix maildir format. CRYPT is the encrypted text password to use.
The alises are the interesting part. Lets start from a top down view to see how emails get delivered:
Say an email arrives addressed to « john@whopper.nu ».
- Postfix looks up domains and say whopper.nu is an domain it listens to.
- Postfix then looks up aliases and searches for a row where the mail field matches « john@whopper.nu ».
- None does so it next searches for « @whopper.nu », which is the way to specify catch all others for that domain.
- It finds one row and its destination is « xandros@blobber.org ».
- It then searches for « xandros@blobber.org » and finds one, which destination is the same as the mail, therefor it is the final destination.
- It then tries to deliver this mail. The look up says blobber.org is a local mail so it looks up users for a matching id and delivers it to its maildir.
Lets try « julian.whippit@lala.com ».
- Postfix looks up domains and it is an domain it listens to.
- First lookup does not find this user, but the next finds the catchall « @lala.com ». But its destination is another catchall, « @blobber.org ».
- This means Postfix will look for « julian.whippit@blobber.org ». This address is not found either, nor is a catchall for blobber.org. Therefor this address is not valid and the message will be bounced.
Any mail arriving for « karl@blobber.org » or « karl@lala.com », gets forward to an external address of « karl.vovianda@gmail.com ». So forwarding is simple. I tend to use a subdomain for all my friends addresses as easily I forget what their real addresses are, and I use different email clients all the time.
I also added the required aliases of postmaster and abuse to blobber.org and whopper.nu. The catchall for lala.com means they are not required for that domain.