GNU/Linux >> LINUX-Kenntnisse >  >> Ubuntu

Virtuelle Benutzer und Domains mit Postfix, Courier, MySQL und SquirrelMail (Ubuntu 12.04 LTS)

Dieses Tutorial ist Copyright (c) 2012 von Falko Timme. Es ist abgeleitet von einem Tutorial von Christoph Haas, das Sie unter http://workaround.org finden. Es steht Ihnen frei, dieses Tutorial unter der Creative Commons-Lizenz 2.5 oder einer späteren Version zu verwenden.

Dieses Dokument beschreibt, wie Sie einen Postfix-Mailserver installieren, der auf virtuellen Benutzern und Domänen basiert, d. h. Benutzern und Domänen, die sich in einer MySQL-Datenbank befinden. Ich werde auch die Installation und Konfiguration von Courier (Courier-POP3, Courier-IMAP) demonstrieren, damit Courier sich bei derselben MySQL-Datenbank authentifizieren kann, die Postfix verwendet.

Der resultierende Postfix-Server ist SMTP-AUTH-fähig und TLS und Quote (Kontingent ist standardmäßig nicht in Postfix integriert, ich werde zeigen, wie Sie Ihr Postfix entsprechend patchen können). Passwörter werden verschlüsselt gespeichert Formular in der Datenbank (die meisten Dokumente, die ich gefunden habe, befassten sich mit Passwörtern im Klartext, was ein Sicherheitsrisiko darstellt). Darüber hinaus behandelt dieses Tutorial die Installation von Amavisd , SpamAssassin und ClamAV damit E-Mails auf Spam und Viren gescannt werden. Ich werde auch zeigen, wie man SquirrelMail installiert als Webmail-Schnittstelle, damit Benutzer E-Mails lesen und senden und ihre Passwörter ändern können.

Der Vorteil eines solchen „virtuellen“ Setups (virtuelle Benutzer und Domänen in einer MySQL-Datenbank) ist, dass es wesentlich performanter ist als ein Setup, das auf „echten“ Systembenutzern basiert. Mit diesem virtuellen Setup kann Ihr Mailserver Tausende von Domänen und Benutzern verwalten. Außerdem ist es einfacher zu administrieren, da Sie sich nur mit der MySQL-Datenbank befassen müssen, wenn Sie neue Benutzer/Domains hinzufügen oder bestehende bearbeiten. Keine Postmap-Befehle mehr zum Erstellen von db-Dateien, kein erneutes Laden von Postfix usw. Für die Verwaltung der MySQL-Datenbank können Sie webbasierte Tools wie phpMyAdmin verwenden, die auch in diesem Howto installiert werden. Der dritte Vorteil ist, dass Benutzer eine E-Mail-Adresse als Benutzernamen haben (statt Benutzername + E-Mail-Adresse), was einfacher zu verstehen und zu merken ist.

Dieses Howto ist als praktischer Leitfaden gedacht; es deckt nicht die theoretischen Hintergründe ab. Sie werden in vielen anderen Dokumenten im Internet behandelt.

Dieses Dokument wird ohne jegliche Gewährleistung geliefert! Ich möchte sagen, dass dies nicht die einzige Möglichkeit ist, ein solches System einzurichten. Es gibt viele Wege, dieses Ziel zu erreichen, aber ich gehe diesen Weg. Ich gebe keine Garantie dafür, dass dies bei Ihnen funktioniert!

1 Vorbemerkung

Dieses Tutorial basiert auf Ubuntu 12.04 LTS Server (Precise Pangolin), daher sollten Sie eine grundlegende Ubuntu 12.04-Serverinstallation einrichten, bevor Sie mit diesem Tutorial fortfahren (z. B. wie auf den Seiten 1 - 3 in diesem Tutorial gezeigt:The Perfect Server - Ubuntu 12.04 LTS (Apache2, BIND, Dovecot, ISPConfig 3)). Das System sollte eine statische IP-Adresse haben. Ich verwende 192.168.0.100 als IP-Adresse in diesem Tutorial und server1.example.com als Hostnamen.

Stellen Sie sicher, dass Sie als root angemeldet sind (geben Sie

ein
sudo su

um root zu werden), da wir alle Schritte aus diesem Tutorial als root-Benutzer ausführen müssen.

Es ist sehr wichtig, dass Sie /bin/sh zu einem symbolischen Link zu /bin/bash...

machen
dpkg-reconfigure dash

Dash als Standardsystem-Shell verwenden (/bin/sh)? <-- Nein

... und dass Sie AppArmor deaktivieren:

/etc/init.d/apparmor stop
update-rc.d -f apparmor remove
apt-get remove apparmor apparmor-utils

 

2 Installieren Sie Postfix, Courier, Saslauthd, MySQL, phpMyAdmin

Um Postfix, Courier, Saslauthd, MySQL und phpMyAdmin zu installieren, führen wir einfach

aus
apt-get install postfix postfix-mysql postfix-doc mysql-client mysql-server courier-authdaemon courier-authlib-mysql courier-pop courier-pop-ssl courier-imap courier-imap-ssl  libsasl2-2 libsasl2-modules libsasl2-modules-sql sasl2-bin libpam-mysql openssl phpmyadmin apache2 libapache2-mod-php5 php5 php5-mysql libpam-smbpass

Ihnen werden einige Fragen gestellt:

Neues Passwort für den MySQL-Benutzer „root“:<-- yourrootsqlpassword
Passwort für den MySQL-Benutzer „root“ wiederholen:<-- yourrootsqlpassword
Verzeichnisse für webbasierte Verwaltung erstellen? <-- Nein
Allgemeine Art der E-Mail-Konfiguration:<-- Internet-Site
System-E-Mail-Name:<-- server1.example.com
SSL-Zertifikat erforderlich <-- Ok
Webserver zur automatischen Neukonfiguration:<-- apache2
Datenbank für phpmyadmin mit dbconfig-common konfigurieren? <-- Nein

3 Wenden Sie den Quoten-Patch auf Postfix an

Wir müssen die Postfix-Quellen besorgen, sie mit dem Quota-Patch patchen, neue Postfix-.deb-Pakete erstellen und diese .deb-Pakete installieren:

apt-get build-dep postfix

cd /usr/src
apt-get source postfix

(Stellen Sie sicher, dass Sie in den folgenden Befehlen die richtige Postfix-Version verwenden. Ich habe Postfix 2.9.1 installiert. Sie können Ihre Postfix-Version herausfinden, indem Sie

ausführen
 postconf -d | grep mail_version

Die Ausgabe sollte so aussehen:

[E-Mail-geschützt]:/usr/src# postconf -d | grep mail_version
mail_version =2.9.1
milter_macro_v =$mail_name $mail_version
[email protected]:/usr/src#

)

wget http://vda.sourceforge.net/VDA/postfix-vda-v11-2.9.1.patch
cd postfix-2.9.1
patch -p1 <../postfix-vda-v11 -2.9.1.patch

Öffnen Sie als nächstes debian/rules und ändern Sie DEB_BUILD_HARDENING von 1 auf 0:

vi debian/rules
[...]
export DEB_BUILD_HARDENING=0
[...]

Wenn Sie dies nicht tun, schlägt Ihr Build mit den folgenden Fehlermeldungen fehl:

maildir.c:In Funktion âdeliver_maildirâ:
maildir.c:974:17:Fehler:Format kein String-Literal und keine Formatargumente [-Werror=format-security]
maildir.c:977:17 :Fehler:Format kein String-Literal und keine Formatargumente [-Werror=Format-Sicherheit]
maildir.c:983:17:Fehler:Format kein String-Literal und keine Formatargumente [-Werror=Format-Security ]
maildir.c:986:17:error:format not a string literal and no format arguments [-Werror=format-security]
maildir.c:In function âsql2fileâ:
maildir. c:404:25:Warnung:Rückgabewert von âreadâ ignorieren, deklariert mit Attribut warn_unused_result [-Wunused-result]
maildir.c:417:26:Warnung:Rückgabewert von âwriteâ ignorieren, deklariert mit Attribut warn_unused_result [- Wuused-Ergebnis]
cc1:Einige Warnungen werden als Fehler behandelt
make:*** [maildir.o] Fehler 1
make:Verzeichnis verlassen `/usr/src/postfix-2.9. 1/src/virtual'
make[1]:*** [update] Error 1
make[1]:Leaving directory `/usr/src/postfix -2.9.1'
make:*** [build] Error 2
dpkg-buildpackage:error:debian/rules build hat Fehlerstatus 2 ausgegeben
[email protected]:/usr/ src/postfix-2.9.1#

Jetzt können wir die neuen Postfix .deb-Pakete bauen:

  dpkg-buildpackage

Jetzt gehen wir ein Verzeichnis nach oben, dort wurden die neuen .deb-Pakete erstellt:

cd ..

Der Befehl

ls -l

zeigt Ihnen die verfügbaren Pakete:

[email protected]:/usr/src# ls -l
insgesamt 6932
drwxr-xr-x 24 root root    4096 Apr 27 11:20 linux-headers-3.2.0-23
drwxr-xr-x  7 root root    4096 Apr 27 11:20 linux-headers-3.2.0-23-generic
drwxr-xr-x  18 root root    4096 Mai  7 15:57 postfix-2.9.1
-rw-r--r--  1 root root    3814 Mai  7 15:58 postfix_2.9.1-4_amd64.changes
-rw-r--r--  1 root root 1497792 Mai  7 15:58 postfix_2 .9.1-4_amd64.deb
-rw-r--r--  1 root root  246141 Mai  7 15:51 postfix_2.9.1-4.diff.gz
-rw-r--r-- 1 root root    1492 Mai  7 15:51 postfix_2.9.1-4.dsc
-rw-r--r--  1 root root 3768329 Mär 22 05:05 postfix_2.9.1.orig.tar.gz
-rw-r--r--  1 root root   46620 Mai  7 15:58 postfix-cdb_2.9.1-4_amd64.deb
-rw-r--r--  1 root root  160196 Mai  7 15:58 postfix-dev_2.9.1-4_all.deb
-rw-r--r--  1 root root 1080772 Mai  7 15:58 postfix-doc_2.9.1-4_all.deb
-rw-r-- r--  1 root root   55478 Mai  7 15:58 postfix-ldap_2.9.1-4_amd64.deb
-rw-r--r--  1 root root   48550 Ma j  7 15:58 postfix-mysql_2.9.1-4_amd64.deb
-rw-r--r--  1 root root   48718 Mai  7 15:58 postfix-pcre_2.9.1-4_amd64.deb
- rw-r--r--  1 root root   48686 Mai  7 15:58 postfix-pgsql_2.9.1-4_amd64.deb
-rw-r--r--  1 root root   55009 11. April 14:54 postfix- vda-v11-2.9.1.patch
[E-Mail-geschützt]:/usr/src#

Wählen Sie die Pakete postfix und postfix-mysql aus und installieren Sie sie wie folgt:

dpkg -i postfix_2.9.1-4_amd64.deb postfix-mysql_2.9.1-4_amd64.deb

4 Erstellen Sie die MySQL-Datenbank für Postfix/Courier

Jetzt erstellen wir eine Datenbank namens mail:

mysqladmin -u root -p create mail

Als nächstes gehen wir zur MySQL-Shell:

mysql -u root -p

Auf der MySQL-Shell erstellen wir den Benutzer mail_admin mit dem Passwort mail_admin_password (ersetzen Sie es durch Ihr eigenes Passwort), der die Berechtigungen SELECT, INSERT, UPDATE, DELETE in der Mail-Datenbank hat. Dieser Benutzer wird von Postfix und Courier verwendet, um sich mit der Mail-Datenbank zu verbinden:

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' IDENTIFIZIERT DURCH 'mail_admin_password';
FLUSH PRIVILEGES;

Immer noch auf der MySQL-Shell erstellen wir die von Postfix und Courier benötigten Tabellen:

USE mail;

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

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

CREATE TABLE-Benutzer (
E-Mail-Varchar(80) NOT NULL,
Passwort-Varchar(20) NOT NULL,
Quote INT(10) DEFAULT '10485760',
PRIMARY KEY (E-Mail )
) ENGINE=MyISAM;

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

quit;

Wie Sie vielleicht bemerkt haben, mit dem Beenden; Befehl haben wir die MySQL-Shell verlassen und befinden uns wieder auf der Linux-Shell.

Die Domänen Tabelle speichert jede virtuelle Domain, für die Postfix E-Mails erhalten soll (z. B. example.com ).

Domäne
beispiel.com

Die Weiterleitungen Tabelle dient zum Aliasing einer E-Mail-Adresse zu einer anderen, z. E-Mails für [email protected] weiterleiten an [email protected] .

Quelle Ziel
[E-Mail-geschützt] [E-Mail-geschützt]

Die Benutzer Tabelle speichert alle virtuellen Benutzer (d. h. E-Mail-Adressen, weil E-Mail-Adresse und Benutzername identisch sind) und Passwörter (in verschlüsselt Formular!) und einen Kontingentwert für jedes Postfach (in diesem Beispiel ist der Standardwert 10485760 Bytes, was 10 MB entspricht).

E-Mail Passwort Kontingent
[E-Mail-geschützt] No9.E4skNvGa. ("geheim" in verschlüsselter Form) 10485760

Der Transport Tabelle ist optional, sie ist für fortgeschrittene Benutzer. Es erlaubt, Mails für einzelne Benutzer, ganze Domänen oder alle Mails an einen anderen Server weiterzuleiten. Beispiel:

Domäne Transport
beispiel.com smtp:[1.2.3.4]

würde alle E-Mails für example.com weiterleiten über das SMTP-Protokoll an den Server mit der IP-Adresse 1.2.3.4 (die eckigen Klammern [] bedeutet "keine Suche nach dem MX-DNS-Eintrag durchführen" (was für IP-Adressen sinnvoll ist ...). Wenn Sie stattdessen einen vollständig qualifizierten Domänennamen (FQDN) verwenden, würden Sie die eckigen Klammern nicht verwenden.).

Übrigens (ich gehe davon aus, dass die IP-Adresse Ihres Mailserversystems 192.168.0.100 ist) Sie können über http://192.168.0.100/phpmyadmin/ in einem Browser auf phpMyAdmin zugreifen und sich als mail_admin anmelden. Dann können Sie einen Blick in die Datenbank werfen. Später können Sie mit phpMyAdmin Ihren Mailserver verwalten.

5 Postfix konfigurieren

Jetzt müssen wir Postfix mitteilen, wo es alle Informationen in der Datenbank finden kann. Dazu müssen wir sechs Textdateien erstellen. Sie werden feststellen, dass ich Postfix anweise, sich mit MySQL über die IP-Adresse 127.0.0.1 anstelle von localhost zu verbinden. Dies liegt daran, dass Postfix in einem Chroot-Gefängnis läuft und keinen Zugriff auf den MySQL-Socket hat, den es zu verbinden versuchen würde, wenn ich Postfix anweise, localhost zu verwenden. Wenn ich 127.0.0.1 verwende, verwendet Postfix TCP-Netzwerke, um sich mit MySQL zu verbinden, was selbst in einem Chroot-Gefängnis kein Problem darstellt (die Alternative wäre, den MySQL-Socket in das Chroot-Gefängnis zu verschieben, was einige andere Probleme verursacht).

Bitte stellen Sie sicher, dass /etc/mysql/my.cnf die folgende Zeile enthält:

vi /etc/mysql/my.cnf
[...]
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address           = 127.0.0.1
[...]

Wenn Sie /etc/mysql/my.cnf ändern mussten, starten Sie MySQL bitte jetzt neu:

/etc/init.d/mysql restart

Ausführen

netstat -tap | grep mysql

um sicherzustellen, dass MySQL auf 127.0.0.1 (localhost.localdomain) lauscht:

[email protected]:/usr/src# netstat -tap | grep mysql
tcp        0      0 localhost.localdo:mysql *:*                    LISTEN      3895/mysqld
[email protected]:/usr/src#

Lassen Sie uns nun unsere sechs Textdateien erstellen.

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

Ändern Sie dann die Berechtigungen und die Gruppe dieser Dateien:

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

Jetzt erstellen wir einen Benutzer und eine Gruppe namens vmail mit dem Home-Verzeichnis /home/vmail. Hier werden alle Postfächer gespeichert.

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

Als nächstes nehmen wir eine Postfix-Konfiguration vor. Stellen Sie sicher, dass Sie server1.example.com durch einen gültigen FQDN ersetzen, sonst funktioniert Ihr Postfix möglicherweise nicht richtig!

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_sasl_authenticated_header =yes'
postconf -e 'smtpd_recipient_restrictions =permission_mynetworks, permission_sasl_authenticated, respond_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_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 ="Der Benutzer, den Sie erreichen möchten, hat sein Kontingent überschritten."'
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 $ canonicaljnaps $ sender_canonical_maps $ recipient_canonical_maps $ relocated_maps $ transportjnaps $ mynetworks $ virtual_mailbox_limit_maps'

Anschließend erstellen wir das für TLS benötigte SSL-Zertifikat:

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

Ländername (2-Buchstaben-Code) [AU]:<-- Geben Sie Ihren Ländernamen ein (z. B. "DE").
Staats- oder Provinzname (vollständiger Name) [Some-State]:<-- Geben Sie Ihren Staat ein oder Provinzname.
Ortsname (zB Stadt) []:<-- Geben Sie Ihre Stadt ein.
Organisationsname (zB Firma) [Internet Widgits Pty Ltd]:<-- Geben Sie Ihren Organisationsnamen ein (z. B. der Name Ihres Unternehmens).
Name der Organisationseinheit (z. B. Abteilung) []:<-- Geben Sie den Namen Ihrer Organisationseinheit ein (z. B. "IT-Abteilung").
Allgemeiner Name (z. B. IHR Name) []:<-- Geben Sie den vollständig qualifizierten Domänennamen des Systems ein (z. B. "server1.example.com").
E-Mail-Adresse []:<-- Geben Sie Ihre E-Mail-Adresse ein.

Ändern Sie dann die Berechtigungen des smtpd.key:

chmod o= /etc/postfix/smtpd.key

6 Saslauthd konfigurieren

Erster Lauf

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

Bearbeiten Sie dann /etc/default/saslauthd. Setzen Sie START auf yes und ändern Sie die Zeile OPTIONS="-c -m /var/run/saslauthd" in OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r":

vi /etc/default/saslauthd
#
# Settings for saslauthd daemon
# Please read /usr/share/doc/sasl2-bin/README.Debian for details.
#

# Should saslauthd run automatically on startup? (default: no)
START=yes

# Description of this saslauthd instance. Recommended.
# (suggestion: SASL Authentication Daemon)
DESC="SASL Authentication Daemon"

# Short name of this saslauthd instance. Strongly recommended.
# (suggestion: saslauthd)
NAME="saslauthd"

# Which authentication mechanisms should saslauthd use? (default: pam)
#
# Available options in this Debian package:
# getpwent  -- use the getpwent() library function
# kerberos5 -- use Kerberos 5
# pam       -- use PAM
# rimap     -- use a remote IMAP server
# shadow    -- use the local shadow password file
# sasldb    -- use the local sasldb database file
# ldap      -- use LDAP (configuration is in /etc/saslauthd.conf)
#
# Only one option may be used at a time. See the saslauthd man page
# for more information.
#
# Example: MECHANISMS="pam"
MECHANISMS="pam"

# Additional options for this mechanism. (default: none)
# See the saslauthd man page for information about mech-specific options.
MECH_OPTIONS=""

# How many saslauthd processes should we run? (default: 5)
# A value of 0 will fork a new process for each connection.
THREADS=5

# Other options (default: -c -m /var/run/saslauthd)
# Note: You MUST specify the -m option or saslauthd won't run!
#
# WARNING: DO NOT SPECIFY THE -d OPTION.
# The -d option will cause saslauthd to run in the foreground instead of as
# a daemon. This will PREVENT YOUR SYSTEM FROM BOOTING PROPERLY. If you wish
# to run saslauthd in debug mode, please run it by hand to be safe.
#
# See /usr/share/doc/sasl2-bin/README.Debian for Debian-specific information.
# See the saslauthd man page and the output of 'saslauthd -h' for general
# information about these options.
#
# Example for chroot Postfix users: "-c -m /var/spool/postfix/var/run/saslauthd"
# Example for non-chroot Postfix users: "-c -m /var/run/saslauthd"
#
# To know if your Postfix is running chroot, check /etc/postfix/master.cf.
# If it has the line "smtp inet n - y - - smtpd" or "smtp inet n - - - - smtpd"
# then your Postfix is running in a chroot.
# If it has the line "smtp inet n - n - - smtpd" then your Postfix is NOT
# running in a chroot.
#OPTIONS="-c -m /var/run/saslauthd"
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"

Erstellen Sie dann die Datei /etc/pam.d/smtp. Es sollte nur die folgenden zwei Zeilen enthalten (stellen Sie sicher, dass Sie Ihre korrekten Datenbankdetails eingeben):

vi /etc/pam.d/smtp
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=1
account 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

Als nächstes erstellen Sie die Datei /etc/postfix/sasl/smtpd.conf. Es sollte so aussehen:

vi /etc/postfix/sasl/smtpd.conf
pwcheck_method: saslauthd
mech_list: plain login
allow_plaintext: true
auxprop_plugin: sql
sql_engine: mysql
sql_hostnames: 127.0.0.1
sql_user: mail_admin
sql_passwd: mail_admin_password
sql_database: mail
sql_select: select password from users where email = '%[email protected]%r'

Als nächstes fügen Sie den postfix-Benutzer zur sasl-Gruppe hinzu (dies stellt sicher, dass Postfix die Berechtigung hat, auf saslauthd zuzugreifen):

adduser postfix sasl

Starten Sie dann Postfix und Saslauthd neu:

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

7 Kurier konfigurieren

Jetzt müssen wir Courier mitteilen, dass es sich gegen unsere MySQL-Datenbank authentifizieren soll. Bearbeiten Sie zunächst /etc/courier/authdaemonrc und ändern Sie den Wert von authmodulelist so, dass er lautet:

vi /etc/courier/authdaemonrc
[...]
authmodulelist="authmysql"
[...]

Erstellen Sie dann ein Backup von /etc/courier/authmysqlrc und leeren Sie die alte Datei:

cp /etc/courier/authmysqlrc /etc/courier/authmysqlrc_orig
cat /dev/null> /etc/courier/authmysqlrc

Öffnen Sie dann /etc/courier/authmysqlrc und fügen Sie die folgenden Zeilen ein:

vi /etc/courier/authmysqlrc
MYSQL_SERVER localhost
MYSQL_USERNAME mail_admin
MYSQL_PASSWORD mail_admin_password
MYSQL_PORT 0
MYSQL_DATABASE mail
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),'/')
#MYSQL_NAME_FIELD
MYSQL_QUOTA_FIELD quota

Während der Installation werden die SSL-Zertifikate für IMAP-SSL und POP3-SSL mit dem Hostnamen localhost erstellt. Um dies in den richtigen Hostnamen (server1.example.com in diesem Tutorial) zu ändern, löschen Sie die Zertifikate...

cd /etc/courier
rm -f /etc/courier/imapd.pem
rm -f /etc/courier/pop3d.pem

... und ändern Sie die folgenden zwei Dateien; Ersetzen Sie CN=localhost durch CN=server1.example.com (Sie können bei Bedarf auch die anderen Werte ändern):

vi /etc/courier/imapd.cnf
[...]
CN=server1.example.com
[...]
vi /etc/courier/pop3d.cnf 
[...]
CN=server1.example.com
[...]

Erstellen Sie dann die Zertifikate neu...

mkimapdcert
mkpop3dcert

... und starten Sie Courier neu:

/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

Durch Ausführen

telnet localhost pop3

können Sie sehen, ob Ihr POP3-Server ordnungsgemäß funktioniert. Es sollte +OK zurückgeben. Hallo. (Geben Sie quit ein, um zur Linux-Shell zurückzukehren.)

[email protected]:/etc/courier# telnet localhost pop3
Versuche 127.0.0.1...
Verbunden mit localhost.localdomain.
Escape-Zeichen ist '^]'.
+OK Hallo.
<-- Beenden
+OK Viel Glück beim nächsten Mal.
Verbindung von ausländischem Host geschlossen.
[email protected]:/etc/courier#

8 /etc/aliases ändern

Jetzt sollten wir /etc/aliases öffnen. Stellen Sie sicher, dass postmaster auf root zeigt und root auf Ihren eigenen Benutzernamen oder Ihre E-Mail-Adresse, z. so:

vi /etc/aliases
[...]
postmaster: root
root: [email protected]
[...]

oder so (wenn Administrator Ihr eigener Benutzername ist):

[...]
postmaster: root
root:   administrator
[...]

Wann immer Sie /etc/aliases ändern, müssen Sie

ausführen
newaliases

anschließend Postfix neu starten:

/etc/init.d/postfix restart

9 Installieren Sie amavisd-new, SpamAssassin und ClamAV

Um amavisd-new, spamassassin und clamav zu installieren, führen Sie den folgenden Befehl aus:

apt-get install amavisd-new spamassassin clamav clamav-daemon zoo unzip bzip2 libnet-ph-perl libnet-snpp-perl libnet-telnet-perl nomarch lzop pax

Danach müssen wir amavisd-new konfigurieren. Die Konfiguration ist in verschiedene Dateien aufgeteilt, die sich im Verzeichnis /etc/amavis/conf.d befinden. Sehen Sie sich jeden von ihnen an, um sich mit der Konfiguration vertraut zu machen. Die meisten Einstellungen sind in Ordnung, aber wir müssen drei Dateien ändern:

Zuerst müssen wir ClamAV und SpamAssassin in /etc/amavis/conf.d/15-content_filter_mode aktivieren, indem wir die Zeilen @bypass_virus_checks_maps und @bypass_spam_checks_maps auskommentieren:

vi /etc/amavis/conf.d/15-content_filter_mode

Die Datei sollte folgendermaßen aussehen:

use strict;

# You can modify this file to re-enable SPAM checking through spamassassin
# and to re-enable antivirus checking.

#
# Default antivirus checking mode
# Please note, that anti-virus checking is DISABLED by
# default.
# If You wish to enable it, please uncomment the following lines:


@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);


#
# Default SPAM checking mode
# Please note, that anti-spam checking is DISABLED by
# default.
# If You wish to enable it, please uncomment the following lines:


@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

1;  # ensure a defined return

Und dann sollten Sie sich die Spam-Einstellungen und die Aktionen für Spam-/Virus-Mails in /etc/amavis/conf.d/20-debian_defaults ansehen. Sie müssen nichts ändern, wenn die Standardeinstellungen für Sie in Ordnung sind. Die Datei enthält viele Erklärungen, sodass die Einstellungen hier nicht erklärt werden müssen:

vi /etc/amavis/conf.d/20-debian_defaults
[...]
$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  = 2.0;  # add spam info headers if at, or above that level
$sa_tag2_level_deflt = 6.31; # 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
[...]
$final_virus_destiny      = D_DISCARD;  # (data not lost, see virus quarantine)
$final_banned_destiny     = D_BOUNCE;   # D_REJECT when front-end MTA
$final_spam_destiny       = D_BOUNCE;
$final_bad_header_destiny = D_PASS;     # False-positive prone (for spam)
[...]

Bearbeiten Sie abschließend /etc/amavis/conf.d/50-user und fügen Sie die Zeile $pax='pax'; in der Mitte:

vi /etc/amavis/conf.d/50-user
use strict;

#
# Place your configuration directives here.  They will override those in
# earlier files.
#
# See /usr/share/doc/amavisd-new/ for documentation and examples of
# the directives you can use in this file
#
$pax='pax';

#------------ Do not modify anything below this line -------------
1;  # ensure a defined return

Führen Sie anschließend diese Befehle aus, um den clamav-Benutzer zur amavis-Gruppe hinzuzufügen und amavisd-new und ClamAV neu zu starten:

adduser clamav amavis
/etc/init.d/amavis restart
/etc/init.d/clamav-freshclam restart
/etc/init.d/clamav-daemon restart

Jetzt müssen wir Postfix so konfigurieren, dass eingehende E-Mails durch amavisd-new:

geleitet werden

postconf -e 'content_filter =amavis:[127.0.0.1]:10024'
postconf -e 'receive_override_options =no_address_mappings'

Hängen Sie anschließend die folgenden Zeilen an /etc/postfix/master.cf an:

vi /etc/postfix/master.cf
[...]
amavis unix - - - - 2 smtp
        -o smtp_data_done_timeout=1200
        -o smtp_send_xforward_command=yes

127.0.0.1:10025 inet n - - - - smtpd
        -o content_filter=
        -o local_recipient_maps=
        -o relay_recipient_maps=
        -o smtpd_restriction_classes=
        -o smtpd_client_restrictions=
        -o smtpd_helo_restrictions=
        -o smtpd_sender_restrictions=
        -o smtpd_recipient_restrictions=permit_mynetworks,reject
        -o mynetworks=127.0.0.0/8
        -o strict_rfc821_envelopes=yes
        -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks

Starten Sie dann Postfix neu:

/etc/init.d/postfix restart

Jetzt ausführen

netstat -tap

und Sie sollten sehen, dass Postfix (Master) auf Port 25 (smtp) und 10025 lauscht, und amavisd-new auf Port 10024:

[email protected]:/etc/courier# netstat -tap
Aktive Internetverbindungen (Server und hergestellt)
Proto Recv-Q Send-Q Lokale Adresse           Ausländische Adresse         Staat       PID/Programmname
tcp 0 0 localhost.localdo:10025*:*Hören Sie 25911/Master
tcp 0 0 localhost.localdo:mysql*:*Hören 3895/mysqld
TCP 0 0*:http*:*Hören 4845/apache2
TCP 0 0*:SSH*:*Hören Sie 649 /SSHD
TCP 0 0**:SMTP*:*Hören Sie 25911 /Master
TCP 0 0 0 0 localhost.localdo:10024*:*Hören 24534/amavisd (Mast
TCP 0 52 Server1.example.com:SHSH 192.168.0.199:4745 Erstellt 847/0
TCP6 0 0 [::]:pop3 [::]:*Hören 20989/ couriertcpd
tcp6 0 0 [::]:IMAP2 [::]:*Hören Sie 20921 /CourIERTCPD
TCP6 0 0 [::]:ssh [::]:*Hören Sie 649 /sshd
tcp6 0 [::]:SMTP [::]:*Hören Sie 25911 /Master
TCP6 0 0 [::]:IMAPS [::]:*Hören Sie 20958 /Courerertcpd
tcp6 0 0 [::]:Pop3s [::]:*                  HÖREN      21026/couriertcpd
[email protected]:/etc/courier#

 

10 Installieren Sie Razor, Pyzor und DCC und konfigurieren Sie SpamAssassin

Razor, Pyzor und DCC sind Spamfilter, die ein kollaboratives Filternetzwerk verwenden. Um Razor und Pyzor zu installieren, führen Sie

aus
apt-get install razor pyzor

DCC ist in den Ubuntu 12.04-Repositories nicht verfügbar, daher installieren wir es wie folgt:

cd /tmp
wget http://www.dcc-servers.net/dcc/source/dcc-dccproc.tar.Z
tar xzvf dcc-dccproc.tar.Z
cd dcc -dccproc-1.3.142
./configure --with-uid=amavis
make
make install
chown -R amavis:amavis /var/dcc
ln -s /var/dcc/libexec/dccifd /usr/local/bin/dccifd

Jetzt müssen wir SpamAssassin anweisen, diese drei Programme zu verwenden. Bearbeiten Sie /etc/spamassassin/local.cf und fügen Sie die folgenden Zeilen hinzu:

vi /etc/spamassassin/local.cf
[...]
#dcc
use_dcc 1
dcc_path /usr/local/bin/dccproc

#pyzor
use_pyzor 1
pyzor_path /usr/bin/pyzor

#razor
use_razor2 1
razor_config /etc/razor/razor-agent.conf

#bayes
use_bayes 1
use_bayes_rules 1
bayes_auto_learn 1

Dann müssen wir das DCC-Plugin in SpamAssassin aktivieren. Öffnen Sie /etc/spamassassin/v310.pre und kommentieren Sie die loadplugin Mail::SpamAssassin::Plugin::DCC line:

aus
vi /etc/spamassassin/v310.pre
[...]
# DCC - perform DCC message checks.
#
# DCC is disabled here because it is not open source.  See the DCC
# license for more details.
#
loadplugin Mail::SpamAssassin::Plugin::DCC
[...]

Sie können Ihre SpamAssassin-Konfiguration überprüfen, indem Sie Folgendes ausführen:

spamassassin --lint

Es sollte keine Fehler anzeigen.

Jetzt gibt es einen kleinen Fehler im amavisd-new Init-Skript. Öffnen Sie /etc/init.d/amavis...

vi /etc/init.d/amavis

... und kommentieren Sie die Zeile STOP="--stop --quiet --pidfile $PIDFILE --name ${DAEMONNAME}" aus und fügen Sie stattdessen STOP="--stop --quiet --pidfile $PIDFILE" hinzu:

[...]
set -e

START="--start --quiet --pidfile $PIDFILE --name ${DAEMONNAME} --startas ${DAEMON}"
#STOP="--stop --quiet --pidfile $PIDFILE --name ${DAEMONNAME}"
STOP="--stop --quiet --pidfile $PIDFILE"
PARAMS=

check_noncompatible_upgrade()
[...]

Starten Sie danach amavisd-new neu:

/etc/init.d/amavis restart

Jetzt aktualisieren wir unsere SpamAssassin-Regelsätze wie folgt:

sa-update --no-gpg

Wir erstellen einen Cron-Job, damit die Regelsätze regelmäßig aktualisiert werden. Ausführen

crontab -e

um den Cronjob-Editor zu öffnen. Erstellen Sie den folgenden Cronjob:

23 4 */2 * * /usr/bin/sa-update --no-gpg &> /dev/null

Dadurch werden die Regelsätze jeden zweiten Tag um 4:23 Uhr aktualisiert.

11 Benachrichtigungen über Quotenüberschreitungen

Wenn Sie Benachrichtigungen über alle E-Mail-Konten erhalten möchten, die das Kontingent überschritten haben, erstellen Sie die Datei /usr/local/sbin/quota_notify:

cd /usr/local/sbin/
vi quota_notify

#!/usr/bin/perl -w

# Author <[email protected]>
#
# This script assumes that virtual_mailbox_base in defined
# in postfix's main.cf file. This directory is assumed to contain
# directories which themselves contain your virtual user's maildirs.
# For example:
#
# -----------/
#            |
#            |
#    home/vmail/domains/
#        |          |
#        |          |
#  example.com/  foo.com/
#                   |
#                   |
#           -----------------
#           |       |       |
#           |       |       |
#         user1/   user2/  user3/
#                           |
#                           |
#                        maildirsize
#

use strict;

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

#get virtual mailbox base from postfix config
open(PCF, "< $POSTFIX_CF") or die $!;
my $mboxBase;
while (<PCF>) {
   next unless /virtual_mailbox_base\s*=\s*(.*)\s*/;
   $mboxBase = $1;
}
close(PCF);

#assume one level of subdirectories for domain names
my @domains;
opendir(DIR, $mboxBase) or die $!;
while (defined(my $name = readdir(DIR))) {
   next if $name =~ /^\.\.?$/;        #skip '.' and '..'
   next unless (-d "$mboxBase/$name");
   push(@domains, $name);
}
closedir(DIR);
#iterate through domains for username/maildirsize files
my @users;
chdir($mboxBase);
foreach my $domain (@domains) {
        opendir(DIR, $domain) or die $!;
        while (defined(my $name = readdir(DIR))) {
           next if $name =~ /^\.\.?$/;        #skip '.' and '..'
           next unless (-d "$domain/$name");
      push(@users, {"$name\@$domain" => "$mboxBase/$domain/$name"});
        }
}
closedir(DIR);

#get user quotas and percent used
my (%lusers, $report);
foreach my $href (@users) {
   foreach my $user (keys %$href) {
      my $quotafile = "$href->{$user}/maildirsize";
      next unless (-f $quotafile);
      open(QF, "< $quotafile") or die $!;
      my ($firstln, $quota, $used);
      while (<QF>) {
         my $line = $_;
              if (! $firstln) {
                 $firstln = 1;
                 die "Error: corrupt quotafile $quotafile"
                    unless ($line =~ /^(\d+)S/);
                 $quota = $1;
            last if (! $quota);
            next;
         }
         die "Error: corrupt quotafile $quotafile"
            unless ($line =~ /\s*(-?\d+)/);
         $used += $1;
      }
      close(QF);
      next if (! $used);
      my $percent = int($used / $quota * 100);
      $lusers{$user} = $percent unless not $percent;
   }
}

#send a report to the postmasters
if ($MAIL_REPORT) {
   open(MAIL, "| $MAILPROG");
   select(MAIL);
   map {print "To: $_\n"} @POSTMASTERS;
   print "From: $COADDR\n";
   print "Subject: Daily Quota Report.\n";
   print "DAILY QUOTA REPORT:\n\n";
   print "----------------------------------------------\n";
   print "| % USAGE |            ACCOUNT NAME          |\n";
   print "----------------------------------------------\n";
   foreach my $luser ( sort { $lusers{$b} <=> $lusers{$a} } keys %lusers ) {
      printf("|   %3d   | %32s |\n", $lusers{$luser}, $luser);
      print "---------------------------------------------\n";
   }
        print "\n--\n";
        print "$CONAME\n";
        close(MAIL);
}

#email a warning to people over quota
if ($MAIL_WARNING) {
        foreach my $luser (keys (%lusers)) {
           next unless $lusers{$luser} >= $WARNPERCENT;       # skip those under quota
           open(MAIL, "| $MAILPROG");
           select(MAIL);
           print "To: $luser\n";
      map {print "BCC: $_\n"} @POSTMASTERS;
           print "From: $SUADDR\n";
           print "Subject: WARNING: Your mailbox is $lusers{$luser}% full.\n";
           print "Reply-to: $SUADDR\n";
           print "Your mailbox: $luser is $lusers{$luser}% full.\n\n";
           print "Once your e-mail box has exceeded your monthly storage quota\n";
      print "your monthly billing will be automatically adjusted.\n";
      print "Please consider deleting e-mail and emptying your trash folder to clear some space.\n\n";
           print "Contact <$SUADDR> for further assistance.\n\n";
           print "Thank You.\n\n";
           print "--\n";
           print "$CONAME\n";
           close(MAIL);
        }
}

Stellen Sie sicher, dass Sie die Variablen oben anpassen (insbesondere die [E-Mail-geschützte] E-Mail-Adresse).

Wir müssen die Datei ausführbar machen:

chmod 755 quota_notify 

Ausführen

crontab -e

um einen Cron-Job für dieses Skript zu erstellen:

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

12 Postfix testen

Um zu sehen, ob Postfix für SMTP-AUTH und TLS bereit ist, führen Sie

aus
telnet localhost 25

Nachdem Sie die Verbindung zu Ihrem Postfix-Mailserver hergestellt haben, geben Sie

ein
ehlo localhost

Wenn Sie die Linien sehen

250-STARTTLS

und

250-AUTH PLAIN LOGIN

alles ist in Ordnung:

[email protected]:/usr/local/sbin# telnet localhost 25
Versuche 127.0.0.1...
Verbunden mit localhost.localdomain.
Escape-Zeichen ist '^]'.
220 server1.example.com ESMTP Postfix (Ubuntu)
<-- ehlo localhost
250-server1.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250 -8BITMIME
250 DSN
<-- quit
221 2.0.0 Bye
Verbindung von fremdem Host geschlossen.
[email protected]:/usr/local/sbin #

Geben Sie

ein
quit

um zur System-Shell zurückzukehren.

13 Datenbank füllen und testen

Um die Datenbank zu füllen, können Sie die MySQL-Shell verwenden:

mysql -u root -p
  USE mail;

Zumindest müssen Sie Einträge in den Tabellen domains erstellen und Benutzer :

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

(Bitte achten Sie darauf, dass Sie in der zweiten INSERT-Anweisung die ENCRYPT-Syntax verwenden, um das Passwort zu verschlüsseln!)

Wenn Sie in den anderen beiden Tabellen Einträge machen wollen, sieht das so aus:

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

Um die MySQL-Shell zu verlassen, geben Sie

ein
quit;

Für die meisten Leute ist es einfacher, wenn sie ein grafisches Frontend für MySQL haben; daher können Sie auch phpMyAdmin verwenden (in diesem Beispiel unter http://192.168.0.100/phpmyadmin/ ). oder http://server1.example.com/phpmyadmin/), um die Mail zu verwalten Datenbank. Achten Sie auch hier beim Erstellen eines Benutzers darauf, dass Sie die ENCRYPT-Funktion verwenden, um das Passwort zu verschlüsseln:

Ich glaube nicht, dass ich die Domänen- und Benutzertabelle weiter erklären muss.

Die Weiterleitungstabelle kann Einträge wie die folgenden haben:

um weitergeleitet
Quelle Ziel  
[E-Mail-geschützt] [E-Mail-geschützt] Leitet E-Mails für [email protected] an [email protected]
@example.com [E-Mail-geschützt] Erstellt ein Catch-All-Konto für [email protected] Alle E-Mails an example.com kommen bei [email protected] an, mit Ausnahme derjenigen, die in der Benutzertabelle vorhanden sind (d. h. wenn [email protected] existiert in In der Benutzertabelle werden E-Mails an [email protected] weiterhin bei [email protected] ankommen).
@example.com @anotherdomain.tld Hierdurch werden alle E-Mails an example.com an denselben Benutzer unter otherdomain.tld weitergeleitet. Beispielsweise werden E-Mails an [email protected] an [email protected]
[E-Mail-geschützt] [E-Mail-geschützt], [E-Mail-geschützt] E-Mails für [email protected] an zwei oder mehr E-Mail-Adressen weiterleiten. Alle unter Ziel aufgelisteten E-Mail-Adressen erhalten eine Kopie der E-Mail.

Die Transporttabelle kann folgende Einträge haben:

Domäne Transport  
beispiel.com : stellt E-Mails für example.com lokal zu. Dies ist so, als ob dieser Datensatz in dieser Tabelle überhaupt nicht vorhanden wäre.
beispiel.com smtp:mail.anotherdomain.tld Liefert alle E-Mails für example.com per SMTP an den Server mail.anotherdomain.com.
beispiel.com smtp:mail.anotherdomain.tld:2025 Liefert alle E-Mails für example.com über SMTP an den Server mail.anotherdomain.com, aber auf Port 2025, nicht 25, was der Standardport für SMTP ist.
beispiel.com

smtp:[1.2.3.4]
smtp:[1.2.3.4]:2025
smtp:[mail.anotherdomain.tld]

Die eckigen Klammern verhindern, dass Postfix den MX-DNS-Eintrag nach der Adresse in eckigen Klammern sucht. Sinnvoll bei IP-Adressen.
.example.com smtp:mail.anotherdomain.tld Mail für jede Subdomain von example.com wird an mail.anotherdomain.tld zugestellt.
* smtp:mail.anotherdomain.tld Alle E-Mails werden an mail.anotherdomain.tld zugestellt.
[E-Mail-geschützt] smtp:mail.anotherdomain.tld E-Mails für [email protected] werden an mail.anotherdomain.tld zugestellt.

Siehe

man transport 

für mehr Details.

Bitte beachten Sie, dass die Reihenfolge der Einträge in der Transporttabelle wichtig ist! Die Einträge werden von oben nach unten verfolgt.

Wichtig: Postfix verwendet einen Caching-Mechanismus für die Transporte, daher kann es eine Weile dauern, bis Ihre Änderungen in der Transporttabelle wirksam werden. Wenn Sie möchten, dass sie sofort wirksam werden, führen Sie

aus
postfix reload 

nachdem Sie Ihre Änderungen in der Transporttabelle vorgenommen haben.

14 Senden Sie eine Willkommens-E-Mail zum Erstellen von Maildir

Wenn Sie ein neues E-Mail-Konto erstellen und versuchen, E-Mails von dort abzurufen (mit POP3/IMAP), erhalten Sie wahrscheinlich Fehlermeldungen, die besagen, dass das Maildir nicht existiert. Das Maildir wird automatisch erstellt, wenn die erste E-Mail für das neue Konto eintrifft. Daher ist es eine gute Idee, eine Willkommens-E-Mail an ein neues Konto zu senden.

Zuerst installieren wir das mailx-Paket:

apt-get install mailutils

So senden Sie eine Willkommens-E-Mail an [email protected]:

mailx [email protected]

Sie werden nach dem Betreff gefragt. Geben Sie den Betreff ein (z. B. Willkommen), drücken Sie dann die EINGABETASTE, und geben Sie in der nächsten Zeile Ihre Nachricht ein. Wenn die Nachricht fertig ist, drücken Sie erneut die EINGABETASTE, sodass Sie sich in einer neuen Zeile befinden, und drücken Sie dann STRG+D; Wenn Sie die E-Mail nicht auf CC setzen möchten, drücken Sie erneut die EINGABETASTE:

[E-Mail-geschützt]:/usr/local/sbin# mailx [E-Mail-geschützt]
Cc:<-- ENTER
Betreff:Willkommen <-- ENTER
Willkommen! Viel Spaß mit Ihrem neuen Mailkonto. <-- EINGABE
<-- STRG+D
[email protected]:/usr/local/sbin#

15 Installation von SquirrelMail

SquirrelMail ist eine Webmail-Schnittstelle, mit der Ihre Benutzer E-Mails in einem Browser senden und empfangen können. Dieses Kapitel zeigt, wie man es installiert und an unser Setup anpasst, sodass Benutzer sogar das Passwort ihres E-Mail-Kontos über die SquirrelMail-Oberfläche ändern können.

Um SquirrelMail zu installieren, führen wir Folgendes aus:

apt-get install squirrelmail squirrelmail-compatibility php-pear php-db

Als nächstes verknüpfen wir die Apache-Konfiguration, die mit dem SquirrelMail-Paket geliefert wird, mit dem Verzeichnis /etc/apache2/conf.d und starten Apache neu:

ln -s /etc/squirrelmail/apache.conf /etc/apache2/conf.d/squirrelmail.conf
/etc/init.d/apache2 restart

SquirrelMail wird mit einigen vorinstallierten Plugins geliefert, leider ist keines davon in der Lage, uns unser E-Mail-Passwort in unserer MySQL-Datenbank ändern zu lassen. Aber es gibt das Plugin zum Ändern des SQL-Passworts, das wir manuell installieren können:

cd /usr/share/squirrelmail/plugins
wget http://www.squirrelmail.org/plugins/change_sqlpass-3.3-1.2.tar.gz
tar xvfz change_sqlpass-3.3-1.2.tar.gz
cd change_sqlpass
cp config.php.sample config.php

Nun müssen wir die config.php editieren und an unser Setup anpassen. Bitte passen Sie die Variablen $csp_dsn, $lookup_password_query, $password_update_queries, $password_encryption, $csp_salt_static und $csp_delimiter wie folgt an und kommentieren Sie $csp_salt_query aus:

vi config.php
[...]
$csp_dsn = 'mysql://mail_admin:[email protected]/mail';
[...]
$lookup_password_query = 'SELECT count(*) FROM users WHERE email = "%1" AND password = %4';
[...]
$password_update_queries = array('UPDATE users SET password = %4 WHERE email = "%1"');
[...]
$password_encryption = 'MYSQLENCRYPT';
[...]
$csp_salt_static = 'LEFT(password, 2)';
[...]
//$csp_salt_query = 'SELECT salt FROM users WHERE username = "%1"';
[...]
$csp_delimiter = '@';
[...]

Die vollständige Datei sieht wie folgt aus:

<?php

/**
  * SquirrelMail Change SQL Password Plugin
  * Copyright (C) 2001-2002 Tyler Akins
  *               2002 Thijs Kinkhorst <[email protected]>
  *               2002-2005 Paul Lesneiwski <[email protected]>
  * This program is licensed under GPL. See COPYING for details
  *
  * @package plugins
  * @subpackage Change SQL Password
  *
  */


   // Global Variables, don't touch these unless you want to break the plugin
   //
   global $csp_dsn, $password_update_queries, $lookup_password_query,
          $force_change_password_check_query, $password_encryption,
          $csp_salt_query, $csp_salt_static, $csp_secure_port,
          $csp_non_standard_http_port, $csp_delimiter, $csp_debug,
          $min_password_length, $max_password_length, $include_digit_in_password,
          $include_uppercase_letter_in_password, $include_lowercase_letter_in_password,
          $include_nonalphanumeric_in_password;



   // csp_dsn
   //
   // Theoretically, any SQL database supported by Pear should be supported
   // here.  The DSN (data source name) must contain the information needed
   // to connect to your database backend. A MySQL example is included below.
   // For more details about DSN syntax and list of supported database types,
   // please see:
   //   http://pear.php.net/manual/en/package.database.db.intro-dsn.php
   //
   //$csp_dsn = 'mysql://user:[email protected]/email_users';
   $csp_dsn = 'mysql://mail_admin:[email protected]/mail';


   // lookup_password_query
   //
   // This plugin will always verify the user's old password
   // against their login password, but an extra check can also
   // be done against the database for more security if you
   // desire.  If you do not need the extra password check,
   // make sure this setting is empty.
   //
   // This is a query that returns a positive value if a user
   // and password pair are found in the database.
   //
   // This query should return one value (one row, one column), the
   // value being ideally a one or a zero, simply indicating that
   // the user/password pair does in fact exist in the database.
   //
   //   %1 in this query will be replaced with the full username
   //      (including domain), such as "[email protected]"
   //   %2 in this query will be replaced with the username (without
   //      any domain portion), such as "jose"
   //   %3 in this query will be replaced with the domain name,
   //      such as "example.com"
   //   %4 in this query will be replaced with the current (old)
   //      password in whatever encryption format is needed per other
   //      plugin configuration settings (Note that the syntax of
   //      the password will be provided depending on your encryption
   //      choices, so you NEVER need to provide quotes around this
   //      value in the query here.)
   //   %5 in this query will be replaced with the current (old)
   //      password in unencrypted plain text.  If you do not use any
   //      password encryption, %4 and %5 will be the same values,
   //      except %4 will have double quotes around it and %5 will not.
   //
   //$lookup_password_query = '';
   // TERRIBLE SECURITY: $lookup_password_query = 'SELECT count(*) FROM users WHERE username = "%1" AND plain_password = "%5"';
   //$lookup_password_query = 'SELECT count(*) FROM users WHERE username = "%1" AND crypt_password = %4';
   $lookup_password_query = 'SELECT count(*) FROM users WHERE email = "%1" AND password = %4';


   // password_update_queries
   //
   // An array of SQL queries that will all be executed
   // whenever a password change attempt is made.
   //
   // Any number of queries may be included here.
   // The queries will be executed in the order given here.
   //
   //   %1 in all queries will be replaced with the full username
   //      (including domain), such as "[email protected]"
   //   %2 in all queries will be replaced with the username (without
   //      any domain portion), such as "jose"
   //   %3 in all queries will be replaced with the domain name,
   //      such as "example.com"
   //   %4 in all queries will be replaced with the new password
   //      in whatever encryption format is needed per other
   //      plugin configuration settings (Note that the syntax of
   //      the password will be provided depending on your
   //      encryption choices, so you NEVER need to provide quotes
   //      around this value in the queries here.)
   //   %5 in all queries will be replaced with the new password
   //      in unencrypted plain text - BEWARE!  If you do not use
   //      any password encryption, %4 and %5 will be the same
   //      values, except %4 will have double quotes around it
   //      and %5 will not.
   //
//   $password_update_queries = array(
//            'UPDATE users SET crypt_password = %4 WHERE username = "%1"',
//            'UPDATE user_flags SET force_change_pwd = 0 WHERE username = "%1"',
//            'UPDATE users SET crypt_password = %4, force_change_pwd = 0 WHERE username = "%1"',
//                                   );
   $password_update_queries = array('UPDATE users SET password = %4 WHERE email = "%1"');


   // force_change_password_check_query
   //
   // A query that checks for a flag that indicates if a user
   // should be forced to change their password.  This query
   // should return one value (one row, one column) which is
   // zero if the user does NOT need to change their password,
   // or one if the user should be forced to change it now.
   //
   // This setting should be an empty string if you do not wish
   // to enable this functionality.
   //
   //   %1 in this query will be replaced with the full username
   //      (including domain), such as "[email protected]"
   //   %2 in this query will be replaced with the username (without
   //      any domain portion), such as "jose"
   //   %3 in this query will be replaced with the domain name,
   //      such as "example.com"
   //
   //$force_change_password_check_query = 'SELECT IF(force_change_pwd = "yes", 1, 0) FROM users WHERE username = "%1"';
   //$force_change_password_check_query = 'SELECT force_change_pwd FROM users WHERE username = "%1"';
   $force_change_password_check_query = '';



   // password_encryption
   //
   // What encryption method do you use to store passwords
   // in your database?  Please use one of the following,
   // exactly as you see it:
   //
   //   NONE          Passwords are stored as plain text only
   //   MYSQLPWD      Passwords are stored using the MySQL password() function
   //   MYSQLENCRYPT  Passwords are stored using the MySQL encrypt() function
   //   PHPCRYPT      Passwords are stored using the PHP crypt() function
   //   MD5CRYPT      Passwords are stored using encrypted MD5 algorithm
   //   MD5           Passwords are stored as MD5 hash
   //
   //$password_encryption = 'MYSQLPWD';
   $password_encryption = 'MYSQLENCRYPT';


   // csp_salt_query
   // csp_salt_static
   //
   // Encryption types that need a salt need to know where to get
   // that salt.  If you have a constant, known salt value, you
   // should define it in $csp_salt_static.  Otherwise, leave that
   // value empty and define a value for the $csp_salt_query.
   //
   // Leave both values empty if you do not need (or use) salts
   // to encrypt your passwords.
   //
   // The query should return one value (one row, one column) which
   // is the salt value for the current user's password.  This
   // query is ignored if $csp_salt_static is anything but empty.
   //
   //   %1 in this query will be replaced with the full username
   //      (including domain), such as "[email protected]"
   //   %2 in this query will be replaced with the username (without
   //      any domain portion), such as "jose"
   //   %3 in this query will be replaced with the domain name,
   //      such as "example.com"
   //
   //$csp_salt_static = 'LEFT(crypt_password, 2)';
   //$csp_salt_static = '"a4"';  // use this format with MYSQLENCRYPT
   //$csp_salt_static = '$2$blowsomefish$';  // use this format with PHPCRYPT
   //$csp_salt_static = '';
   $csp_salt_static = 'LEFT(password, 2)';

   //$csp_salt_query = 'SELECT SUBSTRING_INDEX(crypt_password, '$', 1) FROM users WHERE username = "%1"';
   //$csp_salt_query = 'SELECT SUBSTRING(crypt_password, (LENGTH(SUBSTRING_INDEX(crypt_password, '$', 2)) + 2)) FROM users WHERE username = "%1"';
   //$csp_salt_query = 'SELECT salt FROM users WHERE username = "%1"';
   //$csp_salt_query = '';



   // csp_secure_port
   //
   // You may ensure that SSL encryption is used during password
   // change by setting this to the port that your HTTPS is served
   // on (443 is typical).  Set to zero if you do not wish to force
   // an HTTPS connection when users are changing their passwords.
   //
   // You may override this value for certain domains, users, or
   // service levels through the Virtual Host Login (vlogin) plugin
   // by setting a value(s) for $vlogin_csp_secure_port in the vlogin
   // configuration.
   //
   $csp_secure_port = 0;
   //$csp_secure_port = 443;



   // csp_non_standard_http_port
   //
   // If you serve standard HTTP web requests on a non-standard
   // port (anything other than port 80), you should specify that
   // port number here.  Set to zero otherwise.
   //
   // You may override this value for certain domains, users, or
   // service levels through the Virtual Host Login (vlogin) plugin
   // by setting a value(s) for $vlogin_csp_non_standard_http_port
   // in the vlogin configuration.
   //
   //$csp_non_standard_http_port = 8080;
   $csp_non_standard_http_port = 0;



   // min_password_length
   // max_password_length
   // include_digit_in_password
   // include_uppercase_letter_in_password
   // include_lowercase_letter_in_password
   // include_nonalphanumeric_in_password
   //
   // You can set the minimum and maximum password lengths that
   // you accept or leave those settings as zero to indicate that
   // no limit should be applied.
   //
   // Turn on any of the other settings here to check that the
   // new password contains at least one digit, upper case letter,
   // lower case letter and/or one non-alphanumeric character.
   //
   $min_password_length = 6;
   $max_password_length = 0;
   $include_digit_in_password = 0;
   $include_uppercase_letter_in_password = 0;
   $include_lowercase_letter_in_password = 0;
   $include_nonalphanumeric_in_password = 0;



   // csp_delimiter
   //
   // if your system has usernames with something other than
   // an "@" sign separating the user and domain portion,
   // specify that character here
   //
   //$csp_delimiter = '|';
   $csp_delimiter = '@';



   // debug mode
   //
   $csp_debug = 0;



?>

Now we must go into the SquirrelMail configuration and tell SquirrelMail that we use Courier as our POP3 and IMAP server and enable the Change SQL Password and the Compatibility plugins:

/usr/sbin/squirrelmail-configure

You'll see the following menu. Navigate through it as indicated:

SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1.  Organization Preferences
2.  Server Settings
3.  Folder Defaults
4.  General Options
5.  Themes
6.  Address Books
7.  Message of the Day (MOTD)
8.  Plugins
9.  Database
10. Languages

D.  Set pre-defined settings for specific IMAP servers

C   Turn color on
S   Save data
Q   Quit

Command >> <-- D


SquirrelMail Configuration : Read: config.php
---------------------------------------------------------
While we have been building SquirrelMail, we have discovered some
preferences that work better with some servers that don't work so
well with others.  If you select your IMAP server, this option will
set some pre-defined settings for that server.

Please note that you will still need to go through and make sure
everything is correct.  This does not change everything.  There are
only a few settings that this will change.

Please select your IMAP server:
    bincimap    = Binc IMAP server
    courier     = Courier IMAP server
    cyrus       = Cyrus IMAP server
    dovecot     = Dovecot Secure IMAP server
    exchange    = Microsoft Exchange IMAP server
    hmailserver = hMailServer
    macosx      = Mac OS X Mailserver
    mercury32   = Mercury/32
    uw          = University of Washington's IMAP server
    gmail       = IMAP access to Google mail (Gmail) accounts

    quit        = Do not change anything
Command >> <-- courier


              imap_server_type = courier
         default_folder_prefix = INBOX.
                  trash_folder = Trash
                   sent_folder = Sent
                  draft_folder = Drafts
            show_prefix_option = false
          default_sub_of_inbox = false
show_contain_subfolders_option = false
            optional_delimiter = .
                 delete_folder = true

Press enter to continue... <-- press ENTER


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1.  Organization Preferences
2.  Server Settings
3.  Folder Defaults
4.  General Options
5.  Themes
6.  Address Books
7.  Message of the Day (MOTD)
8.  Plugins
9.  Database
10. Languages

D.  Set pre-defined settings for specific IMAP servers

C   Turn color on
S   Save data
Q   Quit

Command >> <-- 8


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
  Installed Plugins
    1. view_as_html

  Available Plugins:
    2. administrator
    3. bug_report
    4. calendar
    5. change_sqlpass
    6. compatibility
    7. delete_move_next
    8. demo
    9. filters
    10. fortune
    11. info
    12. listcommands
    13. mail_fetch
    14. message_details
    15. newmail
    16. sent_subfolders
    17. spamcop
    18. squirrelspell
    19. test
    20. translate

R   Return to Main Menu
C   Turn color on
S   Save data
Q   Quit

Command >> <-- 6 (or whatever number the compatibility plugin has - it's needed by the change_sqlpass plugin)


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
  Installed Plugins
    1. view_as_html
    2. compatibility

  Available Plugins:
    3. administrator
    4. bug_report
    5. calendar
    6. change_sqlpass
    7. delete_move_next
    8. demo
    9. filters
    10. fortune
    11. info
    12. listcommands
    13. mail_fetch
    14. message_details
    15. newmail
    16. sent_subfolders
    17. spamcop
    18. squirrelspell
    19. test
    20. translate

R   Return to Main Menu
C   Turn color on
S   Save data
Q   Quit

Command >> <-- 6 (the number of the change_sqlpass plugin)


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
  Installed Plugins
    1. view_as_html
    2. compatibility
    3. change_sqlpass

  Available Plugins:
    4. administrator
    5. bug_report
    6. calendar
    7. delete_move_next
    8. demo
    9. filters
    10. fortune
    11. info
    12. listcommands
    13. mail_fetch
    14. message_details
    15. newmail
    16. sent_subfolders
    17. spamcop
    18. squirrelspell
    19. test
    20. translate

R   Return to Main Menu
C   Turn color on
S   Save data
Q   Quit

Command >> <-- S


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
  Installed Plugins
    1. view_as_html
    2. compatibility
    3. change_sqlpass

  Available Plugins:
    4. administrator
    5. bug_report
    6. calendar
    7. delete_move_next
    8. demo
    9. filters
    10. fortune
    11. info
    12. listcommands
    13. mail_fetch
    14. message_details
    15. newmail
    16. sent_subfolders
    17. spamcop
    18. squirrelspell
    19. test
    20. translate

R   Return to Main Menu
C   Turn color on
S   Save data
Q   Quit

Command >> S

Data saved in config.php
Press enter to continue... <-- press ENTER


SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Plugins
  Installed Plugins
    1. view_as_html
    2. compatibility
    3. change_sqlpass

  Available Plugins:
    4. administrator
    5. bug_report
    6. calendar
    7. delete_move_next
    8. demo
    9. filters
    10. fortune
    11. info
    12. listcommands
    13. mail_fetch
    14. message_details
    15. newmail
    16. sent_subfolders
    17. spamcop
    18. squirrelspell
    19. test
    20. translate

R   Return to Main Menu
C   Turn color on
S   Save data
Q   Quit

Command >> <-- Q

Now you can type in http://server1.example.com/squirrelmail or http://192.168.0.100/squirrelmail in your browser to access SquirrelMail.

Log in with your email address (e.g. [email protected]) and your password:

You should find the welcome email in your inbox:

To change your password, go to Options and then select Change Password:

Type in your current password and then your new password twice:

If the password has been changed successfully, you will see the following error message which means you must log in again with your new password (because the old one isn't active anymore):

16 VMA (Virtual Mail Admin Interface)

Virtual Mail Admin (VMA) is a small PHP-based web app written to manage the email system set up in this guide. I didn't test it, but I thought I'd share.

This is what the developer (Charl Loubser) wrote to me in an email:

"Hi There,

I don't know if you'll like this, or if this has any use to you, but I thought I'd Share:

I wrote a silly little webapp for the setup you did in the Howto:https://www.howtoforge.com/virtual-users-domains-postfix-courier-mysql-squirrelmail-ubuntu-10.04

If you approve and think it worthy of sharing on your tutorial, you are more than welcome, and can feel free to do so.

As mentioned in the readme, this is not a perfect app, but it does the job for now, and I'd thing it's relatively safe in a closed environment (LAN setup between servers).

The rar file with the app is attached, but can also be downloaded at :http://code.google.com/p/vma/"


17 References

  • Tutorial:ISP-style Email Service with Debian-Sarge and Postfix 2.1:http://workaround.org/articles/ispmail-sarge/
  • Postfix + Quota:http://vhcs.net/new/modules/newbb/viewtopic.php?topic_id=3496&forum=17
  • Mail Passwords Encrypted using saslauthd:http://www.syscp.de/docs/public/contrib/cryptedmailpws

  • Postfix MTA:http://www.postfix.org/
  • Postfix Quota Patch:http://web.onda.com.br/nadal/
  • phpMyAdmin:http://www.phpmyadmin.net/
  • SquirrelMail:http://www.squirrelmail.org/
  • Ubuntu:http://www.ubuntu.com/
  • Virtual Mail Admin Interface (VMA):http://code.google.com/p/vma/

Ubuntu
  1. Virtuelle Benutzer und Domänen mit Postfix, Courier, MySQL und SquirrelMail (Ubuntu 14.04LTS)

  2. Virtuelle Benutzer und Domains mit Postfix, Courier, MySQL und SquirrelMail (Ubuntu 13.10)

  3. Ubuntu 16.04 (LTS) LAMP-Server-Tutorial mit Apache, PHP 7 und MySQL

  4. Virtuelle Benutzer und Domänen mit Sendmail

  5. Mailserver mit virtuellen Benutzern und Domains mit Postfix und Dovecot auf einem CentOS 6 VPS

Virtuelle Benutzer und Domains mit Postfix, Courier, MySQL und SquirrelMail (Ubuntu 12.10)

Virtuelles Hosting mit vsftpd und MySQL auf Ubuntu 12.10

Virtuelles Hosting mit Proftpd und MySQL (inkl. Quote) auf Ubuntu 12.10

Virtuelle Benutzer und Domains mit Postfix, Courier, MySQL und SquirrelMail (Debian Wheezy)

Virtuelle Benutzer und Domains mit Postfix, Courier, MySQL und SquirrelMail (CentOS 6.3 x86_64)

Virtuelle Benutzer und Domänen mit Postfix, Courier, MySQL und SquirrelMail (Fedora 18 x86_64)