setting mail server debian

27
setting mail server debian 5 Howto: Installasi mailserver dengan postfix and courier menggunakan authentikasi mysql Tutorial ini menjelaskan Step by Step tentang cara membuat mailserver dg virtual domain (domain email tidak harus selalu sama dg domain komputer yang sesungguhnya) denganberbasiskan postfix dan courier dg memanfaatkan mysql sebagai penyimpan data username & password bagi tiap2 user. Berikut ini yang harus anda lakukan. ( INTERNET )—————-| DMZ |—————-( Local Area Networks ) Step 1: Install paket-paket yang diperlukan Paket yang diperlukan dalam tutorial ini antara lain : Untuk Mengirim email (SMTP) : postfix (Pilih: “Local only”), postfix-tls, postfix-mysql, postfix-doc Untuk Database user : mysql-client-5.0, mysql-server-5.0 Untuk menerima email (POP3 & IMAP) : courier-base (Pilih: “No”), courier-authdaemon, courier-authlib-mysql, courier-pop, courier-pop-ssl, courier-imap, courier-imap-ssl Untuk Keamanan Pengiriman dan Penerimaan email : libsasl2, libsasl2-modules, libsasl2-modules-sql, openssl Untuk Mencegah Virus dan Spam : amavisd-new, spamassassin, clamav, clamav-daemon, zoo, unzip, lha Untuk tampilan WebMail : squirrelmail, phpmyadmin Untuk testing tools : telnet sakarotul:~# apt-get install postfix postfix-tls postfix-mysql postfix-doc mysql-client-5.0 mysql-server-5.0 courier- authdaemon courier-authlib-mysql courier-pop courier-pop-ssl courier-imap courier-imap-ssl libsasl2 libsasl2-modules libsasl2-modules-sql openssl amavisd-new spamassassin clamav clamav-daemon zoo unzip lha squirrelmail phpmyadmin telnet Step 2: Membuat user, database, dan tabel yang diperlukan pada mysql Tambahkan database dan tabel-tabel baru pada mysql anda sebagai berikut sakarotul:~# mysql -u root -p password: mysql>CREATE DATABASE mail;

Transcript of setting mail server debian

Page 1: setting mail server debian

setting mail server debian   5

Howto: Installasi mailserver dengan postfix and courier menggunakan authentikasi mysql

Tutorial ini menjelaskan Step by Step tentang cara membuat mailserver dg virtual domain (domain email tidak harus selalu sama dg domain komputer yang sesungguhnya) denganberbasiskan postfix dan courier dg memanfaatkan mysql sebagai penyimpan data username & password bagi tiap2 user. Berikut ini yang harus anda lakukan.

( INTERNET )—————-| DMZ |—————-( Local Area Networks )

Step 1: Install paket-paket yang diperlukan

Paket yang diperlukan dalam tutorial ini antara lain :Untuk Mengirim email (SMTP) : postfix (Pilih: “Local only”), postfix-tls, postfix-mysql, postfix-docUntuk Database user : mysql-client-5.0, mysql-server-5.0Untuk menerima email (POP3 & IMAP) : courier-base (Pilih: “No”), courier-authdaemon, courier-authlib-mysql, courier-pop, courier-pop-ssl, courier-imap, courier-imap-sslUntuk Keamanan Pengiriman dan Penerimaan email : libsasl2, libsasl2-modules, libsasl2-modules-sql, opensslUntuk Mencegah Virus dan Spam : amavisd-new, spamassassin, clamav, clamav-daemon, zoo, unzip, lhaUntuk tampilan WebMail : squirrelmail, phpmyadminUntuk testing tools : telnetsakarotul:~# apt-get install postfix postfix-tls postfix-mysql postfix-doc mysql-client-5.0 mysql-server-5.0 courier-authdaemon courier-authlib-mysql courier-pop courier-pop-ssl courier-imap courier-imap-ssl libsasl2 libsasl2-modules libsasl2-modules-sql openssl amavisd-new spamassassin clamav clamav-daemon zoo unzip lha squirrelmail phpmyadmin telnet

Step 2: Membuat user, database, dan tabel yang diperlukan pada mysqlTambahkan database dan tabel-tabel baru pada mysql anda sebagai berikutsakarotul:~# mysql -u root -ppassword:mysql>CREATE DATABASE mail;mysql>CREATE USER ‘mailadmin’@’localhost’ identified by ‘passwordanda’;mysql>USE mail;mysql>CREATE TABLE domains (domain varchar(50) NOT NULL,PRIMARY KEY (domain) )TYPE=MyISAM;mysql>CREATE TABLE forwardings (source varchar(80) NOT NULL,destination TEXT NOT NULL,PRIMARY KEY (source) )TYPE=MyISAM;mysql>CREATE TABLE users (email varchar(80) NOT NULL,

Page 2: setting mail server debian

password varchar(20) NOT NULL,PRIMARY KEY (email) )TYPE=MyISAM;mysql>GRANT all ON mail.* TO ‘mailadmin’@’localhost’;

Step 3: Membuat file2 baru sebagai penunjuk ke database mysqlBuat file baru dg nama mysql-virtual_domains.cf :sakarotul:~# touch /etc/postfix/mysql-virtual_domains.cfisi file mysql-virtual_domains.cf dg baris-baris dibawah ini :sakarotul:~# mcedit /etc/postfix/mysql-virtual_domains.cfuser = mailadminpassword = passwordandadbname = mailtable = domainsselect_field = ‘virtual’where_field = domainhosts = 127.0.0.1Buat file baru dg nama mysql-virtual_forwardings.cf yg berisi :sakarotul:~# touch /etc/postfix/mysql-virtual_forwardings.cfisi file mysql-virtual_forwardings.cf dg baris-baris dibawah ini :sakarotul:~# mcedit /etc/postfix/mysql-virtual_forwardings.cfuser = mailadminpassword = passwordandadbname = mailtable = forwardingsselect_field = destinationwhere_field = sourcehosts = 127.0.0.1Buat file baru dg nama user mysql-virtual_mailboxes.cf yg berisi :sakarotul:~# touch /etc/postfix/mysql-virtual_mailboxes.cfisi file mysql-virtual_mailboxes.cf dg baris-baris dibawah ini :sakarotul:~# mcedit /etc/postfix/mysql-virtual_mailboxes.cfuser = mailadminpassword = passwordandadbname = mailtable = usersselect_field = CONCAT(SUBSTRING_INDEX(email,’@’,-1),’/’,SUBSTRING_INDEX(email,’@’,1),’/’)where_field = emailhosts = 127.0.0.1Buat file baru mysql-virtual_email2email.cf yang berisi :sakarotul:~# touch /etc/postfix/mysql-virtual_email2email.cfisi file mysql-virtual_email2email.cf dg baris-baris dibawah ini :sakarotul:~# mcedit /etc/postfix/mysql-virtual_email2email.cfuser = mailadminpassword = passwordandadbname = mailtable = usersselect_field = emailwhere_field = email

Page 3: setting mail server debian

hosts = 127.0.0.1[Penting] Demi keamanan, pastikan hanya user root & postfix saja yang bisa mengakses file-file yang telah anda buat.sakarotul:~# chown root:postfix /etc/postfix/mysql-virtual_*.cfsakarotu;:~# chmod u=rw,g=r,o= /etc/postfix/mysql-virtual_*.cf

Step 4: Membuat user baru pada system kita sebagai administrator-emailUser ini bertugas untuk membuat maildir baru setiap ada user baru yang mendaftar pada mailserver andasakarotul:~# groupadd -g 5000 mail-adminsakarotul:~# useradd -g mail-admin -u 5000 mail-admin -d /home/mail -msakarotul:~# mkdir /home/mailsakarotul:~# chown -R mail-admin:mail-admin /home/mailsakarotul:~# chmod -R u=rwx,g=,o= /home/mail

Step 5: Mengkonfigurasi postfix sbg server SMTPFile main.cf ini adalah file konfigurasi utama dari postfixsakarotul:~# mcedit /etc/postfix/main.cfEditlah file tsb, sehingga menjadi seperti dibawah ini :inet_interfaces = allmyhostname = mail.domain-anda.org (fqdn)mydestination = (jangan menuliskan virtual domain disini -> lebih baik dikosongi saja)mynetworks = lqman.org (nama domain anda)virtual_alias_domains =virtual_alias_maps = mysql:/etc/postfix/mysql-virtual_forwardings.cf mysql:/etc/postfix/mysql-virtual_email2email.cfvirtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual_domains.cfvirtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual_mailboxes.cfvirtual_mailbox_base = /home/mailvirtual_uid_maps = static:5000virtual_gid_maps = static:5000smtpd_sasl_auth_enable = yesbroken_sasl_auth_clients = yessmtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destinationsmtpd_use_tls = yessmtpd_tls_cert_file = /etc/postfix/smtpd.certsmtpd_tls_key_file = /etc/postfix/smtpd.key

Testing…Restart service postfix, dan cobalah untuk mengakses port 25 dengan telnetsakarotul:~# /etc/init.d/postfix restartsakarotul:~# postfix checkJika tidak muncul suatu pesan kesalahan, berarti anda sukses…….sakarotul:~# telnet localhost 25Trying 127.0.0.1…Connected to localhost.localdomain.Escape character is ‘^]’.220 mail.lqman.org ESMTP Postfix (Debian/GNU)

Page 4: setting mail server debian

Jika muncul sebagaimana tulisan diatas, berarti postfix anda sudah berjalan lancar…Tekanlah tombol Ctrl+] lalu ketik quit untuk keluar dari sesi telnet,Ambilah napas dalam-dalam, dan lanjutkan perjuangan

Step 6: Mengaktifkan fasilitas authentikasi pada postfix (Auth-SMTP)Tell Postfix to use SASL/MySQL, dg cara buat file baru dg nama /etc/postfix/sasl/smtpd.conf :sakarotul:~# touch /etc/postfix/sasl/smtpd.confIsi file /etc/postfix/sasl/smtpd.conf dg baris-baris dibawah ini :sakarotul:~# mcedit /etc/postfix/sasl/smtpd.confpwcheck_method: auxpropauxprop_plugin: sqlmech_list: plain login cram-md5 digest-md5sql_engine: mysqlsql_hostnames: 127.0.0.1sql_user: mailadminsql_passwd: passwordandasql_database: mailsql_select: select password from users where email=’%u@%r’log_level: 7[Penting] Demi keamanan, pastikan hanya user root & postfix saja yang bisa mengakses file-file yang telah anda buat.sakarotul:~# chown root:postfix /etc/postfix/sasl/smtpd.confsakarotul:~# chmod u=rw,g=r,o= /etc/postfix/sasl/smtpd.conf

Mengaktifkan TLS untuk meng-encrypt SMTP traffik, dg cara membuat sertifikat (certificate)root@bajoel:~# openssl req -new -outform PEM -out /etc/postfix/smtpd.cert -newkey rsa:2048 -nodes -keyout /etc/postfix/smtpd.key -keyform PEM -days 365 -x509[Penting] Demi keamanan, pastikan hanya user root & postfix saja yang bisa mengakses file-file yang telah anda buat.sakarotul:~# chown root:postfix /etc/postfix/smtpd.*sakarotul:~# chmod u=rw,g=r,o= /etc/postfix/smtpd.*

Step 7: Mengkonfigurasi courier sebagai server POP3 / IMAPEdit file /etc/courier/authdaemonrc :sakarotul:~# mcedit /etc/courier/authdaemonrcUbah parameter authmodulelist menjadi :authmodulelist=”authmysql”Lalu edit file /etc/courier/authmysqlrc :sakarotul:~# mcedit /etc/courier/authmysqlrcUbah beberapa parameter, shg menjadi seperti di bawah ini :MYSQL_SERVER localhostMYSQL_USERNAME mailadminMYSQL_PASSWORD passwordandaMYSQL_PORT 0MYSQL_DATABASE mailMYSQL_USER_TABLE users#MYSQL_CRYPT_PWFIELD (jadikan baris ini sebagai komentar)MYSQL_CLEAR_PWFIELD password

Page 5: setting mail server debian

MYSQL_UID_FIELD 5000MYSQL_GID_FIELD 5000MYSQL_LOGIN_FIELD emailMYSQL_HOME_FIELD “/home/mail”MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,’@’,-1),’/’,SUBSTRING_INDEX(email,’@’,1),’/’)#MYSQL_NAME_FIELD (jadikan baris ini sebagai komentar)[Penting] Mengedit file authmysqlrc agak sedikit susah, pastikan anda berhati-hati dan tidak membuat kesalahan (jangan memakai tanda SPASI, tetapi gunakan tombol TAB)Testing…Restart service courier-authdaemon, dan cobalah untuk mengakses port 110 dengan telnetsakarotul:~# /etc/init.d/courier-authdaemon restartJika tidak muncul suatu pesan kesalahan, berarti anda sukses…sakarotul:~# telnet localhost 110Trying 127.0.0.1…Connected to localhost.Escape character is ‘^]’.+OK Hello there.

Jika muncul pesan seperti diatas, maka berbahagialah.Tarik napas dalam-dalam dan ucapkan hamdalah atas keberhasilan anda[Penting] Anda tidak dapat membuka mailbox / maildir anda sebelum ada email yang terkirim pada mailbox anda. Pesan kesalahan akan dimunculkan. Karena itulah anda harus mengirim welcome email pada setiap user baru.

Step 8: Test hasil konfigurasi andaSelamat, anda telah menyelesaikan poin konfigurasi. Pada bagian ini anda anda hanya akan men-testing server yang telah anda konfig sebelumnya.Sekarang kita akan membuat database pada domain yang akan kita coba, domain inilah yang kita jadikan sebagai domain percobaan untuk mengirim dan menerima email.Buatlah domain baru dg nama lqman.org pada tabel domains, dan buatlah juga alamat email dan password baru pada tabel users.Untuk lebih jelasnya ikutilah syntax mysql dibawah ini.sakarotul:~# mysql -u mailadmin -p mailpassword:mysql>INSERT INTO domains(domain) VALUES (’lqman.org’);mysql>INSERT INTO users(email,password) VALUES (’[email protected]’,’admin’);mysql>INSERT INTO users(email,password) VALUES (’[email protected]’,’user’);Sekarang kita sudah punya sebuah virtual domain baru dg nama “lqman.org” dan 2 orang user, yaitu “[email protected]” dan “[email protected]” yang masing-masing user ini mempunyai password “admin” dan “user”.Jika anda tidak mempunyai MX record pada DNS server anda, maka kami menyarankan utk menambahkan MX record spt dibawah ini :sakarotul:~# mcedit /etc/bind/db.lqman.org

@ IN MX 5 mail.lqman.org.mail IN A 10.122.1.22

IP-Address 10.122.1.22 hanya sebagai contoh saja, ubahlah sesuai dg IP-Address yg anda inginkan. Kemudian untuk mencoba pengiriman email dari smtp server anda, lakukan telnet

Page 6: setting mail server debian

pada localhost 25sakarotul:~# telnet localhost 25Trying 127.0.0.1…Connected to localhost.localdomain.Escape character is ‘^]’.220 mail.lqman.org ESMTP Postfix (Debian/GNU)

Kemudian secara interaktif (pada mode telnet) berikan perintah spt dibawah ini :Anda : ehlo virtual.testServer : 250-mailtest250-PIPELINING250-SIZE 10240000250-VRFY250-ETRN250-STARTTLS250-AUTH LOGIN PLAIN DIGEST-MD5 CRAM-MD5250-AUTH=LOGIN PLAIN DIGEST-MD5 CRAM-MD5250 8BITMIMEAnda : mail from:[email protected] : 250 OkAnda : rcpt to:[email protected] : 250 OkAnda : dataServer : 354 End data with .Anda : Subject:Just for testThis is a test email. (tanda titik)Server : 250 Ok: queued as ABC1D1C123Anda : quitServer : 221 BYE

Jika respon server seperti tulisan diatas, berarti email dari [email protected] kepada [email protected] sudah masuk ke dalam antrian untuk segera dikirimkan oleh postfix (SMTP server).Lihatlah pada log file yang berada pada /var/log/mail.info :sakarotul:~# tail -f /var/log/mail/info | cczePasti akan kita lihat bagin seperti dibawah ini :Jul 24 21:48:28 myserver postfix/smtpd[9119]: connect from myserver[127.0.0.1]Jul 24 21:48:48 myserver postfix/smtpd[9119]: F2C1B47BD: client=myserver[127.0.0.1]Jul 24 21:48:52 myserver postfix/cleanup[9144]: F2C1B47BD: message-id=Jul 24 21:48:52 myserver postfix/qmgr[9117]: F2C1B47BD: from=, size=313, nrcpt=1 (queue active)Jul 24 21:48:52 myserver postfix/virtual[9148]: F2C1B47BD: to=, relay=virtual, delay=10, status=sent (delivered to maildir)Jika anda melihat “status=sent (delivered to maildir)” maka email yang anda kirimkan sudah berhasil dikirimkan ke dalam Maildir user yang bersangkutan ([email protected]). Jalankan perintah find untuk melihat seluruh file dan direktori yang ada dibawah direktori “/home/mail”.sakarotul:~# find /home/mail/home/mail/

Page 7: setting mail server debian

/home/mail/lqman.org/home/mail/lqman.org/user/home/mail/lqman.org/user/cur/home/mail/lqman.org/user/new/home/mail/lqman.org/user/new/1170803794.V805I1c1fbM98807.bajoel/home/mail/lqman.org/user/new/1170803833.V805I1c1feM87660.bajoel/home/mail/lqman.org/user/tmpSemuanya berjalan Lancar? Bagus.. Sebagai langkah terakhir, anda harus mencoba login pada email baru nada melalui tampilan web yg telah disediakan oleh squirrelmail. Pada percobaan ini, username yang bisa digunakan adalah “[email protected]” dengan password “user”

Step 9: Menambahkan User Baru pada Mail-ServerPada step yang terakhir ini anda tinggal memasukkan / menambahkan pada database setiap username dan password user baru pada mailserver anda.Untuk setiap virtual-domain baru, Tambahkan nama virtual-domain tsb pada tabel ‘domains’Untuk setiap user baru, Tambahkan username (email address) dan password (plain text) pada tabel ‘users’Untuk setiap forwarding, Tambahkan source dan destination mail address pada tabel ‘forwardings’, jika anda punya banyak destination, pisahkan dengan koma. Tabel ini digunakan untuk me-redirect setiap email pada system anda, termasuk juga anda bisa me-redirect local mail-address.Contoh :source destination [email protected] [email protected] me-redirect emails untuk postmaster kepada [email protected] @another.domain Ini adalah re-direction thd seluruh domain. Setiap email yang dialamatkan kpd suatu user pada domain ‘my.domain’ akan di-forward kepada user yang sama pada domain ‘another.domain’.Jadi mail kpd [email protected] akan di-redirect kepada [email protected]@my.domain [email protected],[email protected] mem-forward email yg dialamatkan untuk [email protected] [email protected] dan [email protected]

Step 10: Interface WebMail dg squirrelmailUntuk mempermudah user anda dalam menggunakan mailserver yg sdh anda buat, maka tampilan web merupakan interface yang paling mudah.Oleh karena itu paket squirrelmail yang sudah kita install pada step pertama harus dikonfigurasi sesuai dg mailserver yg sdh kita buat.Untuk menyesuaikan dg konfigurasi mailserver ini, cukup lakukan perintah squirrelmail-configure :sakarotul:~# squirrelmail-configurelalu lakukan sesuai dg langkah-langkah yang sudah tersedia. Langkah yang paling penting disini adalah saat menentukan “Server Settings” saja, selain itu tidak ada yang terlalu penting.Pada saat menentukan “Server Settings”, lakukan perubahan spt dibawah ini

Secure IMAP (TLS) : falseServer software : courier

Kemudian save opsi tersebut dg cara menekan tombol “s”, lalu keluar dari configurasi dg menekan tombol “q”.

Page 8: setting mail server debian

Step 11: Menjadikan webmail kita sebagai VirtualHost baruBuatlah file baru pada konfigurasi webserver anda (pada tutorial ini dipakai webserver apache2)sakarotul:~# touch /etc/apache2/sites/available/squirrelmailKemudian tambahkan baris-baris dibawah ini :NameVirtualHost 10.122.1.22:80ServerAdmin [email protected] mail.lqman.orgDocumentRoot /usr/share/squirrelmailOptions FollowSymLinksAllowOverride NoneOptions Indexes FollowSymLinks MultiViewsAllowOverride NoneOrder allow,denyallow from allSetelah itu, buatlah symbolic link ke direktori /etc/apache2/sites-enable/ dengan cara :sakarotul:~# ln -s /etc/apache2/sites-available/squirrelmail.conf /etc/apache/sites-enable/001squirrelmail.confLalu cek konfigurasi apache2 dg syntax :sakarotul:~# apache2ctl configtestdan jika muncul tulisan Syntax OK, maka restart-lah apache2 dg :sakarotul:~# apache2ctl restart

Page 9: setting mail server debian

Postfix and Courier Installation using MySQL

Page Discussion View source History

Contents

[hide]

1 Introduction 2 Requirements 3 Pre-Installation 4 Install Postfix, Courier and Saslauthd 5 Apply Quota Patch To Postfix 6 Prevent APT from upgrading Postfix 7 Create The MySQL Database For Postfix/Courier

o 7.1 MySQL Database Structure 8 Configure Postfix 9 Configure Saslauthd 10 Configure Courier 11 Quota Notifications 12 Testing Postfix 13 Adding to the Database

o 13.1 Forwarding Options o 13.2 Transport Options

14 References

Introduction

This HOWTO describes how to install a mail server, using Postfix, that is based on virtual users and domains - i.e. users and domains that are stored in a MySQL database. We'll also cover the installation and configuration of Courier (Courier-POP3, Courier-IMAP), so that Courier can authenticate against the same MySQL database that Postfix uses.

The resulting Postfix server is capable of SMTP-AUTH and quota. Quota is not built into Postfix but we'll patch your Postfix appropriately and prevent apt from upgrading and breaking Postfix in the future. Passwords are stored in encrypted form in the database.

This HOWTO is meant as a practical guide which I used to setup my own system. It does not cover the theoretical backgrounds as they are treated in a lot of other documents available on the web.

Requirements

A Debian Etch base installation - Installation HOWTO here. A working version of MySQL, phpMyAdmin and PHP - Installation HOWTO here.

Page 10: setting mail server debian

Root access to your server.

Pre-Installation

Before proceeding to install, update the necessary packages in Debian with these commands.

apt-get updateapt-get upgrade

Install Postfix, Courier and Saslauthd

Installing Postfix, Courier and Saslauthd is as easy as running this one simple command:

apt-get install postfix postfix-mysql postfix-doc courier-authdaemon courier-authlib-mysql courier-pop courier-pop-sslcourier-imap courier-imap-ssl libsasl2 libsasl2-modules libsasl2-modules-sql sasl2-bin libpam-mysql openssl

Ensure that the above command is run in one line (i.e. don't break it up)!

You will be asked a few questions:

General type of configuration? <-- Internet siteWhere should mail for root go? <-- NONEMail name? <-- server1.example.com (replace according to your server)Other destinations to accept mail for? (blank for none) <-- server1.example.com, localhost, localhost.localdomainForce synchronous updates on mail queue? <-- NoSSL certificate required <-- Ok

Apply Quota Patch To Postfix

Falko Timme's original documentation was a little outdated for Debian Etch and my initial trials didn't work. I've managed to figure out how to patch Postfix 2.3.4-3 as follows.

We have to get the Postfix sources, patch it with the quota patch, build new Postfix .deb packages and install those .deb packages:

apt-get install build-essential dpkg-dev fakeroot debhelper libdb4.2-dev libgdbm-dev libldap2-dev libpcre3-dev libmysqlclient15-dev libssl-dev libsasl2-dev postgresql-dev po-debconf dpatch

NB: Run the above command in one line i.e. don't break it up.

cd /usr/srcapt-get source postfixwget http://vda.sourceforge.net/VDA/postfix-2.3.4-vda.patch.gzgunzip postfix-2.3.4-vda.patch.gzcd postfix-2.3.4patch -p1 < ../postfix-2.3.4-vda.patch.gzdpkg-buildpackagecd ..dpkg -i postfix_2.3.4-3_i386.deb

Page 11: setting mail server debian

dpkg -i postfix-mysql_2.3.4-3_i386.deb

Prevent APT from upgrading Postfix

I like to keep my system up to date however patching Postfix requires us to prevent apt from trying to upgrade Postfix and in turn break our installation. Here's what I did:

vim /etc/apt/preferences

Add the following to this new file:

Package: postfixPin: version 2.3.4Pin-Priority: 1001

Package: postfix-mysqlPin: version 2.3.4Pin-Priority: 1001

Package: postfix-devPin: version 2.3.4Pin-Priority: 1001

Save this new file and run the following:

apt-get updateapt-get upgrade

If all went well you should see the following output:

The following packages have been kept back: postfix postfix-dev postfix-mysql0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.

Create The MySQL Database For Postfix/Courier

Let's create a database for Postfix and Courier called mail:

mysqladmin -u root -p create mail

Next, we go to the MySQL shell:

mysql -u root -p

In 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 and 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';

Page 12: setting mail server debian

FLUSH PRIVILEGES;

Still in the MySQL shell, we create the tables that 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;

MySQL Database Structure

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 [email protected] to [email protected].

source destination

[email protected] [email protected]

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

Page 13: setting mail server debian

[email protected] No9.E4skNvGa. 10485760

The transport table is optional and is for advanced users. It allows us 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.).

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:

bind-address = 127.0.0.1

so that MySQL allows connections on 127.0.0.1 (restart MySQL if you have to make changes to /etc/mysql/my.cnf).

Now let's create our six text files.

/etc/postfix/mysql-virtual_domains.cf

user = mail_adminpassword = mail_admin_passworddbname = mailtable = domainsselect_field = 'virtual'where_field = domainhosts = 127.0.0.1

/etc/postfix/mysql-virtual_forwardings.cf

user = mail_adminpassword = mail_admin_passworddbname = mail

Page 14: setting mail server debian

table = forwardingsselect_field = destinationwhere_field = sourcehosts = 127.0.0.1

/etc/postfix/mysql-virtual_mailboxes.cf

user = mail_adminpassword = mail_admin_passworddbname = mailtable = usersselect_field = CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/')where_field = emailhosts = 127.0.0.1

/etc/postfix/mysql-virtual_email2email.cf

user = mail_adminpassword = mail_admin_passworddbname = mailtable = usersselect_field = emailwhere_field = emailhosts = 127.0.0.1

/etc/postfix/mysql-virtual_transports.cf

user = mail_adminpassword = mail_admin_passworddbname = mailtable = transportselect_field = transportwhere_field = domainhosts = 127.0.0.1

/etc/postfix/mysql-virtual_mailbox_limit_maps.cf

user = mail_adminpassword = mail_admin_passworddbname = mailtable = usersselect_field = quotawhere_field = emailhosts = 127.0.0.1

Next run the following commands:

chmod o= /etc/postfix/mysql-virtual_*.cfchgrp 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 vmailuseradd -g vmail -u 5000 vmail -d /home/vmail -m

Page 15: setting mail server debian

Next we do some Postfix configuration. Ensure that you replace server1.example.com below with your own server name otherwise Postfix will 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_mailbox_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'

Configure Saslauthd

mkdir -p /var/spool/postfix/var/run/saslauthd

Edit /etc/default/saslauthd. Remove the # in front of START=yes and add the line PARAMS="-m /var/spool/postfix/var/run/saslauthd -r". The file should then look like this:

# This needs to be uncommented before saslauthd will be run automatically START=yes

# You must specify the authentication mechanisms you wish to use.# This defaults to "pam" for PAM support, but may also include# "shadow" or "sasldb", like this:# MECHANISMS="pam shadow"

MECHANISMS="pam"PARAMS="-m /var/spool/postfix/var/run/saslauthd -r"

Page 16: setting mail server debian

We must also edit /etc/init.d/saslauthd and change the location of saslauthd's PID file. Change the value of PIDFILE to /var/spool/postfix/var/run/${NAME}/saslauthd.pid:

PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"

Then create the file /etc/pam.d/smtp. It should contain only the following two lines (be sure to fill in your correct database details):

auth required pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=email passwdcolumn=password crypt=1account sufficient pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=email passwdcolumn=password crypt=1

Next create the file /etc/postfix/sasl/smtpd.conf remembering to replace the mysql password with your own. It should look like this:

pwcheck_method: saslauthdmech_list: plain loginallow_plaintext: trueauxprop_plugin: mysqlsql_hostnames: 127.0.0.1sql_user: mail_adminsql_passwd: mail_admin_passwordsql_database: mailsql_select: select password from users where email = '%u'

Then restart Postfix and Saslauthd:

/etc/init.d/postfix restartpostfix check/etc/init.d/saslauthd restart

Configure Courier

Now we have to tell Courier that it should authenticate against our MySQL database. First, edit /etc/courier/authdaemonrc and change the value of authmodulelist so that it reads:

authmodulelist="authmysql"

Then edit /etc/courier/authmysqlrc. It should look like this (again, make sure to fill in the correct database details):

MYSQL_SERVER localhostMYSQL_USERNAME mail_adminMYSQL_PASSWORD mail_admin_passwordMYSQL_PORT 0MYSQL_DATABASE mailMYSQL_USER_TABLE usersMYSQL_CRYPT_PWFIELD password#MYSQL_CLEAR_PWFIELD passwordMYSQL_UID_FIELD 5000MYSQL_GID_FIELD 5000MYSQL_LOGIN_FIELD email

Page 17: setting mail server debian

MYSQL_HOME_FIELD "/home/vmail"MYSQL_MAILDIR_FIELD CONCAT(SUBSTRING_INDEX(email,'@',-1),'/',SUBSTRING_INDEX(email,'@',1),'/')#MYSQL_NAME_FIELDMYSQL_QUOTA_FIELD quota

Then restart Courier:

/etc/init.d/courier-authdaemon restart/etc/init.d/courier-imap restart/etc/init.d/courier-imap-ssl restart/etc/init.d/courier-pop restart/etc/init.d/courier-pop-ssl restart

By running:

telnet localhost pop3

you can see if your POP3 server is working correctly. It should give back +OK Hello there. (Type quit to get back to the Linux shell.)

Quota Notifications

If you want to get notifications about all the email accounts that are over quota, then do this:

cd /usr/local/sbin/wget http://puuhis.net/vhcs/quota.txtmv quota.txt quota_notifychmod 755 quota_notify

Open /usr/local/sbin/quota_notify and edit the variables at the top:

my $POSTFIX_CF = "/etc/postfix/main.cf";my $MAILPROG = "/usr/sbin/sendmail -t";my $WARNPERCENT = 80;my @POSTMASTERS = ('[email protected]');my $CONAME = 'ISP.tld';my $COADDR = '[email protected]';my $SUADDR = '[email protected]';my $MAIL_REPORT = 1;my $MAIL_WARNING = 1;

Once done run:

crontab -e

And add the following cron job for the script:

0 0 * * * /usr/local/sbin/quota_notify &> /dev/null

Testing Postfix

To see if Postfix is ready for SMTP-AUTH run:

Page 18: setting mail server debian

telnet localhost 25

After you have established the connection to your postfix mail server type

ehlo localhost

If you see the following lines then everything is configured correctly:

250-AUTH LOGIN PLAIN250-AUTH=LOGIN PLAIN

Adding to the Database

To populate the database you can use the MySQL shell:

mysql -u root -pUSE mail;

At a minimum you have to create entries in the domain and user tables:

INSERT INTO `domains` (`domain`) VALUES ('example.com');INSERT INTO `users` (`email`, `password`, `quota`) VALUES ('[email protected]', ENCRYPT('secret'), 10485760);

To add entries into the other two tables you would do the following:

INSERT INTO `forwardings` (`source`, `destination`) VALUES ('[email protected]', '[email protected]');INSERT INTO `transport` (`domain`, `transport`) VALUES ('example.com', 'smtp:mail.example.com');

To leave the MySQL shell, type

quit;

Forwarding Options

The forwardings table can have entries as follows:

source destination description

[email protected] [email protected] emails for [email protected] to [email protected]

@example.com [email protected] Creates a Catch-All account for [email protected]. All emails to example.com will arrive at [email protected], except those that exist in the users table (i.e., if [email protected] exists in the users table, mails to

Page 19: setting mail server debian

[email protected] will still arrive at [email protected]).

@example.com @anotherdomain.com

This redirects all emails to example.com to the same user at anotherdomain.tld. E.g., emails to [email protected] will be forwarded to [email protected].

[email protected]@example.com, [email protected]

Forward emails for [email protected] to two or more email addresses. All listed email addresses under destination receive a copy of the email.

Transport Options

The transport table can have entries like these:

domain transport description

example.com :Delivers emails for example.com locally. This is as if this record would not exist in this table at all.

example.com smtp:mail.anotherdomain.comDelivers all emails for example.com via smtp to the server mail.anotherdomain.com.

example.com smtp:mail.anotherdomain.com:2025

Delivers all emails for example.com via smtp to the server mail.anotherdomain.com, but on port 2025, not 25 which is the default port for smtp.

example.comsmtp:[1.2.3.4], smtp:[1.2.3.4]:2025, smtp:[mail.anotherdomain.tld]

The square brackets prevent Postfix from doing lookups of the MX DNS record for the address in square brackets. Makes sense for IP addresses.

.example.com smtp:mail.anotherdomain.com Mail for any subdomain of example.com is delivered to

Page 20: setting mail server debian

mail.anotherdomain.com.

* smtp:mail.anotherdomain.comAll emails are delivered to mail.anotherdomain.com.

[email protected] smtp:mail.anotherdomain.comEmails for [email protected] are delivered to mail.anotherdomain.com.

Please keep in mind that the order of entries in the transport table is important! The entries will be followed from the top to the bottom.

Important: Postfix uses a caching mechanism for the transports, therefore it might take a while until you changes in the transport table take effect. If you want them to take effect immediately, run

postfix reload

after you have made your changes in the transport table.

Page 21: setting mail server debian