Difference between revisions of "Postfix"

From ArchWiki
Jump to: navigation, search
m (main.cf: edit style flag)
 
(177 intermediate revisions by 56 users not shown)
Line 1: Line 1:
[[Category:Mail Server]]
+
[[Category:Mail server]]
 +
[[ja:Postfix]]
 
{{Related articles start}}
 
{{Related articles start}}
{{Related|PostFix Howto With SASL}}
+
{{Related|Postfix with SASL}}
{{Related|Simple Virtual User Mail System}}
+
{{Related|Amavis}}
 +
{{Related|Virtual user mail system}}
 
{{Related|Courier MTA}}
 
{{Related|Courier MTA}}
{{Related|SOHO Postfix}}
+
{{Related|Exim}}
 +
{{Related|OpenSMTPD}}
 +
{{Related|OpenDMARC}}
 +
{{Related|OpenDKIM}}
 +
{{Related|SOGo}}
 
{{Related articles end}}
 
{{Related articles end}}
 
From [http://www.postfix.org/ Postfix's site]:
 
From [http://www.postfix.org/ Postfix's site]:
:"''Postfix attempts to be fast, easy to administer, and secure, while at the same time being sendmail compatible enough to not upset existing users. Thus, the outside has a sendmail-ish flavor, but the inside is completely different.''"
+
:Postfix attempts to be fast, easy to administer, and secure, while at the same time being sendmail compatible enough to not upset existing users. Thus, the outside has a sendmail-ish flavor, but the inside is completely different.
  
The goal of this article is to setup Postfix for virtual mailbox delivery only. There will be no delivery to user accounts on the system ({{ic|/etc/passwd}}). Further, access will only be available via a web mail frontend (Squirrelmail), no direct POP3 or IMAP access will be granted. It should be fairly easy to allow those additional features given the information below, but it is not within the scope of this document.
+
The goal of this article is to setup Postfix and explain what the basic configuration files do. There are instructions for setting up local system user-only delivery and a link to a guide for virtual user delivery.  
  
== Required packages ==
+
== Installation ==
  
{{Accuracy|The squirrelmail and courier-imap packages have been dropped from the offical repositories and moved to the [[AUR]]. {{Pkg|roundcubemail}} is an officially supported possible alternative to Squirrelmail}}
+
[[Install]] the {{Pkg|postfix}} package.
  
* {{Pkg|postfix}}
+
== Configuration ==
* {{AUR|courier-imap}}
 
* {{Pkg|squirrelmail}}
 
* {{Pkg|mariadb}}
 
* {{Pkg|apache}}
 
* {{Pkg|openssl}}
 
  
== Postfix configuration ==
+
=== master.cf ===
  
=== Step 1: check /etc/passwd, /etc/group ===
+
{{ic|/etc/postfix/master.cf}} is the master configuration file where you can specify which protocols will be served. It is also the place where you can put your new pipes e.g. to check for Spam!
  
After Postfix installation, make sure that the following shows up in {{ic|/etc/passwd}}:
+
It is recommended to enable secure SMTP as described in [[#Secure SMTP (sending)]] and [[#Secure SMTP (receiving)]].
postfix:x:73:73::/var/spool/postfix:/bin/false
 
  
Make sure that the following shows up in {{ic|/etc/group}}:
+
See [http://www.postfix.org/TLS_README.html this page] for more information about encrypting outgoing and incoming email.
postdrop:x:75:
 
postfix:x:73:
 
  
{{Note|Postfix can be made to run in a chroot. This document does not currently cover this and might be added later.}}
+
=== main.cf ===
  
=== Step 2: setup MX record ===
+
{{Style|Even the comments in the default {{ic|main.cf}} contain recommendations for more scenarios.}}
  
An MX record should point to the mail host. Usually this is done from configuration interface of your domain provider.
+
{{ic|/etc/postfix/main.cf}} is the main configuration file where everything is configured. The settings below are recommended for virtual local-only delivery.
  
A mail exchanger record (MX record) is a type of resource record in the Domain Name System that specifies a mail server responsible for accepting email messages on behalf of a recipient's domain.  
+
*{{ic|myhostname}} should be set if your mail server has multiple domains, and you do not want the primary domain to be the mail host. You should have both a DNS A record and an MX record point to this hostname.
 +
:{{bc|1=myhostname = mail.nospam.net}}
  
When an e-mail message is sent through the Internet, the sending mail transfer agent queries the Domain Name System for MX records of each recipient's domain name. This query returns a list of host names of mail exchange servers accepting incoming mail for that domain and their preferences. The sending agent then attempts to establish an SMTP connection to one of these servers, starting with the one with the smallest preference number, delivering the message to the first server with which a connection can be made.  
+
*{{ic|mydomain}} is usually the value of {{ic|myhostname}}, minus the first part. If your domain is wonky, then just set it manually.
 +
:{{bc|1=mydomain = nospam.net}}
  
{{Note|Some mail servers will not deliver mail to you if your MX record points to a CNAME. For best results, always point an MX record to an A record definition. For more information, see e.g. [https://secure.wikimedia.org/wikipedia/en/wiki/List_of_DNS_record_types Wikipedia's List of DNS Record Types].}}
+
*{{ic|myorigin}} is where the email will be seen as being sent from. I usually set this to the value of {{ic|mydomain}}. For simple servers, this works fine. This is for mail originating from a local account. Since we are not doing local delivery (except sending), then this is not really as important as it normally would be.  
 +
:{{bc|1=myorigin = $mydomain}}
  
=== Step 3: /etc/postfix/master.cf ===
+
*{{ic|mydestination}} is the lookup for local users.
 +
:{{bc|1=mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain}}
  
This is the Pipeline configuration file, in which you can put your new pipes e.g. to check for Spam!
+
*{{ic|mynetworks}} and {{ic|mynetworks_style}} control relaying, and whom is allowed to. We do not want any relaying.
 +
:For our sakes, we will simply set {{ic|mynetwork_style}} to host, as we are trying to make a standalone Postfix host, that people will use webmail on. No relaying, no other MTA's. Just webmail.
 +
:{{bc|1=mynetworks_style = host}}
  
=== Step 4: /etc/postfix/main.cf ===
+
*{{ic|relaydomains}} controls the destinations that Postfix will relay TO. The default value is empty. This should be fine for now.
 +
:{{bc|1=relay_domains = }}
  
==== For virtual mail ====
+
*{{ic|home_mailbox}} or {{ic|mail_spool_directory}} control how mail is delivered/stored for the users.
 +
:If set, {{ic|mail_spool_directory}} specifies an absolute path where mail gets delivered. By default Postfix stores mails in {{ic|/var/spool/mail}}.
  
===== Step 4.1 myhostname =====
+
:{{bc|1=mail_spool_directory = /home/vmailer}}
  
set myhostname if your mail server has multiple domains, and you do not want the primary domain to be the mail host. The default is to use the result of a gethostname() call if nothing is specified.
+
:Alternatively, if set, {{ic|home_mailbox}} specifies a mailbox relative to the user's home directory where mail gets delivered (eg: /home/vmailer).
For our purposes we will just set it as follows:
 
  
myhostname = mail.nospam.net
+
:Courier-IMAP requires "Maildir" format, so you '''must''' set it like the following example with trailing slash:
 +
:{{bc|1=home_mailbox = Maildir/}}
  
This is assuming that a DNS A record, and an MX record both point to mail.nospam.net
+
{{Warning|If you plan on implementing SSL/TLS, please respond safely to [https://weakdh.org/sysadmin.html FREAK/Logjam] by adding the following to your configuration:
 +
{{bc|1=
 +
smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CBC3-SHA, KRB5-DES, CBC3-SHA}}
  
===== Step 4.2 mydomain =====
+
Then, generate a [https://www.openssl.org/docs/man1.0.2/apps/dhparam.html dhparam file] by following [https://weakdh.org/sysadmin.html these instructions] and then adding the following to your configuration:
 +
{{bc|1=smtpd_tls_dh1024_param_file = ${config_directory}/dhparams.pem}}
  
this is usually the value of myhostname, minus the first part. If your domain is wonky, then just set it manually:
+
Since mid-2015, the default settings have been safe against [http://disablessl3.com/ POODLE].
 +
}}
  
mydomain = nospam.net
+
==== Default message and mailbox size limits ====
  
===== Step 4.3 myorigin =====
+
Postfix imposes both message and mailbox size limits by default. The message_size_limit controls the maximum size in bytes of a message, including envelope information. (default 10240000) The mailbox_size_limit controls the maximum size of any local individual mailbox or maildir file. This limits the size of '''any''' file that is written to upon local delivery, '''including files written by external commands''' (i.e. procmail) that are executed by the local delivery agent. (default is 51200000, set to 0 for no limit) If bounced message notifications are generated, check the size of the local mailbox under {{ic|/var/spool/mail}} and use postconf to check these size limits:
  
this is where the email will be seen as being sent from. I usually set this to the value of mydomain. For simple servers, this works fine. This is for mail originating from a local account. Since we are not doing local delivery (except sending), then this is not really as important as it normally would be.
+
# postconf mailbox_size_limit
 +
mailbox_size_limit = 51200000
 +
# postconf message_size_limit
 +
message_size_limit = 10240000
  
myorigin = $mydomain
+
=== Aliases ===
  
===== Step 4.4 mydestination =====
+
You can specify aliases (also known as forwarders) in {{ic|/etc/postfix/aliases}}.
  
This is the lookup for local users. Since we are not going to deliver internet mail for any local users, set this to localhost only.
+
You need to map all mail addressed to ''root'' to another account since it is not a good idea to read mail as root.  
  
  mydestination = localhost
+
Uncomment the following line, and change {{ic|you}} to a real account.
 +
  root: you
  
===== Step 4.5 mynetworks and mynetwork_style =====
+
Once you have finished editing {{ic|/etc/postfix/aliases}} you must run the postalias command:
 +
postalias /etc/postfix/aliases
 +
For later changes you can use:
 +
newaliases
  
Both of these control relaying, and whom is allowed to. We do not want any relaying.
+
{{Tip|Alternatively you can create the file {{ic|~/.forward}}, e.g. {{ic|/root/.forward}} for root. Specify the user to whom root mail should be forwarded, e.g. ''user@localhost''.
For our sakes, we will simply set mynetwork_style to host, as we are trying to make a standalone postfix host, that people with use webmail on. No relaying, no other MTA's. Just webmail.
 
  
 +
{{hc|/root/.forward|
 +
user@localhost
 +
}}
 +
 +
}}
 +
 +
=== Local mail ===
 +
 +
To only deliver mail to local system users (that are in {{ic|/etc/passwd}}) update {{ic|/etc/postfix/main.cf}} to reflect the following configuration. Uncomment, change, or add the following lines:
 +
 +
myhostname = localhost
 +
mydomain = localdomain
 +
mydestination = $myhostname, localhost.$mydomain, localhost
 +
inet_interfaces = $myhostname, localhost
 
  mynetworks_style = host
 
  mynetworks_style = host
 +
default_transport = error: outside mail is not deliverable
  
===== Step 4.6 relaydomains =====
+
All other settings may remain unchanged. After setting up the above configuration file, you may wish to set up some [[#Aliases]] and then [[#Start Postfix]].
  
This controls the destinations that Postfix will relay TO. The default value is $mydestination. This should be fine for now.
+
=== Virtual mail ===
 +
Virtual mail is mail that does not map to a user account ({{ic|/etc/passwd}}).
  
relay_domains = $mydestination
+
See [[Virtual user mail system]] for a comprehensive guide how to set it up.
  
===== Step 4.7 home_mailbox =====
+
=== DNS records ===
  
This setting controls how mail is stored for the users.
+
An MX record should point to the mail host. Usually this is done from configuration interface of your domain provider.
Set this to "Maildir/", as courier IMAP requires Maildir style mail storage. This is a good thing. Maildir format mailboxes remove the possible race conditions that can occur with old style mbox formats. No more need to deal with file locking. The '/' at the end is REQUIRED.
 
  
home_mailbox = Maildir/
+
A mail exchanger record (MX record) is a type of resource record in the Domain Name System that specifies a mail server responsible for accepting email messages on behalf of a recipient's domain.
  
===== Step 4.8 virtual_mail =====
+
When an e-mail message is sent through the Internet, the sending mail transfer agent queries the Domain Name System for MX records of each recipient's domain name. This query returns a list of host names of mail exchange servers accepting incoming mail for that domain and their preferences. The sending agent then attempts to establish an SMTP connection to one of these servers, starting with the one with the smallest preference number, delivering the message to the first server with which a connection can be made.  
  
Virtual mail is mail that does not map to a user account ({{ic|/etc/passwd}}). This is where all the email for the system will be kept. We are not doing local delivery, remember, so if you want a user that has the same name as a local user, just make a virtual account with the same name.
+
{{Note|Some mail servers will not deliver mail to you if your MX record points to a CNAME. For best results, always point an MX record to an A record definition. For more information, see e.g. [[Wikipedia:List of DNS record types|Wikipedia's List of DNS Record Types]].}}
First thing we need to do is add the following:
 
  
virtual_mailbox_domains = virtualdomain.tld
+
=== Check configuration ===
virtual_alias_maps = hash:/etc/postfix/virtual_alias, mysql:/etc/postfix/mysql_virtual_forwards.cf
 
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains.cf
 
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailboxes.cf
 
virtual_mailbox_base = /home/vmailer
 
virtual_uid_maps = static:5003
 
virtual_gid_maps = static:5003
 
virtual_minimum_uid = 5003
 
virtual_mailbox_limit = 51200000
 
  
virtual_mailbox_domains is a list of the domains that you want to receive mail for. This CANNOT be the same thing that is listed in mydestination. That is why we left mydestination to be localhost only.
+
Run the {{ic|postfix check}} command. It should output anything that you might have done wrong in a config file.  
virtual_mailbox_maps will contain the info about the virtual users and their mailbox locations. We are using a hash file to store the more permanent maps, and these will override the forwards in the MySQL database.
 
  
virtual_mailbox_base is the base dir where the virtual mailboxes will be stored.
+
To see all of your configs, type {{ic|postconf}}. To see how you differ from the defaults, try {{ic|postconf -n}}.
The gid and uid maps are the real system user account that the virtual mail will be owned by. This is for storage purposes. Since we will be using a web interface, and do not want people accessing this by any other means, we will be creating this account later with no login access.
 
Virtual_mailbox_limit controls the size of the mailbox. I do not know how well this works yet. I have set the size above to about 50MB.
 
  
===== Step 4.9 Default message and mailbox size limits =====
+
== Start Postfix ==
  
Postfix imposes both message and mailbox size limits by default. The message_size_limit controls the maximum size in bytes of a message, including envelope information. (default 10240000) The mailbox_size_limit controls the maximum size of any local individual mailbox or maildir file. This limits the size of '''any''' file that is written to upon local delivery, '''including files written by external commands''' (i.e. procmail) that are executed by the local delivery agent. (default is 51200000, set to 0 for no limit) If bounced message notifications are generated, check the size of the local mailbox under {{ic|/var/spool/mail}} and use postconf to check these size limits:
+
{{Note|You must run {{ic|newaliases}} at least once for postfix to run, even if you did not set up any [[#Aliases]].}}
  
supersff:~> postconf -d mailbox_size_limit
+
[[Start/enable]] the {{ic|postfix.service}}.
mailbox_size_limit = 51200000
 
supersff:~> postconf -d message_size_limit
 
message_size_limit = 10240000
 
  
==== Local mail ====
+
== Testing ==
  
The only things you need to change in {{ic|/etc/postfix/main.cf}} are as follows. Uncomment them and modify them to the specifics listed below. Everything else can be left as installed.
+
{{Style|Needs some cleanup. There are probably more general ways to write this.}}
  
inet_interfaces = loopback-only
+
Now lets see if Postfix is going to deliver mail for our test user.
mynetworks_style = host
+
{{bc|
append_dot_mydomain = no
+
nc servername 25
default_transport = error: Local delivery only!
+
helo testmail.org
 +
mail from:<test@testmail.org>
 +
rcpt to:<cactus@virtualdomain.tld>
 +
data
 +
This is a test email.
 +
.
 +
quit
 +
}}
  
If you want to control where the mail gets delivered and which mailbox format is to be used, you can do this by setting:
+
=== Error response ===
home_mailbox = /some/path
 
or:
 
mail_spool_directory some/path
 
''mail_spool_directory'' is an absolute path where all mail goes, while ''home_mailbox'' specifies a mailbox relative to the user's home directory. If the path ends with a slash ('/'), messages are stored in Maildir format (directory tree, one message per file); if it doesn't, the mbox format is used (all mail in one file).
 
  
Examples:
+
451 4.3.0 <lisi@test.com>:Temporary lookup failure
mail_spool_directory = /var/mail  (1)
+
Maybe you have entered the wrong user/password for MySQL or the MySQL socket is not in the right place.
home_mailbox = Maildir/           (2)
 
1) All mail will be stored in {{ic|/var/mail}}, mbox format.
 
  
2) Mail will be saved in {{ic|~/Maildir}}, Maildir format.
+
This error will also occur if you neglect to run newaliases at least once before starting postfix. MySQL is not required for local only usage of postfix.
  
=== Step 4: /etc/postfix/aliases ===
+
550 5.1.1 <email@spam.me>: Recipient address rejected: User unknown in virtual mailbox table.
 +
Double check content of mysql_virtual_mailboxes.cf and check the main.cf for mydestination
  
We need to map some aliases to real accounts. The default setup by arch looks pretty good here.
+
=== See that you have received a email ===
  
Uncomment the following line, and change it to a real account. I put the user account on the box that I use. Best not to just send mail to root, because you do not want to be logging in as root or checking email as root. Not good. Sudo is your friend, and so is forwarding root mail. Since this is for local delivery only (syslogs and stuff), it is still within the realm of mydestination.
+
Now type {{ic|$ find /home/vmailer}}.
  
root: USER
+
You should see something like the following:
 +
{{bc|
 +
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld
 +
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/tmp
 +
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/cur
 +
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new
 +
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new/1102974226.2704_0.bonk.testmail.org
 +
}}
 +
The key is the last entry. This is an actual email, if you see that, it is working.
  
Once you have finished editing {{ic|/etc/postfix/aliases}} you must run the postalias command:
+
== Extra ==
  
postalias /etc/postfix/aliases
+
=== PostfixAdmin ===
  
=== Step 5: /etc/postfix/virtual_alias ===
+
To use PostfixAdmin, you need a working Apache/MySQL/PHP setup as described in [[Apache HTTP Server]].
  
Create {{ic|/etc/postfix/virtual_alias}} with the following contents:
+
For IMAP functionality, you will need to install {{Pkg|php-imap}} and uncomment imap.so in /etc/php/php.ini
  
{{bc|
+
Next, [[install]] {{Pkg|postfixadmin}}.
MAILER-DAEMON:  postmaster
 
postmaster:    root
 
  
# General redirections for pseudo accounts
+
{{Style|in-code comments}}
bin:            root
 
daemon:        root
 
named:          root
 
nobody:        root
 
uucp:          root
 
www:            root
 
ftp-bugs:      root
 
postfix:        root
 
  
# Put your local aliases here.
+
Edit the PostfixAdmin configuration file:
  
# Well-known aliases
+
{{hc|/etc/webapps/postfixadmin/config.inc.php|<nowiki>
manager:        root
+
$CONF['configured'] = true;
dumper:        root
+
// correspond to dovecot maildir path /home/vmail/%d/%u
operator:      root
+
$CONF['domain_path'] = 'YES';
abuse:          postmaster
+
$CONF['domain_in_mailbox'] = 'NO';
 +
$CONF['database_type'] = 'mysqli';
 +
$CONF['database_host'] = 'localhost';
 +
$CONF['database_user'] = 'postfix_user';
 +
$CONF['database_password'] = 'hunter2';
 +
$CONF['database_name'] = 'postfix_db';
  
# trap decode to catch security attacks
+
// globally change all instances of ''change-this-to-your.domain.tld''
decode:        root
+
// to an appropriate value
 +
</nowiki>}}
  
# Person who should get root's mail. Don't receive mail as root!
+
If installing dovecot and you changed the password scheme in dovecot (to SHA512-CRYPT for example), reflect that with postfix
root:          cactus@virtualdomain.tld
 
}}
 
  
Then run the postalias command on it:
+
{{hc|/etc/webapps/postfixadmin/config.inc.php|<nowiki>
postalias /etc/postfix/virtual_alias
+
$CONF['encrypt'] = 'dovecot:SHA512-CRYPT';
 +
</nowiki>}}
  
Alternatively you can create the file .forward in /rootspecify the user to whom root mail should be forwarded, e.g. ''user@localhost''.
+
As of dovecot 2, dovecotpw has been deprecatedYou will also want to ensure that your config reflects the new binary name.
  
{{hc|/root/.forward|
+
{{hc|/etc/webapps/postfixadmin/config.inc.php|<nowiki>
user@localhost
+
$CONF['dovecotpw'] = "/usr/sbin/doveadm pw";
}}
+
</nowiki>}}
  
=== Step 6. mysql_virtual_domains.cf ===
+
Create the Apache configuration file:
 +
{{hc|/etc/httpd/conf/extra/httpd-postfixadmin.conf|<nowiki>
 +
Alias /postfixadmin "/usr/share/webapps/postfixAdmin"
 +
<Directory "/usr/share/webapps/postfixAdmin">
 +
    DirectoryIndex index.html index.php
 +
    AllowOverride All
 +
    Options FollowSymlinks
 +
    Require all granted
 +
</Directory>
 +
</nowiki>}}
  
Create the {{ic|/etc/postfix/mysql_virtual_domains.cf}} file with the following (or similar) contents:
+
To only allow localhost access to postfixadmin (for heightened security), add this to the previous <Directory> directive:
 +
    Order Deny,Allow
 +
    Deny from all
 +
    Allow from 127.0.0.1
  
user = postfixuser
+
Now, include httpd-postfixadmin.conf to {{ic|/etc/httpd/conf/httpd.conf}}:
password = XXXXXXXXXX
+
  # PostfixAdmin configuration
hosts = localhost
+
  Include conf/extra/httpd-postfixadmin.conf
dbname = postfix
 
table = domains
 
  select_field = 'virtual'
 
  where_field = domain
 
  
=== Step 7: mysql_virtual_mailboxes.cf ===
+
{{Note|If you go to yourdomain/postfixadmin/setup.php and it says do not find config.inc.php, add {{ic|/etc/webapps/postfixadmin}} to the {{ic|open_basedir}} line in {{ic|/etc/php/php.ini}}.}}
 +
{{Note|If you get a blank page check the syntax of the file with {{ic|php -l /etc/webapps/postfixadmin/config.inc.php}}.}}
  
Create the /etc/postfix/mysql_virtual_mailboxes.cf file with the following (or similar) contents:
+
=== Postgrey ===
  
user = postfixuser
+
{{Style|See [[Help:Style]]}}
password = XXXXXXXXXX
 
hosts = localhost
 
dbname = postfix
 
table = users
 
select_field = concat(domain,'/',email,'/')
 
where_field = email
 
  
Instead of having a directory structure something like ''/home/vmail/example.com/user@example.com'' you can have cleaner subdirectories (without the additional domain name) by replacing ''select_field'' and ''where_field'' with:
+
[http://postgrey.schweikert.ch/ Postgrey] can be used to enable greylisting for a Postfix mail server.
  
query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') FROM users WHERE email='%s'
+
==== Installation ====
  
=== Step 8: mysql_virtual_forwards.cf ===
+
[[Install]] the {{Pkg|postgrey}} package. To get it running quickly edit the Postfix configuration file and add these lines:
 +
{{hc|/etc/postfix/main.cf|<nowiki>
 +
smtpd_recipient_restrictions =
 +
  check_policy_service inet:127.0.0.1:10030
 +
</nowiki>}}
  
Create the {{ic|/etc/postfix/mysql_virtual_forwards.cf}} file with the following (or similar) contents:
+
Then [[start/enable]] the {{ic|postgrey}} service. Afterwards, reload the {{ic|postfix}} service. Now greylisting should be enabled.
  
user = postfixuser
+
==== Configuration ====
password = XXXXXXXXXX
 
hosts = localhost
 
dbname = postfix
 
table = forwardings
 
select_field = destination
 
where_field = source
 
  
=== Step 9: Postfix check ===
+
Configuration is done via editing the {{ic|greylist.service}} file. First copy it over to edit it.
  
Run the {{ic|postfix check}} command. It should output anything that you might have done wrong in a config file.  
+
# cp /usr/lib/systemd/system/postgrey.service /etc/systemd/system/
  
To see all of your configs, type {{ic|postconf}}. To see how you differ from the defaults, try {{ic|postconf -n}}.
+
Now you can edit it. For example, to add automatic whitelisting (successful deliveries are whitelisted and don't have to wait any more), you could add the {{ic|<nowiki>--auto-whitelist-clients=N</nowiki>}} option and replace {{ic|N}} by a suitably small number (or leave it at its default of 5).
  
=== Step 10: enable and start the service ===
+
...actually, the preferred method should be the override:
  
Enabling the [[systemd]] service '''postfix''' will automatically start Postfix at boot, but needs to be started manually for the first time.
+
cat /etc/systemd/system/postgrey.service.d/override.conf
  
=== Step 11: newuser ===
+
[Service]
 +
ExecStart=
 +
ExecStart=/usr/bin/postgrey --inet=127.0.0.1:10030 \
 +
        --pidfile=/run/postgrey/postgrey.pid \
 +
        --group=postgrey --user=postgrey \
 +
        --daemonize \
 +
        --greylist-text="Greylisted for %%s seconds" \
 +
        --auto-whitelist-clients
  
We need to create the user for storing the virtual mail. Create a vmailuser as follows:
+
==== Troubleshooting ====
  
# groupadd -g 5003 vmail
+
If you specify --unix=/path/to/socket and the socket file is not created ensure you have removed the default --inet=127.0.0.1:10030 from the service file.  
# useradd -g vmail -u 5003 -d /home/vmailer -s /bin/false vmailer
 
# mkdir /home/vmailer
 
# chown vmailer.vmail /home/vmailer
 
# chmod -R 750 /home/vmailer
 
# passwd vmailer
 
  
5003 UID/GID are the ones specified in the Postfix main.cf file.
+
For a full documentation of possible options see {{ic|perldoc postgrey}}.
  
== MySQL configuration ==
+
=== Secure SMTP (sending) ===
  
=== Step 1: create a MySQL database ===
+
By default, Postfix/sendmail will not send email encrypted to other SMTP servers. To use TLS when available, add the following line to {{ic|main.cf}}:
 +
{{hc|/etc/postfix/main.cf|2=
 +
smtp_tls_security_level = may
 +
}}
  
Create MySQL database called 'postfix', or something similar.
+
To ''enforce'' TLS (and fail when the remote server does not support it), change {{ic|may}} to {{ic|encrypt}}.
  
CREATE DATABASE postfix;
+
=== Secure SMTP (receiving) ===
USE postfix;
+
For more information, see [http://www.postfix.org/TLS_README.html Postfix TLS Support].
  
=== Step 2: setup table structure ===
+
==== STARTTLS over SMTP (port 587) ====
  
Import the following table structure.
+
To enable STARTTLS over SMTP (port 587, the proper way of securing SMTP), add the following lines to {{ic|main.cf}}
{{bc|
 
CREATE TABLE `domains` (
 
  `domain` varchar(50) NOT NULL default "",
 
  PRIMARY KEY  (`domain`),
 
  UNIQUE KEY `domain` (`domain`)
 
);
 
  
 +
{{hc|/etc/postfix/main.cf|2=
 +
smtpd_tls_security_level = may
 +
smtpd_tls_cert_file = '''/path/to/cert.pem'''
 +
smtpd_tls_key_file = '''/path/to/key.pem'''
 +
}}
  
CREATE TABLE `forwardings` (
+
Also in {{ic|master.cf}} find and remove the comment from the following line to enable the service on that port:
  `source` varchar(80) NOT NULL default "",
 
  `destination` text NOT NULL,
 
  PRIMARY KEY  (`source`)
 
);
 
  
CREATE TABLE `users` (
+
{{hc|/etc/postfix/master.cf|2=
  `email` varchar(80) NOT NULL default "",
+
submission inet n      -      n      -      -      smtpd
  `password` varchar(20) NOT NULL default "",
 
  `quota` varchar(20) NOT NULL default '20971520',
 
  `domain` varchar(255) NOT NULL default "",
 
  UNIQUE KEY `email` (`email`)
 
);
 
 
}}
 
}}
  
=== Step 3: create a MySQL user ===
+
If you need support for the deprecated SMTPS port 465, read the next section.
  
Add a user for Postfix to use. Something like "postfixuser".
+
==== SMTPS (port 465) ====
Give permissions for Postfix user to the table. This user should be listed in the {{ic|/etc/postfix/mysql_virtual_domains.cf}} file.
 
  
The [http://dev.mysql.com/doc/refman/5.5/en/server-administration.html official reference manual] has a detailed guide on user management and server administration in general.
+
The deprecated method of securing SMTP is using the '''wrapper mode''' which uses the system service '''smtps''' as a non-standard service and runs on port 465.
  
The following is just an example for creation of 'postfixuser' with password 'XXXXXXXXXX'.
+
To enable it uncomment the following lines in
Note that the GRANT statements need to be executed after creating the tables in the next step.
 
  
  CREATE USER 'postfixuser' IDENTIFIED BY 'XXXXXXXXXX';
+
{{hc|/etc/postfix/master.cf|<nowiki>
GRANT SELECT, INSERT, UPDATE, DELETE ON domains TO postfixuser;
+
smtps    inet n      -      n      -      -      smtpd
GRANT SELECT, INSERT, UPDATE, DELETE ON forwardings TO postfixuser;
+
  -o smtpd_tls_wrappermode=yes
GRANT SELECT, INSERT, UPDATE, DELETE ON users TO postfixuser;
+
  -o smtpd_sasl_auth_enable=yes
 +
</nowiki>}}
  
=== Step 4: add a domain ===
+
And verify that these lines are in {{ic|/etc/services}}:
 +
smtps 465/tcp # Secure SMTP
 +
smtps 465/udp # Secure SMTP
  
INSERT INTO `domains` VALUES ('virtualdomain.tld');
+
If they are not there, go ahead and add them (replace the other listing for port 465). Otherwise Postfix will not start and you will get the following error:
  
=== Step 5: add a user ===
+
''postfix/master[5309]: fatal: 0.0.0.0:smtps: Servname not supported for ai_socktype''
  
INSERT INTO `users` VALUES ('cactus@virtualdomain.tld', 'secret',
+
=== SpamAssassin ===
'20971520', 'virtualdomain.tld');
 
  
The above creates the user and sets a password as secret.  
+
Install the {{Pkg|spamassassin}} package.
  
This will allow you to use encrypted passwords
+
Go over {{ic|/etc/mail/spamassassin/local.cf}} and configure it to your needs.
  
INSERT INTO `users` VALUES ('cactus@virtualdomain.tld', ENCRYPT('secret'),
+
==== Spam Assassin rule update ====
'20971520', 'virtualdomain.tld');
 
  
== Test Postfix ==
+
Update the SpamAssassin matching patterns and compile them:
 +
# sa-update
 +
# sa-compile
  
Start Postfix service. Now lets see if Postfix is going to deliver mail for our test user.
+
You will want to run this periodically, the best way to do so is by setting up a [[Systemd/Timers]].
{{bc|
+
 
telnet servername 25
+
Create the following service, which will run these commands:
ehlo testmail.org
+
{{hc|1=/etc/systemd/system/spamassassin-update.service|2=
mail from:<test@testmail.org>
+
[Unit]
rcpt to:<cactus@virtualdomain.tld>
+
Description=spamassassin housekeeping stuff
data
+
 
This is a test email.
+
[Service]
 +
#User=spamd
 +
#Group=spamd
 +
Type=oneshot
 +
ExecStart=/usr/bin/vendor_perl/sa-update --allowplugins #You can remove the allowplugins options if you do not want direct plugin updates from SA.
 +
SuccessExitStatus=0 1 #0 = updated, 1 = no updates available
 +
ExecStart=/usr/bin/vendor_perl/sa-compile
 +
SuccessExitStatus=0
 +
# You can automatically train SA's bayes filter by uncommenting this line and specifying the path to a mailbox where you store email that is spam (for ex this could be yours or your users manually reported spam)
 +
#ExecStart=/usr/bin/vendor_perl/sa-learn --spam <path to your spam>
 +
}}
 +
 
 +
Then create the timer, which will execute the previous service daily:
 +
{{hc|1=/etc/systemd/system/spamassassin-update.timer|2=
 +
[Unit]
 +
Description=spamassassin house keeping
 +
 
 +
[Timer]
 +
OnCalendar=daily
 +
Persistent=true
 +
 
 +
[Install]
 +
WantedBy=timers.target
 +
}}
 +
 
 +
Finally, you'll need to modify your Spamassassin systemd service file so that it knows to restart itself to read the new rules. Copy the bundled service file to a custom service file:
 +
{{bc|1=
 +
# cp /usr/lib/systemd/system/spamassassin.service /etc/systemd/system
 +
}}
  
.
+
And edit the newly created {{ic|/etc/systemd/system/spamassassin.service}} to include:
quit
+
{{bc|1=
 +
[Unit]
 +
PartOf=spamassassin-update.service
 
}}
 
}}
  
=== Error response ===
+
This will ensure that Spamassassin's spamd is restarted just before the timer runs. This means the rules will be available the next day if your timer runs daily. This is so that there is no long service interruption while {{ic|sa.service}} runs as it takes a while to compile rules.
  
451 4.3.0 <lisi@test.com>:Temporary lookup failure
+
Now you can [[start]] and [[enable]] {{ic|spamassassin-update.timer}}.
Maybe you have entered the wrong user/password for MySQL or the MySQL socket is not in the right place.
 
  
550 5.1.1 <email@spam.me>: Recipient address rejected: User unknown in virtual mailbox table.
+
==== SpamAssassin stand-alone generic setup ====
Double check content of mysql_virtual_mailboxes.cf and check the main.cf for mydestination
 
  
=== See that you have received a email ===
+
{{Note|If you want to combine SpamAssassin and Dovecot Mail Filtering, ignore the next two lines and continue further down instead.}}
  
Now type {{ic|$ find /home/vmailer}}.
+
Edit {{ic|/etc/postfix/master.cf}} and add the content filter under smtp.
 +
{{bc|1=
 +
smtp      inet  n      -      n      -      -      smtpd
 +
  -o content_filter=spamassassin
 +
}}
  
You should see something like the following:
+
Also add the following service entry for SpamAssassin
{{bc|
+
{{bc|1=
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld
+
spamassassin unix -    n      n      -      -      pipe
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/tmp
+
  flags=R user=spamd argv=/usr/bin/vendor_perl/spamc -e /usr/bin/sendmail -oi -f ${sender} ${recipient}
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/cur
 
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new
 
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new/1102974226.2704_0.bonk.testmail.org
 
 
}}
 
}}
The key is the last entry. This is an actual email, if you see that, it is working.
 
  
== Configure Courier IMAP ==
+
Now you can [[start]] and [[enable]] {{ic|spamassassin.service}}.
 +
 
 +
==== SpamAssassin combined with Dovecot LDA / Sieve (Mailfiltering) ====
 +
Set up LDA and the Sieve-Plugin as described in [[Dovecot#Sieve]]. But ignore the last line {{ic|mailbox_command... }}.
 +
 
 +
Instead add a pipe in {{ic|/etc/postfix/master.cf}}:
 +
  dovecot  unix  -      n      n      -      -      pipe
 +
        flags=DRhu user=vmail:vmail argv=/usr/bin/vendor_perl/spamc -u spamd -e /usr/lib/dovecot/dovecot-lda -f ${sender} -d ${recipient}
  
=== Step 1: /etc/courier-imap/imapd ===
+
And activate it in {{ic|/etc/postfix/main.cf}}:
 +
  virtual_transport = dovecot
  
ADDRESS=127.0.0.1
+
==== SpamAssassin combined with Dovecot LMTP / Sieve ====
 +
Set up the LMTP and Sieve as described in [[Dovecot#Sieve]].
  
We set the listen address to LOCAL ONLY. No outside connections.
+
Edit {{ic|/etc/dovecot/conf.d/90-plugins.conf}} and add:
  
=== Step 2: /etc/authlib/authdaemonrc ===
+
  sieve_before = /etc/dovecot/sieve.before.d/
 +
  sieve_extensions = +vnd.dovecot.filter
 +
  sieve_plugins = sieve_extprograms
 +
  sieve_filter_bin_dir = /etc/dovecot/sieve-filter
 +
  sieve_filter_exec_timeout = 120s #this is often needed for the long running spamassassin scans, default is otherwise 10s
  
Remove all the modules from the authmodulelist line except for authmysql like so:
+
Create the directory and put spamassassin in as a binary that can be ran by dovecot:
  
authmodulelist="authmysql"
+
  # mkdir /etc/dovecot/sieve-filter
 +
  # ln -s /usr/bin/vendor_perl/spamc /etc/dovecot/sieve-filter/spamc
  
=== Step 3: /etc/authlib/authmysqlrc ===
+
Create a new file, {{ic|/etc/dovecot/sieve.before.d/spamassassin.sieve}} which contains:
  
Replace the ''entire'' file with the following:
+
  require [ "vnd.dovecot.filter" ];
{{bc|
+
  filter "spamc" [ "-d", "127.0.0.1", "--no-safe-fallback" ];
MYSQL_SERVER            localhost
 
MYSQL_USERNAME          postfixuser
 
MYSQL_PASSWORD          secret
 
MYSQL_SOCKET            /run/mysqld/mysqld.sock
 
MYSQL_DATABASE          postfix
 
# MYSQL_NAME_FIELD      name
 
MYSQL_USER_TABLE        users
 
MYSQL_CLEAR_PWFIELD    password
 
MYSQL_UID_FIELD        '5003'
 
##note, this is the uid that we set in /etc/postfix/main.cf
 
MYSQL_GID_FIELD        '5003'
 
##note, this is the gid that we set in /etc/postfix/main.cf
 
MYSQL_LOGIN_FIELD      email
 
MYSQL_HOME_FIELD        "/home/vmailer"
 
MYSQL_MAILDIR_FIELD    concat(domain,'/',email,'/')
 
MYSQL_QUOTA_FIELD      quota
 
}}
 
Where secret is the MySQL password for the user postfixuser.
 
If you are using encrypted passwords by using MySQL's encrypt function. Use "MYSQL_CRYPT_PWFIELD columnname" instead of "MYSQL_CLEAR_PWFIELD columnname".
 
  
For an alternative directory structure, you could also use this setting for MAILDIR_FIELD:
+
Compile the sieve rules {{ic|spamassassin.svbin}}:
  
MYSQL_MAILDIR_FIELD    CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/')
+
  # cd /etc/dovecot/sieve.before.d
 +
  # sievec spamassassin.sieve
  
In this case, ''courier'' will use a directory like {{ic|/home/vmail/exampledomain.com/exampleuser}}.
+
Finally, [[restart]] {{ic|dovecot.service}}.
  
=== Step 4: autorun imapd on system start ===
+
==== Call ClamAV from SpamAssassin ====
  
If you already using [[systemd]], enable '''authdaemond''' and '''courier-imapd.services'''.
+
Install and setup clamd as described in [[ClamAV]].
If authdaemond fails to start, make sure the folder {{ic|/run/authdaemon}} exists.
 
  
=== Step 5: Fam and rpcbind ===
+
Follow one of the above instructions to call SpamAssassin from within your mail system.
  
{{Accuracy|FAM should not be required anymore.|section=FAM is obsolete}}
+
[[Install]] the {{pkg|perl-cpanplus-dist-arch}} package. Then install the ClamAV perl library as follows:
Courier-imap for arch comes compiled with FAM. This means portmap is also required. What used to be portmap is nowadays called rpcbind.
 
  
Install {{Pkg|rpcbind}} and edit {{ic|/etc/fam/fam.conf}}
+
  # /usr/bin/vendor_perl/cpanp -i File::Scan::ClamAV
 +
 
 +
Add the 2 files from http://wiki.apache.org/spamassassin/ClamAVPlugin into {{ic|/etc/mail/spamassassin/}}.
 +
Edit {{ic|/etc/mail/spamassassin/clamav.pm}} and update {{ic|$CLAM_SOCK}} to point to your Clamd socket location (default is {{ic|/var/lib/clamav/clamd.sock}}).
  
local_only = true
+
Finally, [[restart]] {{ic|spamassassin.service}}.
idle_timeout = 0
 
  
Make sure the two above values are set. Then start and enable the daemon '''rpcbind'''.
+
=== Using Razor ===
 +
Make sure you have installed SpamAssassin first, then:
  
=== Step 6: start courier imap ===
+
[[Install]] the {{Pkg|razor}} package.
  
Start the ''courier-imapd.service'' daemon.
+
Register with Razor.
  
=== Step 7: Test courier ===
+
  # mkdir /etc/mail/spamassassin/razor
 +
  # chown spamd:spamd /etc/mail/spamassassin/razor
 +
  # sudo -u spamd -s
 +
  $ cd /etc/mail/spamassassin/razor
 +
  $ razor-admin -home=/etc/mail/spamassassin/razor -register
 +
  $ razor-admin -home=/etc/mail/spamassassin/razor -create
 +
  $ razor-admin -home=/etc/mail/spamassassin/razor -discover
  
Lets see if courier is working:
+
Tell SpamAssassin about Razor, add
{{bc|<nowiki>
 
telnet localhost imap
 
Trying 127.0.0.1...
 
Connected to localhost.localdomain.
 
Escape character is '^]'.
 
* OK [[CAPABILITY IMAP4rev1 ... ]] Courier-IMAP ready.
 
  
A LOGIN "cactus@virtualdomain.tld" "password"
+
  razor_config /etc/mail/spamassassin/razor/razor-agent.conf
A OK LOGIN Ok.
 
  
B SELECT "Inbox"
+
to {{ic|/etc/mail/spamassassin/local.cf}}.
* FLAGS (\Draft \Answered ... \Recent)
 
* OK [[PERMANENTFLAGS (\Draft \Answered ... \Seen)]] Limited
 
* 8 EXISTS
 
* 5 RECENT
 
* OK [[UIDVALIDITY 1026858715]] Ok
 
B OK [[READ-WRITE]] Ok
 
  
Z LOGOUT
+
Tell Razor about itself, add
* BYE Courier-IMAP server shutting down
 
Z OK LOGOUT completed
 
Connection closed by foreign host.
 
</nowiki>}}
 
  
== Configure Squirrelmail==
+
  razorhome = /etc/mail/spamassassin/razor/
  
=== Step 1: Create secure http site (https) ===
+
to  {{ic|/etc/mail/spamassassin/razor/razor-agent.conf}}
  
We are going to create a secure http site. This is so that people can login with plain text passwords, and not have to worry about the passwords getting sniffed (or worry less).
+
Finally, [[restart]] {{ic|spamassassin.service}}.
  
==== Step 1.1: Edit /etc/httpd/conf/extra/httpd-ssl.conf ====
+
===Hide the sender's IP and user agent in the Received header===
 +
This is a privacy concern mostly, if you use Thunderbird and send an email. The received header will contain your LAN and WAN IP and info about the email client you used.
 +
(Original source: [http://askubuntu.com/questions/78163/when-sending-email-with-postfix-how-can-i-hide-the-senders-ip-and-username-in AskUbuntu])
 +
What we want to do is remove the Received header from outgoing emails. This can be done by the following steps:
  
Add appropriate information. Here is an example section:
+
Add this line to main.cf
{{bc|
+
smtp_header_checks = regexp:/etc/postfix/smtp_header_checks
<VirtualHost _default_:443>
+
Create /etc/postfix/smtp_header_checks with this content:
#  General setup for the virtual host
+
/^Received: .*/     IGNORE
DocumentRoot "/home/httpd/site.virtual/virtualdomain.tld/html"
+
/^User-Agent: .*/   IGNORE
ServerName virtualdomain.tld:443
+
Finally, restart postfix.service
ServerAdmin noemailonthisbox@localhost
 
<Directory "/home/httpd/site.virtual/virtualdomain.tld/html">
 
    Options -Indexes +FollowSymLinks
 
    AllowOverride Options Indexes AuthConfig
 
    Order allow,deny
 
    Allow from all
 
</Directory>
 
}}
 
  
==== Step 1.15 Include httpd-ssl.conf in httpd.conf ====
+
=== Postfix in a chroot jail ===
 +
Postfix is not put in a chroot jail by default. The Postfix documentation [http://www.postfix.org/BASIC_CONFIGURATION_README.html#chroot_setup] provides details about how to accomplish such a jail. The steps are outlined below and are based on the chroot-setup script provided in the postfix source code.
  
Simply uncomment this line in your httpd.conf:
+
First, go into the {{ic|master.cf}} file in the directory {{ic|/etc/postfix}} and change all the chroot entries to 'yes' (y) except for the services {{ic|qmgr}}, {{ic|proxymap}}, {{ic|proxywrite}}, {{ic|local}}, and {{ic|virtual}}
  
  #Include conf/extra/httpd-ssl.conf
+
Second, create two functions that will help us later with copying files over into the chroot jail (see last step)
 +
  CP="cp -p"
  
==== Step 1.2: Create the directory structure ====
+
cond_copy() {
 +
  # find files as per pattern in $1
 +
  # if any, copy to directory $2
 +
  dir=`dirname "$1"`
 +
  pat=`basename "$1"`
 +
  lr=`find "$dir" -maxdepth 1 -name "$pat"`
 +
  if test ! -d "$2" ; then exit 1 ; fi
 +
  if test "x$lr" != "x" ; then $CP $1 "$2" ; fi
 +
}
  
Now, create the directory you specified in the ssl.conf file.
+
Next, make the new directories for the jail:
 +
set -e
 +
umask 022
  
  $ mkdir -p /home/httpd/site.virtual/virtualdomain.tld/html
+
  POSTFIX_DIR=${POSTFIX_DIR-/var/spool/postfix}
 +
cd ${POSTFIX_DIR}
  
==== Step 1.3: Generate a certificate ====
+
mkdir -p etc lib usr/lib/zoneinfo
 +
test -d /lib64 && mkdir -p lib64
  
Follow the instructions here: [[LAMP#SSL]]
+
Find the localtime file
 +
lt=/etc/localtime
 +
if test ! -f $lt ; then lt=/usr/lib/zoneinfo/localtime ; fi
 +
if test ! -f $lt ; then lt=/usr/share/zoneinfo/localtime ; fi
 +
if test ! -f $lt ; then echo "cannot find localtime" ; exit 1 ; fi
 +
rm -f etc/localtime
  
==== Step 1.4: restart Apache and test ====
+
Copy localtime and some other system files into the chroot's etc
 +
$CP -f $lt /etc/services /etc/resolv.conf /etc/nsswitch.conf etc
 +
$CP -f /etc/host.conf /etc/hosts /etc/passwd etc
 +
ln -s -f /etc/localtime usr/lib/zoneinfo
  
Make sure that https is now working, and that you can get to the secure site.
+
Copy required libraries into the chroot using the previously created function {{ic|cond_copy}}
 +
cond_copy '/usr/lib/libnss_*.so*' lib
 +
cond_copy '/usr/lib/libresolv.so*' lib
 +
cond_copy '/usr/lib/libdb.so*' lib
  
=== Step 2: put Squirrelmail in the directory you created===
+
And don't forget to reload postfix.
  
Either extract squirrelmail, or move it from where the arch package puts it, into the directory you created for the secure http site.
+
===Rule-based mail processing===
 +
With policy services one can easily finetune postfix' behaviour of mail delivery.
 +
{{Pkg|postfwd}} and <span class="plainlinks archwiki-template-pkg">[https://aur.archlinux.org/pkgbase/policyd policyd]</span><sup><small>AUR</small></sup> provide services to do so.
 +
This allows you to e.g. implement time-aware grey- and blacklisting of senders and receivers as well as [[SPF]] policy checking.
  
=== Step 3: run Squirrelmail config utility ===
+
Policy services are standalone services and connected to Postfix like this:
 +
{{hc|/etc/postfix/main.cf|<nowiki>
 +
smtpd_recipient_restrictions =
 +
  ...
 +
  check_policy_service unix:/run/policyd.sock
 +
  check_policy_service inet:127.0.0.1:10040
 +
</nowiki>}}
 +
Placing policy services at the end of the queue reduces load, as only legitimate mails are processed. Be sure to place it before the first permit statement to catch all incoming messages.
  
cd ''squirrelmaildir''/config
+
=== DANE (DNSSEC) ===
perl conf.pl
+
==== Resource Record ====
  
Make sure you select 'D', then type in courier and hit enter. Make sure your other options are correct as well.
+
{{warning|This is not a trivial section. Be aware that you make sure you know what you are doing. You better read [https://dane.sys4.de/common_mistakes Common Mistakes] before.}}
Note: If you use php with safe mode on, make sure that the data dir is owned by the same owner as all the files in the squirrelmail directory. With safe mode off, simply follow the squirrelmail setup directions.
 
  
=== Step 4: test the Squirrelmail setup ===
+
[[DANE]] supports several types of records, however not all of them are suitable in postfix.
  
Point your browser to squirrelmail/src/configtest.php. Should you get an error on directory location, make sure php.ini has been set to allow access to them (open_basedir directive).
+
Certificate usage 0 is unsupported, 1 is mapped to 3 and 2 is optional, thus it is recommendet to publish a "3" record.
 +
More on [[DANE#Resource Record|Resource Records]].
  
=== Step 5: test Squirrelmail ===
+
==== Configuration ====
 +
Opportunistic DANE is configured this way:
 +
{{hc|/etc/postfix/main.cf|<nowiki>
 +
smtpd_use_tls = yes
 +
smtp_dns_support_level = dnssec
 +
smtp_tls_security_level = dane
 +
</nowiki>}}
 +
{{hc|/etc/postfix/master.cf|<nowiki>
 +
dane      unix  -      -      n      -      -      smtp
 +
  -o smtp_dns_support_level=dnssec
 +
  -o smtp_tls_security_level=dane
 +
</nowiki>}}
  
Log in with the test account. You will need to login with the form of:  
+
To use per-domain policies, e.g. opportunistic DANE for example.org and mandatory DANE for example.com,
username: cactus@virtualdomain.tld
+
use something like this:
password: secret
+
{{hc|/etc/postfix/main.cf|<nowiki>
 +
indexed = ${default_database_type}:${config_directory}/
  
Try sending email to non-existent local accounts. You should get an immediate bounce back.
+
# Per-destination TLS policy
Try sending email to external good email accounts, as well as non-existent ones.
+
#
Just general testing stuff.
+
smtp_tls_policy_maps = ${indexed}tls_policy
If everything works fine, then you can add other accounts to the MySQL database, and away you go!
 
  
==== Troubleshooting ====
+
# default_transport = smtp, but some destinations are special:
 +
#
 +
transport_maps = ${indexed}transport
 +
</nowiki>}}
  
If you received an error similar to:
+
{{hc|transport|
{{bc|1=Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/var/lib/squirrelmail/data) is not within the allowed path(s): \
+
example.com dane
(/srv/http/:/home/:/tmp/:/usr/share/pear/) in /home/httpd/site.virtual/virtualdomain.tld/html/squirrelmail/src/configtest.php on line 303
+
example.org dane
 
}}
 
}}
Then edit {{ic|/etc/httpd/httpd.conf}}, and in the section:
 
<Directory "/home/httpd/site.virtual/virtualdomain.tld/html">
 
add:
 
php_admin_value open_basedir /home/httpd/site.virtual/virtualdomain.tld/html:/var/lib/squirrelmail/
 
  
If you get an error similar to:
+
{{hc|tls_policy|
Unknown user or password incorrect.
+
example.com dane-only
You may have to create your user directories within vmailer like so:
+
}}
  
$ mkdir -p /home/vmailer/''mydomain.com''/username''
+
{{Note|For global mandatory DANE, change {{ic|smtp_tls_security_level}} to {{ic|dane-only}}. Be aware that this makes postfix tempfail on all delivieres that do not use DANE at all!}}
$ mkdir /home/vmailer/''mydomain.com''/username''/cur
 
$ mkdir /home/vmailer/''mydomain.com''/username''/new
 
$ mkdir /home/vmailer/''mydomain.com''/username''/tmp
 
$ chmod -R 750 /home/vmailer
 
$ chown -R vmailer.vmail /home/vmailer
 
  
where ''mydomain.com''/''username'' is the ''domain''/''username'' given within MySQL.
+
Full documentation is found [http://www.postfix.org/TLS_README.html#client_tls_dane here].
  
== See also==
+
== See also ==
  
*[http://linox.be/index.php/2005/07/13/44/ Out of Office] for Squirrelmail
+
* [http://linox.be/index.php/2005/07/13/44/ Out of Office] for Squirrelmail {{Dead link|2017|08|23}}
*[https://help.ubuntu.com/community/Postfix Postfix Ubuntu documentation]
+
* [https://help.ubuntu.com/community/Postfix Postfix Ubuntu documentation]
*[http://www.gelens.org/archlinux-mailserver/ A simple mailserver on Arch Linux]
 
*[http://sherlock.heroku.com/blog/2012/02/03/setting-up-postfix-to-use-gmail-as-an-smtp-relay-host-in-archlinux/ Use Gmail as an SMTP relay]
 

Latest revision as of 21:49, 2 December 2017

From Postfix's site:

Postfix attempts to be fast, easy to administer, and secure, while at the same time being sendmail compatible enough to not upset existing users. Thus, the outside has a sendmail-ish flavor, but the inside is completely different.

The goal of this article is to setup Postfix and explain what the basic configuration files do. There are instructions for setting up local system user-only delivery and a link to a guide for virtual user delivery.

Installation

Install the postfix package.

Configuration

master.cf

/etc/postfix/master.cf is the master configuration file where you can specify which protocols will be served. It is also the place where you can put your new pipes e.g. to check for Spam!

It is recommended to enable secure SMTP as described in #Secure SMTP (sending) and #Secure SMTP (receiving).

See this page for more information about encrypting outgoing and incoming email.

main.cf

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: Even the comments in the default main.cf contain recommendations for more scenarios. (Discuss in Talk:Postfix#)

/etc/postfix/main.cf is the main configuration file where everything is configured. The settings below are recommended for virtual local-only delivery.

  • myhostname should be set if your mail server has multiple domains, and you do not want the primary domain to be the mail host. You should have both a DNS A record and an MX record point to this hostname.
myhostname = mail.nospam.net
  • mydomain is usually the value of myhostname, minus the first part. If your domain is wonky, then just set it manually.
mydomain = nospam.net
  • myorigin is where the email will be seen as being sent from. I usually set this to the value of mydomain. For simple servers, this works fine. This is for mail originating from a local account. Since we are not doing local delivery (except sending), then this is not really as important as it normally would be.
myorigin = $mydomain
  • mydestination is the lookup for local users.
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
  • mynetworks and mynetworks_style control relaying, and whom is allowed to. We do not want any relaying.
For our sakes, we will simply set mynetwork_style to host, as we are trying to make a standalone Postfix host, that people will use webmail on. No relaying, no other MTA's. Just webmail.
mynetworks_style = host
  • relaydomains controls the destinations that Postfix will relay TO. The default value is empty. This should be fine for now.
relay_domains =
  • home_mailbox or mail_spool_directory control how mail is delivered/stored for the users.
If set, mail_spool_directory specifies an absolute path where mail gets delivered. By default Postfix stores mails in /var/spool/mail.
mail_spool_directory = /home/vmailer
Alternatively, if set, home_mailbox specifies a mailbox relative to the user's home directory where mail gets delivered (eg: /home/vmailer).
Courier-IMAP requires "Maildir" format, so you must set it like the following example with trailing slash:
home_mailbox = Maildir/
Warning: If you plan on implementing SSL/TLS, please respond safely to FREAK/Logjam by adding the following to your configuration:
smtpd_tls_exclude_ciphers = aNULL, eNULL, EXPORT, DES, RC4, MD5, PSK, aECDH, EDH-DSS-DES-CBC3-SHA, EDH-RSA-DES-CBC3-SHA, KRB5-DES, CBC3-SHA

Then, generate a dhparam file by following these instructions and then adding the following to your configuration:

smtpd_tls_dh1024_param_file = ${config_directory}/dhparams.pem

Since mid-2015, the default settings have been safe against POODLE.

Default message and mailbox size limits

Postfix imposes both message and mailbox size limits by default. The message_size_limit controls the maximum size in bytes of a message, including envelope information. (default 10240000) The mailbox_size_limit controls the maximum size of any local individual mailbox or maildir file. This limits the size of any file that is written to upon local delivery, including files written by external commands (i.e. procmail) that are executed by the local delivery agent. (default is 51200000, set to 0 for no limit) If bounced message notifications are generated, check the size of the local mailbox under /var/spool/mail and use postconf to check these size limits:

# postconf mailbox_size_limit
mailbox_size_limit = 51200000
# postconf message_size_limit
message_size_limit = 10240000

Aliases

You can specify aliases (also known as forwarders) in /etc/postfix/aliases.

You need to map all mail addressed to root to another account since it is not a good idea to read mail as root.

Uncomment the following line, and change you to a real account.

root: you

Once you have finished editing /etc/postfix/aliases you must run the postalias command:

postalias /etc/postfix/aliases

For later changes you can use:

newaliases
Tip: Alternatively you can create the file ~/.forward, e.g. /root/.forward for root. Specify the user to whom root mail should be forwarded, e.g. user@localhost.
/root/.forward
user@localhost

Local mail

To only deliver mail to local system users (that are in /etc/passwd) update /etc/postfix/main.cf to reflect the following configuration. Uncomment, change, or add the following lines:

myhostname = localhost
mydomain = localdomain
mydestination = $myhostname, localhost.$mydomain, localhost
inet_interfaces = $myhostname, localhost
mynetworks_style = host
default_transport = error: outside mail is not deliverable

All other settings may remain unchanged. After setting up the above configuration file, you may wish to set up some #Aliases and then #Start Postfix.

Virtual mail

Virtual mail is mail that does not map to a user account (/etc/passwd).

See Virtual user mail system for a comprehensive guide how to set it up.

DNS records

An MX record should point to the mail host. Usually this is done from configuration interface of your domain provider.

A mail exchanger record (MX record) is a type of resource record in the Domain Name System that specifies a mail server responsible for accepting email messages on behalf of a recipient's domain.

When an e-mail message is sent through the Internet, the sending mail transfer agent queries the Domain Name System for MX records of each recipient's domain name. This query returns a list of host names of mail exchange servers accepting incoming mail for that domain and their preferences. The sending agent then attempts to establish an SMTP connection to one of these servers, starting with the one with the smallest preference number, delivering the message to the first server with which a connection can be made.

Note: Some mail servers will not deliver mail to you if your MX record points to a CNAME. For best results, always point an MX record to an A record definition. For more information, see e.g. Wikipedia's List of DNS Record Types.

Check configuration

Run the postfix check command. It should output anything that you might have done wrong in a config file.

To see all of your configs, type postconf. To see how you differ from the defaults, try postconf -n.

Start Postfix

Note: You must run newaliases at least once for postfix to run, even if you did not set up any #Aliases.

Start/enable the postfix.service.

Testing

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: Needs some cleanup. There are probably more general ways to write this. (Discuss in Talk:Postfix#)

Now lets see if Postfix is going to deliver mail for our test user.

nc servername 25
helo testmail.org
mail from:<test@testmail.org>
rcpt to:<cactus@virtualdomain.tld>
data
This is a test email.
.
quit

Error response

451 4.3.0 <lisi@test.com>:Temporary lookup failure

Maybe you have entered the wrong user/password for MySQL or the MySQL socket is not in the right place.

This error will also occur if you neglect to run newaliases at least once before starting postfix. MySQL is not required for local only usage of postfix.

550 5.1.1 <email@spam.me>: Recipient address rejected: User unknown in virtual mailbox table.

Double check content of mysql_virtual_mailboxes.cf and check the main.cf for mydestination

See that you have received a email

Now type $ find /home/vmailer.

You should see something like the following:

/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/tmp
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/cur
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new
/home/vmailer/virtualdomain.tld/cactus@virtualdomain.tld/new/1102974226.2704_0.bonk.testmail.org

The key is the last entry. This is an actual email, if you see that, it is working.

Extra

PostfixAdmin

To use PostfixAdmin, you need a working Apache/MySQL/PHP setup as described in Apache HTTP Server.

For IMAP functionality, you will need to install php-imap and uncomment imap.so in /etc/php/php.ini

Next, install postfixadmin.

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: in-code comments (Discuss in Talk:Postfix#)

Edit the PostfixAdmin configuration file:

/etc/webapps/postfixadmin/config.inc.php
$CONF['configured'] = true;
// correspond to dovecot maildir path /home/vmail/%d/%u 
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix_user';
$CONF['database_password'] = 'hunter2';
$CONF['database_name'] = 'postfix_db';

// globally change all instances of ''change-this-to-your.domain.tld'' 
// to an appropriate value

If installing dovecot and you changed the password scheme in dovecot (to SHA512-CRYPT for example), reflect that with postfix

/etc/webapps/postfixadmin/config.inc.php
$CONF['encrypt'] = 'dovecot:SHA512-CRYPT';

As of dovecot 2, dovecotpw has been deprecated. You will also want to ensure that your config reflects the new binary name.

/etc/webapps/postfixadmin/config.inc.php
$CONF['dovecotpw'] = "/usr/sbin/doveadm pw";

Create the Apache configuration file:

/etc/httpd/conf/extra/httpd-postfixadmin.conf
Alias /postfixadmin "/usr/share/webapps/postfixAdmin"
<Directory "/usr/share/webapps/postfixAdmin">
    DirectoryIndex index.html index.php
    AllowOverride All
    Options FollowSymlinks
    Require all granted
</Directory>

To only allow localhost access to postfixadmin (for heightened security), add this to the previous <Directory> directive:

   Order Deny,Allow
   Deny from all
   Allow from 127.0.0.1

Now, include httpd-postfixadmin.conf to /etc/httpd/conf/httpd.conf:

# PostfixAdmin configuration
Include conf/extra/httpd-postfixadmin.conf
Note: If you go to yourdomain/postfixadmin/setup.php and it says do not find config.inc.php, add /etc/webapps/postfixadmin to the open_basedir line in /etc/php/php.ini.
Note: If you get a blank page check the syntax of the file with php -l /etc/webapps/postfixadmin/config.inc.php.

Postgrey

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: See Help:Style (Discuss in Talk:Postfix#)

Postgrey can be used to enable greylisting for a Postfix mail server.

Installation

Install the postgrey package. To get it running quickly edit the Postfix configuration file and add these lines:

/etc/postfix/main.cf
smtpd_recipient_restrictions =
  check_policy_service inet:127.0.0.1:10030

Then start/enable the postgrey service. Afterwards, reload the postfix service. Now greylisting should be enabled.

Configuration

Configuration is done via editing the greylist.service file. First copy it over to edit it.

# cp /usr/lib/systemd/system/postgrey.service /etc/systemd/system/

Now you can edit it. For example, to add automatic whitelisting (successful deliveries are whitelisted and don't have to wait any more), you could add the --auto-whitelist-clients=N option and replace N by a suitably small number (or leave it at its default of 5).

...actually, the preferred method should be the override:

cat /etc/systemd/system/postgrey.service.d/override.conf
[Service]
ExecStart=
ExecStart=/usr/bin/postgrey --inet=127.0.0.1:10030 \
       --pidfile=/run/postgrey/postgrey.pid \
       --group=postgrey --user=postgrey \
       --daemonize \
       --greylist-text="Greylisted for %%s seconds" \
       --auto-whitelist-clients

Troubleshooting

If you specify --unix=/path/to/socket and the socket file is not created ensure you have removed the default --inet=127.0.0.1:10030 from the service file.

For a full documentation of possible options see perldoc postgrey.

Secure SMTP (sending)

By default, Postfix/sendmail will not send email encrypted to other SMTP servers. To use TLS when available, add the following line to main.cf:

/etc/postfix/main.cf
smtp_tls_security_level = may

To enforce TLS (and fail when the remote server does not support it), change may to encrypt.

Secure SMTP (receiving)

For more information, see Postfix TLS Support.

STARTTLS over SMTP (port 587)

To enable STARTTLS over SMTP (port 587, the proper way of securing SMTP), add the following lines to main.cf

/etc/postfix/main.cf
smtpd_tls_security_level = may
smtpd_tls_cert_file = /path/to/cert.pem
smtpd_tls_key_file = /path/to/key.pem

Also in master.cf find and remove the comment from the following line to enable the service on that port:

/etc/postfix/master.cf
submission inet n       -       n       -       -       smtpd

If you need support for the deprecated SMTPS port 465, read the next section.

SMTPS (port 465)

The deprecated method of securing SMTP is using the wrapper mode which uses the system service smtps as a non-standard service and runs on port 465.

To enable it uncomment the following lines in

/etc/postfix/master.cf
smtps     inet  n       -       n       -       -       smtpd
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes

And verify that these lines are in /etc/services:

smtps 465/tcp # Secure SMTP
smtps 465/udp # Secure SMTP

If they are not there, go ahead and add them (replace the other listing for port 465). Otherwise Postfix will not start and you will get the following error:

postfix/master[5309]: fatal: 0.0.0.0:smtps: Servname not supported for ai_socktype

SpamAssassin

Install the spamassassin package.

Go over /etc/mail/spamassassin/local.cf and configure it to your needs.

Spam Assassin rule update

Update the SpamAssassin matching patterns and compile them:

# sa-update
# sa-compile

You will want to run this periodically, the best way to do so is by setting up a Systemd/Timers.

Create the following service, which will run these commands:

/etc/systemd/system/spamassassin-update.service
[Unit]
Description=spamassassin housekeeping stuff

[Service]
#User=spamd
#Group=spamd
Type=oneshot
ExecStart=/usr/bin/vendor_perl/sa-update --allowplugins #You can remove the allowplugins options if you do not want direct plugin updates from SA.
SuccessExitStatus=0 1 #0 = updated, 1 = no updates available
ExecStart=/usr/bin/vendor_perl/sa-compile
SuccessExitStatus=0
# You can automatically train SA's bayes filter by uncommenting this line and specifying the path to a mailbox where you store email that is spam (for ex this could be yours or your users manually reported spam)
#ExecStart=/usr/bin/vendor_perl/sa-learn --spam <path to your spam>

Then create the timer, which will execute the previous service daily:

/etc/systemd/system/spamassassin-update.timer
[Unit]
Description=spamassassin house keeping

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

Finally, you'll need to modify your Spamassassin systemd service file so that it knows to restart itself to read the new rules. Copy the bundled service file to a custom service file:

# cp /usr/lib/systemd/system/spamassassin.service /etc/systemd/system

And edit the newly created /etc/systemd/system/spamassassin.service to include:

[Unit]
PartOf=spamassassin-update.service

This will ensure that Spamassassin's spamd is restarted just before the timer runs. This means the rules will be available the next day if your timer runs daily. This is so that there is no long service interruption while sa.service runs as it takes a while to compile rules.

Now you can start and enable spamassassin-update.timer.

SpamAssassin stand-alone generic setup

Note: If you want to combine SpamAssassin and Dovecot Mail Filtering, ignore the next two lines and continue further down instead.

Edit /etc/postfix/master.cf and add the content filter under smtp.

smtp      inet  n       -       n       -       -       smtpd
  -o content_filter=spamassassin

Also add the following service entry for SpamAssassin

spamassassin unix -     n       n       -       -       pipe
  flags=R user=spamd argv=/usr/bin/vendor_perl/spamc -e /usr/bin/sendmail -oi -f ${sender} ${recipient}

Now you can start and enable spamassassin.service.

SpamAssassin combined with Dovecot LDA / Sieve (Mailfiltering)

Set up LDA and the Sieve-Plugin as described in Dovecot#Sieve. But ignore the last line mailbox_command... .

Instead add a pipe in /etc/postfix/master.cf:

 dovecot   unix  -       n       n       -       -       pipe
       flags=DRhu user=vmail:vmail argv=/usr/bin/vendor_perl/spamc -u spamd -e /usr/lib/dovecot/dovecot-lda -f ${sender} -d ${recipient}

And activate it in /etc/postfix/main.cf:

 virtual_transport = dovecot

SpamAssassin combined with Dovecot LMTP / Sieve

Set up the LMTP and Sieve as described in Dovecot#Sieve.

Edit /etc/dovecot/conf.d/90-plugins.conf and add:

 sieve_before = /etc/dovecot/sieve.before.d/
 sieve_extensions = +vnd.dovecot.filter
 sieve_plugins = sieve_extprograms
 sieve_filter_bin_dir = /etc/dovecot/sieve-filter
 sieve_filter_exec_timeout = 120s #this is often needed for the long running spamassassin scans, default is otherwise 10s

Create the directory and put spamassassin in as a binary that can be ran by dovecot:

 # mkdir /etc/dovecot/sieve-filter
 # ln -s /usr/bin/vendor_perl/spamc /etc/dovecot/sieve-filter/spamc

Create a new file, /etc/dovecot/sieve.before.d/spamassassin.sieve which contains:

 require [ "vnd.dovecot.filter" ];
 filter "spamc" [ "-d", "127.0.0.1", "--no-safe-fallback" ];

Compile the sieve rules spamassassin.svbin:

 # cd /etc/dovecot/sieve.before.d
 # sievec spamassassin.sieve

Finally, restart dovecot.service.

Call ClamAV from SpamAssassin

Install and setup clamd as described in ClamAV.

Follow one of the above instructions to call SpamAssassin from within your mail system.

Install the perl-cpanplus-dist-arch package. Then install the ClamAV perl library as follows:

 # /usr/bin/vendor_perl/cpanp -i File::Scan::ClamAV
 

Add the 2 files from http://wiki.apache.org/spamassassin/ClamAVPlugin into /etc/mail/spamassassin/. Edit /etc/mail/spamassassin/clamav.pm and update $CLAM_SOCK to point to your Clamd socket location (default is /var/lib/clamav/clamd.sock).

Finally, restart spamassassin.service.

Using Razor

Make sure you have installed SpamAssassin first, then:

Install the razor package.

Register with Razor.

 # mkdir /etc/mail/spamassassin/razor
 # chown spamd:spamd /etc/mail/spamassassin/razor
 # sudo -u spamd -s
 $ cd /etc/mail/spamassassin/razor
 $ razor-admin -home=/etc/mail/spamassassin/razor -register
 $ razor-admin -home=/etc/mail/spamassassin/razor -create
 $ razor-admin -home=/etc/mail/spamassassin/razor -discover

Tell SpamAssassin about Razor, add

 razor_config /etc/mail/spamassassin/razor/razor-agent.conf

to /etc/mail/spamassassin/local.cf.

Tell Razor about itself, add

 razorhome = /etc/mail/spamassassin/razor/

to /etc/mail/spamassassin/razor/razor-agent.conf

Finally, restart spamassassin.service.

Hide the sender's IP and user agent in the Received header

This is a privacy concern mostly, if you use Thunderbird and send an email. The received header will contain your LAN and WAN IP and info about the email client you used. (Original source: AskUbuntu) What we want to do is remove the Received header from outgoing emails. This can be done by the following steps:

Add this line to main.cf

smtp_header_checks = regexp:/etc/postfix/smtp_header_checks

Create /etc/postfix/smtp_header_checks with this content:

/^Received: .*/     IGNORE
/^User-Agent: .*/   IGNORE

Finally, restart postfix.service

Postfix in a chroot jail

Postfix is not put in a chroot jail by default. The Postfix documentation [1] provides details about how to accomplish such a jail. The steps are outlined below and are based on the chroot-setup script provided in the postfix source code.

First, go into the master.cf file in the directory /etc/postfix and change all the chroot entries to 'yes' (y) except for the services qmgr, proxymap, proxywrite, local, and virtual

Second, create two functions that will help us later with copying files over into the chroot jail (see last step)

CP="cp -p"
cond_copy() {
  # find files as per pattern in $1
  # if any, copy to directory $2
  dir=`dirname "$1"`
  pat=`basename "$1"`
  lr=`find "$dir" -maxdepth 1 -name "$pat"`
  if test ! -d "$2" ; then exit 1 ; fi
  if test "x$lr" != "x" ; then $CP $1 "$2" ; fi
}

Next, make the new directories for the jail:

set -e
umask 022
POSTFIX_DIR=${POSTFIX_DIR-/var/spool/postfix}
cd ${POSTFIX_DIR}
mkdir -p etc lib usr/lib/zoneinfo
test -d /lib64 && mkdir -p lib64

Find the localtime file

lt=/etc/localtime
if test ! -f $lt ; then lt=/usr/lib/zoneinfo/localtime ; fi
if test ! -f $lt ; then lt=/usr/share/zoneinfo/localtime ; fi
if test ! -f $lt ; then echo "cannot find localtime" ; exit 1 ; fi
rm -f etc/localtime

Copy localtime and some other system files into the chroot's etc

$CP -f $lt /etc/services /etc/resolv.conf /etc/nsswitch.conf etc
$CP -f /etc/host.conf /etc/hosts /etc/passwd etc
ln -s -f /etc/localtime usr/lib/zoneinfo

Copy required libraries into the chroot using the previously created function cond_copy

cond_copy '/usr/lib/libnss_*.so*' lib
cond_copy '/usr/lib/libresolv.so*' lib
cond_copy '/usr/lib/libdb.so*' lib

And don't forget to reload postfix.

Rule-based mail processing

With policy services one can easily finetune postfix' behaviour of mail delivery. postfwd and policydAUR provide services to do so. This allows you to e.g. implement time-aware grey- and blacklisting of senders and receivers as well as SPF policy checking.

Policy services are standalone services and connected to Postfix like this:

/etc/postfix/main.cf
smtpd_recipient_restrictions =
  ...
  check_policy_service unix:/run/policyd.sock
  check_policy_service inet:127.0.0.1:10040

Placing policy services at the end of the queue reduces load, as only legitimate mails are processed. Be sure to place it before the first permit statement to catch all incoming messages.

DANE (DNSSEC)

Resource Record

Warning: This is not a trivial section. Be aware that you make sure you know what you are doing. You better read Common Mistakes before.

DANE supports several types of records, however not all of them are suitable in postfix.

Certificate usage 0 is unsupported, 1 is mapped to 3 and 2 is optional, thus it is recommendet to publish a "3" record. More on Resource Records.

Configuration

Opportunistic DANE is configured this way:

/etc/postfix/main.cf
smtpd_use_tls = yes
smtp_dns_support_level = dnssec
smtp_tls_security_level = dane
/etc/postfix/master.cf
dane       unix  -       -       n       -       -       smtp
  -o smtp_dns_support_level=dnssec
  -o smtp_tls_security_level=dane

To use per-domain policies, e.g. opportunistic DANE for example.org and mandatory DANE for example.com, use something like this:

/etc/postfix/main.cf
indexed = ${default_database_type}:${config_directory}/

# Per-destination TLS policy
#
smtp_tls_policy_maps = ${indexed}tls_policy

# default_transport = smtp, but some destinations are special:
#
transport_maps = ${indexed}transport
transport
example.com dane
example.org dane
tls_policy
example.com dane-only
Note: For global mandatory DANE, change smtp_tls_security_level to dane-only. Be aware that this makes postfix tempfail on all delivieres that do not use DANE at all!

Full documentation is found here.

See also