Virtual Users And Domains With Postfix, Courier And MySQL (Debian Etch) - Page 2

4 Create The MySQL Database For Postfix/Courier

By default, MySQL is installed without a root password, which we change immediately (replace yourrootsqlpassword with the password you want to use):

mysqladmin -u root password yourrootsqlpassword

Now we create a database called mail:

mysqladmin -u root -p create mail

Next, we go to the MySQL shell:

mysql -u root -p

On the MySQL shell, we create the user mail_admin with the passwort mail_admin_password (replace it with your own password) who has SELECT,INSERT,UPDATE,DELETE privileges on the mail database. This user will be used by Postfix and Courier to connect to the mail database:

GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost' IDENTIFIED BY 'mail_admin_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO 'mail_admin'@'localhost.localdomain' IDENTIFIED BY 'mail_admin_password';
FLUSH PRIVILEGES;

Still on the MySQL shell, we create the tables Postfix and Courier need:

USE mail;

CREATE TABLE domains (
domain varchar(50) NOT NULL,
PRIMARY KEY (domain) )
TYPE=MyISAM;

CREATE TABLE forwardings (
source varchar(80) NOT NULL,
destination TEXT NOT NULL,
PRIMARY KEY (source) )
TYPE=MyISAM;

CREATE TABLE users (
email varchar(80) NOT NULL,
password varchar(20) NOT NULL,
quota INT(10) DEFAULT '10485760',
PRIMARY KEY (email)
) TYPE=MyISAM;

CREATE TABLE transport (
domain varchar(128) NOT NULL default '',
transport varchar(128) NOT NULL default '',
UNIQUE KEY domain (domain)
) TYPE=MyISAM;

quit;

As you may have noticed, with the quit; command we have left the MySQL shell and are back on the Linux shell.

The domains table will store each virtual domain that Postfix should receive emails for (e.g. example.com).

domain
example.com

The forwardings table is for aliasing one email address to another, e.g. forward emails for info@example.com to sales@example.com.

source destination
info@example.com sales@example.com

The users table stores all virtual users (i.e. email addresses, because the email address and user name is the same) and passwords (in encrypted form!) and a quota value for each mail box (in this example the default value is 10485760 bytes which means 10MB).

email password quota
sales@example.com No9.E4skNvGa. ("secret" in encrypted form) 10485760

The transport table is optional, it is for advanced users. It allows to forward mails for single users, whole domains or all mails to another server. For example,

domain transport
example.com smtp:[1.2.3.4]

would forward all emails for example.com via the smtp protocol to the server with the IP address 1.2.3.4 (the square brackets [] mean "do not make a lookup of the MX DNS record" (which makes sense for IP addresses...). If you use a fully qualified domain name (FQDN) instead you would not use the square brackets.).

BTW, (I'm assuming that the IP address of your mail server system is 192.168.0.100) you can access phpMyAdmin over http://192.168.0.100/phpmyadmin/ in a browser and log in as mail_admin. Then you can have a look at the database. Later on you can use phpMyAdmin to administrate your mail server.

 

5 Configure Postfix

Now we have to tell Postfix where it can find all the information in the database. Therefore we have to create six text files. You will notice that I tell Postfix to connect to MySQL on the IP address 127.0.0.1 instead of localhost. This is because Postfix is running in a chroot jail and does not have access to the MySQL socket which it would try to connect if I told Postfix to use localhost. If I use 127.0.0.1 Postfix uses TCP networking to connect to MySQL which is no problem even in a chroot jail (the alternative would be to move the MySQL socket into the chroot jail which causes some other problems).

Please make sure that /etc/mysql/my.cnf contains the following line:

vi /etc/mysql/my.cnf

[...]
bind-address            = 127.0.0.1
[...]

If you had to modify /etc/mysql/my.cnf, please restart MySQL now:

/etc/init.d/mysql restart

Run

netstat -tap

to make sure that MySQL is listening on 127.0.0.1 (localhost.localdomain):

server1:/usr/src# netstat -tap
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 localhost.localdo:mysql *:*                     LISTEN     3003/mysqld
tcp        0      0 *:sunrpc                *:*                     LISTEN     1684/portmap
tcp        0      0 *:auth                  *:*                     LISTEN     2036/inetd
tcp        0      0 *:1522                  *:*                     LISTEN     2077/rpc.statd
tcp        0      0 *:smtp                  *:*                     LISTEN     12053/master
tcp6       0      0 *:imaps                 *:*                     LISTEN     3839/couriertcpd
tcp6       0      0 *:pop3s                 *:*                     LISTEN     3629/couriertcpd
tcp6       0      0 *:pop3                  *:*                     LISTEN     3572/couriertcpd
tcp6       0      0 *:imap2                 *:*                     LISTEN     3792/couriertcpd
tcp6       0      0 *:www                   *:*                     LISTEN     3712/apache2
tcp6       0      0 *:ssh                   *:*                     LISTEN     2058/sshd
tcp6       0    148 server1.example.com:ssh ::ffff:192.168.0.2:4515 ESTABLISHED2139/0

Now let's create our six text files.

vi /etc/postfix/mysql-virtual_domains.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT domain AS virtual FROM domains WHERE domain='%s'
hosts = 127.0.0.1

vi /etc/postfix/mysql-virtual_forwardings.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT destination FROM forwardings WHERE source='%s'
hosts = 127.0.0.1

vi /etc/postfix/mysql-virtual_mailboxes.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/') FROM users WHERE email='%s'
hosts = 127.0.0.1

vi /etc/postfix/mysql-virtual_email2email.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT email FROM users WHERE email='%s'
hosts = 127.0.0.1

vi /etc/postfix/mysql-virtual_transports.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT transport FROM transport WHERE domain='%s'
hosts = 127.0.0.1

vi /etc/postfix/mysql-virtual_mailbox_limit_maps.cf

user = mail_admin
password = mail_admin_password
dbname = mail
query = SELECT quota FROM users WHERE email='%s'
hosts = 127.0.0.1

Then change the permissions and the group of these files:

chmod o= /etc/postfix/mysql-virtual_*.cf
chgrp postfix /etc/postfix/mysql-virtual_*.cf

Now we create a user and group called vmail with the home directory /home/vmail. This is where all mail boxes will be stored.

groupadd -g 5000 vmail
useradd -g vmail -u 5000 vmail -d /home/vmail -m

Next we do some Postfix configuration. Go sure that you replace server1.example.com with a valid FQDN, otherwise your Postfix might not work properly!

postconf -e 'myhostname = server1.example.com'
postconf -e 'mydestination = server1.example.com, localhost, localhost.localdomain'
postconf -e 'mynetworks = 127.0.0.0/8'
postconf -e 'virtual_alias_domains ='
postconf -e 'virtual_alias_maps = proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, mysql:/etc/postfix/mysql-virtual_email2email.cf'
postconf -e 'virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf'
postconf -e 'virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf'
postconf -e 'virtual_mailbox_base = /home/vmail'
postconf -e 'virtual_uid_maps = static:5000'
postconf -e 'virtual_gid_maps = static:5000'
postconf -e 'smtpd_sasl_auth_enable = yes'
postconf -e 'broken_sasl_auth_clients = yes'
postconf -e 'smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination'
postconf -e 'smtpd_use_tls = yes'
postconf -e 'smtpd_tls_cert_file = /etc/postfix/smtpd.cert'
postconf -e 'smtpd_tls_key_file = /etc/postfix/smtpd.key'
postconf -e 'transport_maps = proxy:mysql:/etc/postfix/mysql-virtual_transports.cf'
postconf -e 'virtual_create_maildirsize = yes'
postconf -e 'virtual_maildir_extended = yes'
postconf -e 'virtual_mailbox_limit_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailbox_limit_maps.cf'
postconf -e 'virtual_mailbox_limit_override = yes'
postconf -e 'virtual_maildir_limit_message = "The user you are trying to reach is over quota."'
postconf -e 'virtual_overquota_bounce = yes'
postconf -e 'proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps'

Afterwards we create the SSL certificate that is needed for TLS:

cd /etc/postfix
openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509

<-- Enter your Country Name (e.g., "DE").
<-- Enter your State or Province Name.
<-- Enter your City.
<-- Enter your Organization Name (e.g., the name of your company).
<-- Enter your Organizational Unit Name (e.g. "IT Department").
<-- Enter the Fully Qualified Domain Name of the system (e.g. "server1.example.com").
<-- Enter your Email Address.

Then change the permissions of the smtpd.key:

chmod o= /etc/postfix/smtpd.key

Share this page:

18 Comment(s)

Add comment

Comments

From: at: 2007-06-06 20:11:22

 Hi,

 I don't understand, why you use the smtp-PAM-Module?!

 By the way: In Debian Etch you have to activate DCC in /etc/spamassassin/v310.pre

 Regards,

Hypz 

From: at: 2008-01-29 12:11:27

VERY nice howto. It worked like a dream.
And setting up Squirrelmail for this was a breeze too. 

I encountered some problems while I followed the guide though, which I have listed in my blog @ Ronin's blog[^].

 One was a bug I encountered within Courier-Saslauthdaemon, and 2 were some banal problems with Squirrelmail. But I managed to solve them with some googling around ^^

From: Juan Carlos at: 2008-12-16 17:56:05

hello as are wanting to loguiarme in mailboxes me introduce the following error:
 
Dec 16 12:43:19 linuxdeb authdaemond: stopping authdaemond children
Dec 16 12:43:19 linuxdeb authdaemond: modules="authmyslq", daemons=5
Dec 16 12:43:19 linuxdeb authdaemond: Installing libauthmyslq
Dec 16 12:43:19 linuxdeb authdaemond: libauthmyslq.so: cannot open shared object file: No such file or directory
Dec 16 12:43:46 linuxdeb courierpop3login: Connection, ip=[::ffff:127.0.0.1]
Dec 16 12:43:54 linuxdeb courierpop3login: LOGIN FAILED, user=juan, ip=[::ffff:127.0.0.1]
Dec 16 12:44:03 linuxdeb courierpop3login: LOGOUT, ip=[::ffff:127.0.0.1]
Dec 16 12:44:03 linuxdeb courierpop3login: Disconnected, ip=[::ffff:127.0.0.1]
~
 
that can be
 

From: at: 2007-06-24 18:58:29

This setup seems to be extremely insecure.

Mysql function encrypt () encrypts (on some systems, e.g. my Debian Etch) only first eight characters of a string, making hacking of a mailbox extremely easy. For example, passwords

12345678LHKuhlhKJgkZgHklu

and

12345678

both allow the user to log in (think about people who use password5468d - AOL had similar problem recently).

From: at: 2007-06-24 19:10:25

To fix the security problem I mentioned above, you may possibly use other cyphers, I found this text:

 

User question/comment: I thought MYSQL_CRYPT_PWFIELD only handles the ENCRYPT() function in stead of MD5() (see postfix-mysql setup). Correct me when I'm wrong

User question/comment: MYSQL_CRYPT_PWFIELD only specifies the name of database field,
it has nothing to do with crypt format. authlib
can automatically detect several different formats of password hash, please refer to cryptpassword.c
inside courier authlib source code for more info. Basically it checks if the first
few characters of password hash is:

  • "$1$": password is MD5 format password used by all Linux systems.
  • "{MD5}": this is followed by standard MD5 hash of password phrase.
  • "{SHA}": this is followed by standard SHA hash of password phrase.
  • "{SHA256}": this is followed by standard SHA256 hash of password phrase.
  • "{CRYPT}": this is followed by standard DES crypt() hash of password phrase.

Source:

http://postfix.wiki.xs4all.nl/index.php?title=Virtual_Users_and_Domains_with_Courier-IMAP_and_MySQL 

From: at: 2008-07-25 19:30:16

Hi

To fix this problem, just use md5-crypt passwords (as used in /etc/shadow files, starting with $1$) for your mailboxes.

This should work. If it doesn't, append "md5=true" on both lines in /etc/pam.d/smtp.

From: at: 2008-01-18 16:27:33

apt-get source postfix did not work for me.

Replaced by 'apt-src install postfix'.

 

From: Anonymous at: 2009-06-17 20:42:27

Hi,

 under debian edge there is a bug in clamav so that it produces 100% cpu load and can´t open a unix socket.

Like this: 

connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory

You have to update the clamav to solve this problem. Add folowing package sources in sources.list

deb http://volatile.debian.org/debian-volatile etch/volatile main

 then do: apt-get update

and install the packages: 

clamav-daemon
clamav-freshclam
clamav-base
clamav

then it sould work.

Good Luck

 Kruser

From: at: 2008-01-26 16:54:35

Hi,

Great Howto, thank you very much for your work.

Just a comment: you don't need to set sql parameters and mysql as auxprop_plugin in /etc/postfix/sasl/smtpd.conf as you intend to use PAM for authentication.

The following /etc/postfix/sasl/smtpd.conf should suffice:

pwcheck_method: saslauthd
mech_list: plain login
allow_plaintext: true

This way, plain PAM will be used, with the options you set in /etc/pam.d/smtpd. Indeed, you don't even need to install libsasl2-modules-sql package (but you still do need libpam-mysql, of course).

Best regards,

Alberto Caso
Adaptia

From: at: 2007-06-05 19:31:53

Hi,

 why do you add this SMTP-PAM-Module? I don't see any sense in this.

By the way: In Debian Etch you have to enable DCC in /etc/spamassassin/v310.pre

Regards,

Hypz 

From: at: 2007-07-11 21:17:01

Hi, first ov all thanks for the tut.

In etch you also have to activate spamassasin in /etc/default/spamassasin "ENABLE = 1"

Also I found this in the Fedora tut. about the paths ( it worked for me on etch ):

the dcc_path to the socket is (as I followed exacly the way of installing as described in this tut):

/var/lib/dcc/dccifd

* dcc_add_header and  pyzor_add_header are deprecated (Cf. http://spamassassin.apache.org/full/2.6x/dist/doc/Mail_SpamAssassin_Conf.txt), instead use respectively add_header all DCC _DCCB_: _DCCR_ and add_header all Pyzor _PYZOR_

 * to make amavis keep a part of the spamassassin header, add the following lines to your amavisd.conf :

$remove_existing_spam_headers = 0;

$sa_spam_report_header = 1;

Please correct me if I'm wrong. But it looks like this how it worked for me.

Greets Josh 

 

From: at: 2007-07-20 18:32:01

You are wrong, spamd is typically not used along with amavisd-new. amavisd-new calls spamassassin directly via Perl module Mail::SpamAssassin. So, I suggest leaving the default of "ENABLE = 0" in /etc/default/spamassasin.

From: Tim at: 2009-06-14 22:17:31

I was able to make this run in lenny with some light modifications, no DCC (debian boycotted it in lenny), etc.

Everything works nicely, but spamassassin, razor and pyzor do not print any headers in the e-mail, when "$sa_tag_level_deflt = undef;".

On the amavis startup logging, it does show razor2 being loaded, but not pyzor, while both are installed (did not configuration though).

Amavis is logging to mail.log whether the message is spam or not, and the X-Virus-Scanned shows, but no spamassassin, razor (and pyzor, but it won't even load) headers. Should I just install the perl package for spamassassin? I currently have the "spamassasin" lenny deb installed.

 

"$QUARANTINEDIR = "$MYHOME/virusmails";
$quarantine_subdir_levels = 1; # enable quarantine dir hashing

$log_recip_templ = undef;    # disable by-recipient level-0 log entries
$DO_SYSLOG = 1;              # log via syslogd (preferred)
$syslog_ident = 'amavis';    # syslog ident tag, prepended to all messages
$syslog_facility = 'mail';
$syslog_priority = 'debug';  # switch to info to drop debug output, etc

$enable_db = 1;              # enable use of BerkeleyDB/libdb (SNMP and nanny)
$enable_global_cache = 1;    # enable use of libdb-based cache if $enable_db=1

$inet_socket_port = 10024;   # default listening socket

$sa_spam_subject_tag = '***SPAM*** ';
$sa_tag_level_deflt = undef;   # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 4.00;   # add 'spam detected' headers at that level
$sa_kill_level_deflt = 6.31;   # triggers spam evasive actions
$sa_dsn_cutoff_level = 10;     # spam level beyond which a DSN is not sent
"

Thanks!

Tim

From: at: 2008-02-17 22:56:39

I got this error in /var/log/mail.log
Can't connect to UNIX socket /var/run/clamav/clamd.ctl: No such file or directory

Sollution -> http://blog.brachium-system.net/categories/7-virus

From: at: 2010-08-21 19:37:35

Hi i folowed this guide and the server has worked well for over a year but now clamd uses up 100% of my cpu.

 

From: at: 2007-06-10 11:51:45

Thanks for this tutorial!

Whats with automatic custom rulesets updates for SpamAssassin?

=> http://www.howtoforge.com/virtual_postfix_mysql_quota_courier_p4

 Nico

From: at: 2008-05-27 15:32:58

You need to use clamav from Debian's volatile repository, otherwise this won't work at all.

On more thing, if you create new email account, and than try to fetch mail for it and fail miserably, than send an email to it, and then try again.

Good tutorial. Thanks ;) 

From: Bruno Taranto Alvim at: 2008-09-30 23:30:19

Change 2 files (mysql-virtual_mailboxes.cf and authmysqlrc) to Maildir work.

mail:/etc/postfix# more mysql-virtual_mailboxes.cf

user = postfix password = postfix dbname = postfix query = SELECT CONCAT(SUBSTRING_INDEX(email,'@',-1),'/','',SUBSTRING_INDEX(email,'@',1),'/','Maildir/') FROM users WHERE email='%s' hosts = 127.0.0.1

mail:/etc/courier# more authmysqlrc

MYSQL_SERVER localhost MYSQL_USERNAME postfix MYSQL_PASSWORD postfix MYSQL_PORT 0 MYSQL_DATABASE postfix MYSQL_USER_TABLE users MYSQL_CRYPT_PWFIELD password #MYSQL_CLEAR_PWFIELD password MYSQL_UID_FIELD 5000 MYSQL_GID_FIELD 5000 MYSQL_LOGIN_FIELD email MYSQL_HOME_FIELD "/home/vmail" MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,'@',-1),'/','',SUBSTRING_INDEX(email,'@',1),'/','Maildir/') #MYSQL_NAME_FIELD MYSQL_QUOTA_FIELD quota

Now you can receive and get!