57
Serveur Mail Postfix, Amavisd, Mysql, Spamassassin, Dspam, Courier-IMAP DEBIAN ETCH/LENNY Le système sur lequel est basé ce document est une DEBIAN Testing (Lenny). La version Stable (Etch) à la date de rédaction présente quelques differences sur certain paquets (changement de nom lors des montées de version : voir le site debian pour les versions equivalentes) mais cela n’entraine aucun probleme dans les fonctionnalités. Ce tuto fonctionne aussi sous Ubuntu mais certains paquets présentent de légères différences. On essaiera de les indiquer si possible. On prendra comme base pour l’exemple le domaine starbridge.org et le hostname du serveur de mail sera spike. On met le système à jour aptitude update aptitude dist-upgrade On vérifie les fichiers : /etc/hostname : spike.starbridge.org /etc/hosts : 127.0.0.1 starbridge.org spike.starbridge.org localhost.localdomain localhost spike Cache DNS Local Le fonctionnement d’un serveur de mail nécessite l’utilisation intensive de requètes DNS. Pour des raisons de performances, il est très fortement conseillé d’installer un cache DNS local. aptitude install bind9 La configuration de base sous Debian fournie un serveurcache (on peut bien sur le configurer pour gérer son domaine local voire son domaine public mais ce n’est pas le sujet de cet article). On modifie le /etc/resolv.conf pour pointer en local : nameserver 127.0.0.1 search starbridge.org on relance le serveur DNS : /etc/init.d/bind9 restart Puis on teste la résolution avec nslookup ou dig nslookup >server doit retourner : Default server: 127.0.0.1 Address: 127.0.0.1#53 puis : > yahoo.fr La résolution doit se faire correctement. Postfix et Mysql

Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Serveur Mail Postfix, Amavisd, Mysql, Spamassassin, Dspam, Courier-IMAP

DEBIAN ETCH/LENNY

Le système sur lequel est basé ce document est une DEBIAN Testing (Lenny). La version Stable (Etch) à la date de rédaction présente quelques differences sur certain paquets (changement de nom lors des montées de version : voir le site debian pour les versions equivalentes) mais cela n’entraine aucun probleme dans les fonctionnalités.Ce tuto fonctionne aussi sous Ubuntu mais certains paquets présentent de légères différences. On essaiera de les indiquer si possible.

On prendra comme base pour l’exemple le domaine starbridge.org et le hostname du serveur de mail sera spike.

On met le système à jouraptitude updateaptitude dist-upgradeOn vérifie les fichiers :

• /etc/hostname :spike.starbridge.org

• /etc/hosts :127.0.0.1 starbridge.org spike.starbridge.org localhost.localdomain localhost spike

Cache DNS Local

Le fonctionnement d’un serveur de mail nécessite l’utilisation intensive de requètes DNS. Pour des raisons de performances, il est très fortement conseillé d’installer un cache DNS local.aptitude install bind9La configuration de base sous Debian fournie un serveur cache (on peut bien sur le configurer pour gérer son domaine local voire son domaine public mais ce n’est pas le sujet de cet article).On modifie le /etc/resolv.conf pour pointer en local :nameserver 127.0.0.1search starbridge.org

on relance le serveur DNS :/etc/init.d/bind9 restartPuis on teste la résolution avec nslookup ou dignslookup >serverdoit retourner :Default server: 127.0.0.1Address: 127.0.0.1#53puis :> yahoo.frLa résolution doit se faire correctement.

Postfix et Mysql

Page 2: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

aptitude install postfix postfix-mysql mysql-client-5.0 mysql-server-5.0 courier-imap courier-imap-ssl courier-authdaemon courier-authlib-mysql libsasl2-2 libsasl2-modules sasl2-bin libpam-mysql openssl ntp fam tmpreaperD’autre paquets vont s’installer en même temps. L’ancien MTA exim4 sera desintallé.

Note : pour les questions de l’installeur Debian :• courier-base : Faut-il créer les répertoires nécessaires à l’administration web = NON.• postfix configuration : SITE INTERNET. Pour le reste on repond par défaut.

On installe apache + php5 pour gérer plus tard le tout avec l’interface postfixadmin.aptitude install apache2 libapache2-mod-php5 php5-mysql

Note : Il est fortement conseillé d’installer le SSL avec apache pour sécuriser les échanges. Cette configuration sera détaillé plus loin lors de l’installation de postfixadmin.Pour ceux qui le préfère, on peut tout de suite installer phpmyadmin pour effectuer l’étape suivante. (on ne détaillera pas cette installation, en dehors du scope de ce document)

On passe donc à la création de la base Postfix :Note : Si l’on a mis un password lors de l’installation du paquets mysql, il faut sauter la premiere commande ci dessous et exécuter directement la seconde.mysqladmin -u root password 'your password'mysqladmin -u root --password='<your password>' create postfixCréation de l’user postfix :$ mysql -u root -pEnter password:GRANT ALL PRIVILEGES ON postfix.* TO "postfix"@"localhost" IDENTIFIED BY 'password';On crée les tables suivantes dans la base postfix :USE postfix;CREATE TABLE admin ( username varchar(255) NOT NULL default '', password varchar(255) NOT NULL default '', created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (username)) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Admins';

## Table structure for table alias#CREATE TABLE alias ( address varchar(255) NOT NULL default '', goto text NOT NULL, domain varchar(255) NOT NULL default '', created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (address)) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Aliases';

## Table structure for table domain#CREATE TABLE domain ( domain varchar(255) NOT NULL default '', description varchar(255) NOT NULL default '', aliases int(10) NOT NULL default '0',

Page 3: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

mailboxes int(10) NOT NULL default '0', maxquota int(10) NOT NULL default '0', quota int(10) NOT NULL default '0', transport varchar(255) default NULL, backupmx tinyint(1) NOT NULL default '0', created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (domain)) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Domains';

## Table structure for table domain_admins#CREATE TABLE domain_admins ( username varchar(255) NOT NULL default '', domain varchar(255) NOT NULL default '', created datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', KEY username (username)) TYPE=MyISAM COMMENT='Postfix Admin - Domain Admins';

## Table structure for table log#CREATE TABLE log ( timestamp datetime NOT NULL default '0000-00-00 00:00:00', username varchar(255) NOT NULL default '', domain varchar(255) NOT NULL default '', action varchar(255) NOT NULL default '', data varchar(255) NOT NULL default '', KEY timestamp (timestamp)) TYPE=MyISAM COMMENT='Postfix Admin - Log';

## Table structure for table mailbox#CREATE TABLE mailbox ( username varchar(255) NOT NULL default '', password varchar(255) NOT NULL default '', name varchar(255) NOT NULL default '', maildir varchar(255) NOT NULL default '', quota varchar(20) NOT NULL default '0', domain varchar(255) NOT NULL default '', created datetime NOT NULL default '0000-00-00 00:00:00', modified datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '1', PRIMARY KEY (username)) TYPE=MyISAM COMMENT='Postfix Admin - Virtual Mailboxes';

## Table structure for table vacation#CREATE TABLE vacation ( email varchar(255) NOT NULL default '', subject varchar(255) NOT NULL default '', body text NOT NULL, cache text NOT NULL, domain varchar(255) NOT NULL default '', created datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(4) NOT NULL default '1', PRIMARY KEY (email)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci TYPE=InnoDB COMMENT='Postfix Admin - Virtual Vacation' ;

Page 4: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

## vacation_notification table #CREATE TABLE vacation_notification ( on_vacation varchar(255) NOT NULL, notified varchar(255) NOT NULL, notified_at timestamp NOT NULL default now(), CONSTRAINT vacation_notification_pkey PRIMARY KEY(on_vacation, notified), FOREIGN KEY (on_vacation) REFERENCES vacation(email) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci TYPE=InnoDB COMMENT='Postfix Admin - Virtual Vacation Notifications';

##Création d'un utilisateur manuellement#INSERT INTO domain (domain,description) VALUES ('starbridge.org','Test Domain');INSERT INTO alias (address,goto,domain) VALUES ('[email protected]', '[email protected]','starbridge.org');INSERT INTO alias (address,goto,domain) VALUES ('[email protected]', '[email protected]','starbridge.org');INSERT INTO alias (address,goto,domain) VALUES ('[email protected]', '[email protected]','starbridge.org');INSERT INTO alias (address,goto,domain) VALUES ('[email protected]', '[email protected]','starbridge.org');INSERT INTO alias (address,goto,domain) VALUES ('[email protected]', '[email protected]','starbridge.org');INSERT INTO mailbox (username,password,name,maildir,domain) VALUES ('[email protected]','$1$caea3837$gPafod/Do/8Jj5M9HehhM.','Mailbox User','[email protected]/','starbridge.org');INSERT INTO mailbox (username,password,name,maildir,domain) VALUES ('[email protected]','$1$caea3837$gPafod/Do/8Jj5M9HehhM.','Mailbox Admin','[email protected]/','starbridge.org');INSERT INTO domain_admins (username, domain, active) VALUES ('[email protected]','ALL','1');INSERT INTO `admin` (`username`, `password`, `created`, `modified`, `active`) VALUES ('[email protected]', '$1$caea3837$gPafod/Do/8Jj5M9HehhM.', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1);

Note : Seules 3 tables sont nécessaires à Postfix. Le reste est pour l’interface postfixadmin que l’on installera plus tard.

Le password (MD5) est "secret" ($1$caea3837$gPafod/Do/8Jj5M9HehhM.)Le premier INSERT permet à Postfix de savoir que ce domaine est virtuel et qu’il doit donc le gérer.Le 3ème INSERT est un alias virtuel poitant vers un user de la table mailbox. Cet alias vers lui même sera utilisé par postfixadmin.le 4ème INSERT est lui un simple alias virtuel.Le 7ème INSERT est un compte (boite email) virtuel, qui utilise un mot de passe encrypté en MD5.Les deux derniers INSERT permettent de créer le superadministrateur que l’on utilisera plus tard dans postfixadmin

Paramétrage de Postfix

Note : on remarquera que l’on laisse Postfix chrooté (plus secure) et que l’on utilise le daemon proxy pour communiquer avec le socket de mysql.

On remplace tout le /etc/postfix/main.cf par le contenu ci dessous :smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)biff = noappend_dot_mydomain = nomyhostname = spike.starbridge.orgalias_maps = hash:/etc/aliasesalias_database = hash:/etc/aliasesmyorigin = starbridge.orgmydestination = localhost.localdomain, localhostmynetworks = 127.0.0.0/8

Page 5: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

mailbox_command = /usr/bin/procmail -a "$EXTENSION"mailbox_size_limit = 0recipient_delimiter = +best_mx_transport = locallocal_transport = localhome_mailbox = Maildir/ notify_classes = 2bounce, bounce, delay, policy, protocol, resource, softwaremasquerade_domains = starbridge.orgsmtpd_helo_required = yesstrict_rfc821_envelopes = yesvirtual_alias_maps = proxy:mysql:/etc/postfix/mysql_virtual_alias_maps.cfvirtual_gid_maps = static:20001virtual_mailbox_base = /home/virtualvirtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql_virtual_domains_maps.cfvirtual_mailbox_limit = 51200000virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql_virtual_mailbox_maps.cfvirtual_minimum_uid = 20001virtual_uid_maps = static:20001proxy_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 $smtpd_recipient_restrictions $smtpd_sender_login_mapsmessage_size_limit = 50240000smtpd_recipient_restrictions =

permit_mynetworks, reject_unauth_destination, permit

smtpd_data_restrictions = reject_unauth_pipelining, permit

On modifie le /etc/postfix/master.cf comme ci dessous (c’est le meme que l’original de l’installeur debian sauf pour le pickup) :## Postfix master process configuration file. For details on the format# of the file, see the master(5) manual page (command: "man 5 master").## ==========================================================================# service type private unpriv chroot wakeup maxproc command + args# (yes) (yes) (yes) (never) (100)# ==========================================================================smtp inet n - - - - smtpd#submission inet n - - - - smtpd# -o smtpd_enforce_tls=yes# -o smtpd_sasl_auth_enable=yes# -o smtpd_client_restrictions=permit_sasl_authenticated,reject#smtps inet n - - - - smtpd# -o smtpd_tls_wrappermode=yes# -o smtpd_sasl_auth_enable=yes# -o smtpd_client_restrictions=permit_sasl_authenticated,reject#628 inet n - - - - qmqpdpickup fifo n - - 60 1 pickup -o receive_override_options=no_header_body_checks -o content_filter=cleanup unix n - - - 0 cleanupqmgr fifo n - n 300 1 qmgr#qmgr fifo n - - 300 1 oqmgrtlsmgr unix - - - 1000? 1 tlsmgrrewrite unix - - - - - trivial-rewritebounce unix - - - - 0 bouncedefer unix - - - - 0 bouncetrace unix - - - - 0 bounceverify unix - - - - 1 verifyflush unix n - - 1000? 0 flushproxymap unix - - n - - proxymap

Page 6: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

smtp unix - - - - - smtp# When relaying mail as backup MX, disable fallback_relay to avoid MX loopsrelay unix - - - - - smtp -o fallback_relay=# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5showq unix n - - - - showqerror unix - - - - - errorretry unix - - - - - errordiscard unix - - - - - discardlocal unix - n n - - localvirtual unix - n n - - virtuallmtp unix - - - - - lmtpanvil unix - - - - 1 anvilscache unix - - - - 1 scache## ====================================================================# Interfaces to non-Postfix software. Be sure to examine the manual# pages of the non-Postfix software to find out what options it wants.## Many of the following services use the Postfix pipe(8) delivery# agent. See the pipe(8) man page for information about ${recipient}# and other message envelope options.# ====================================================================## maildrop. See the Postfix MAILDROP_README file for details.# Also specify in main.cf: maildrop_destination_recipient_limit=1#maildrop unix - n n - - pipe flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}## See the Postfix UUCP_README file for configuration details.#uucp unix - n n - - pipe flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)## Other external delivery methods.#ifmail unix - n n - - pipe flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)bsmtp unix - n n - - pipe flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipientscalemail-backend unix - n n - 2 pipe flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}mailman unix - n n - - pipe flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py ${nexthop} ${user}

On crée le dossier des mails :mkdir /home/virtualOn crée le groupe et le user vmail avec l’uid et gid 20001 :groupadd -g 20001 vmailuseradd -g vmail -u 20001 vmail -d /home/vmail -mOn sécurise :chown -R vmail: /home/virtualchmod 770 /home/virtualOn crée les fichiers d’appel des tables par Postfix :vi /etc/postfix/mysql_virtual_alias_maps.cfet on colle :user = postfixpassword = ****hosts = localhostdbname = postfixquery = SELECT goto FROM alias WHERE address='%s' and active = '1'

Page 7: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

vi /etc/postfix/mysql_virtual_domains_maps.cfuser = postfixpassword = ****hosts = localhostdbname = postfixquery = SELECT domain FROM domain WHERE domain='%s' and active = '1'

vi /etc/postfix/mysql_virtual_mailbox_maps.cfuser = postfixpassword = ****hosts = localhostdbname = postfixquery = SELECT maildir FROM mailbox WHERE username='%s' and active = '1'

On sécurise le tout :chmod 640 /etc/postfix/mysql_*chgrp postfix /etc/postfix/mysql_*

Maildrop

Nous avons besoin d’un MDA (mail delivery agent) pour livrer les mails dans les boîtes. Le service de livraison Virtual de Postfix ne convient pas totalement pour notre usage. En effet nous allons avoir besoin de capacité de filtrage sur le MDA ainsi que la possibilité de gérer les quotas, ce que ne sait pas faire Virtual. Procmail est très bien pour le filtrage, mais ne supporte pas les users/domaines virtuels car il ne sait pas communiquer avec une base de données. Une méthode répandue pour les quotas est l’application du patch VDA sur Postfix, option que nous ne choisirons pas pour des raisons de fiabilité.Maildrop répond lui à nos besoins :Il s’occupera donc de la livraison des mails dans les home.On installe d’abord les outils pour la compilation :aptitude install bzip2 gcc libpcre3-dev libpcre++-dev courier-authlib-dev g++ libtool libmysqlclient15-dev makeOn télécharge les sources :wget http://heanet.dl.sourceforge.net/sourceforge/courier/maildrop-2.0.4.tar.bz2tar jxf maildrop-2.0.4.tar.bz2cd maildrop-2.0.4 ./configure -prefix=/usr/local/courier --with-etcdir=directory=/etc/courier --enable-maildrop-uid=20001 --enable-maildrop-gid=20001 --enable-maildirquota --without-dbmake && make install

Notes : Le ./configure est particulièrement long et donne l’impression de tourner en boucle. Ceci est

normal, il faut attendre la fin du processus. A la fin du make avec la version 2.0.4, il se peut que l’on obtienne un message d’erreur sur

un des composants. Meme si cela n’empechera pas Maildrop de fonctionner on peut régler le probleme comme ceci :cd makedatln -s makedatprog.c makedatprogcd ..make install

Page 8: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On applique les permissions correctement sur les exécutables puis on fait un chmod 775 sur le répertoire /var/run/courier (juste le répertoire) et sur /var/run/courier/authdaemaon (que le dossier) :chown vmail: /usr/local/courier/bin/*chmod 775 /var/run/courier/chmod 775 /var/run/courier/authdaemon/

Note : sous ubuntu il faudra aussi modifier le fichier /etc/init.d/courier-authdaemon et modifier le 750 dans

chmod 750 ${run_dir} par 775

On vérifie si maildrop est correctement installé (modules activés) :/usr/local/courier/bin/maildrop -vdevrait donner :maildrop 2.0.4 Copyright 1998-2005 Double Precision, Inc.Courier Authentication Library extension enabled.Maildir quota extension enabled.This program is distributed under the terms of the GNU General PublicLicense. See COPYING for additional information.On voit que l’authentification est activée, ainsi que la gestion des quotas que nous configurerons plus tard.On édite le fichier /etc/courier/authdaemonrcil faut remplacer authmodulelist="authpam" par authmodulelist="authpam authmysql"On édite le /etc/courier/authmysqlrcMYSQL_SERVER localhostMYSQL_USERNAME postfixMYSQL_PASSWORD xxxxxxMYSQL_SOCKET /var/run/mysqld/mysqld.sockMYSQL_PORT 3306MYSQL_OPT 0MYSQL_DATABASE postfixMYSQL_USER_TABLE mailboxMYSQL_CRYPT_PWFIELD passwordMYSQL_UID_FIELD '20001'MYSQL_GID_FIELD '20001'MYSQL_LOGIN_FIELD usernameMYSQL_HOME_FIELD '/home/virtual'MYSQL_NAME_FIELD nameMYSQL_MAILDIR_FIELD maildirMYSQL_QUOTA_FIELD concat(quota,'S')

Il faut faire très attention à la syntaxe de ce fichier et bien mettre un tab entre le paramètre et sa valeur. Il ne doit y avoir aucun espace à la fin d’un paramètre. La moindre erreur entrainera le non fonctionnement de l’authentification.On sécurise :chmod 640 /etc/courier/authmysqlrcMaildrop est appelé par Postfix au moment de la livraison. Pour que Postfix utilise Maildrop, on ajoute au main.cf :virtual_transport = maildropmaildrop_destination_recipient_limit = 1

et au master.cf (on efface la ligne maildrop existante et on la remplace par celle ci):maildrop unix - n n - - pipe flags=DRhu user=vmail argv=/usr/local/courier/bin/maildrop -w 90 -d ${user}@${nexthop} ${extension} ${recipient} ${user} ${nexthop} ${sender}

On crée /home/virtual/.mailfilter pour activer les logs et la création automatique des maildir à la livraison (postfix ne sait pas le faire comme avec le transport par défaut "virtual", car ce n’est pas lui livre directement dans les répertoires) :vi /home/virtual/.mailfilter

Page 9: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

et on colle :logfile "/home/virtual/.maildrop.log" `[ -d $DEFAULT ] || (maildirmake $DEFAULT && maildirmake -f Spam $DEFAULT && maildirmake -f sent-mail $DEFAULT && maildirmake -f SpamToLearn $DEFAULT && maildirmake -f SpamFalse $DEFAULT)`

`test -r $HOME/$DEFAULT.mailfilter`if( $RETURNCODE == 0 ) { log "(==) Including $HOME/$DEFAULT.mailfilter" exception { include $HOME/$DEFAULT.mailfilter } }

On sécurise ce fichier :chown vmail: /home/virtual/.mailfilterchmod 600 /home/virtual/.mailfilter on redémarre le daemon d’authentification et Postfix/etc/init.d/courier-authdaemon restart/etc/init.d/postfix restartOn teste cette première configuration de base :authtest [email protected] donner :Authentication succeeded. Authenticated: [email protected] (uid 20001, gid 20001) Home Directory: /home/virtual Maildir: [email protected]/ Quota: 0SEncrypted Password: $1$caea3837$gPafod/Do/8Jj5M9HehhM.Cleartext Password: (none) Options: (none)En cas d’erreur, il est fort problable que le fichier authmysqlrc soit en cause.Regarder les log /var/log/mail.log.puis :/usr/local/courier/bin/maildrop -V 7 -d [email protected] devrait donner :maildrop: authlib: groupid=20001maildrop: authlib: userid=20001maildrop: authlib: [email protected], home=/home/virtual, [email protected]/maildrop: Changing to /home/virtualCTRL + C pour sortirOn vérifie que l’on peut envoyer un mail à [email protected] :mail [email protected] : il faut taper un . (un point) pour terminer le message.On regarde les logs pour les erreurs. Si tout a fonctionné on devrait trouver dans une ligne :...status=sent (delivered via maildrop service)...

Note : si la commande mail n’existe pas sur le système (Ubuntu par exemple) l’installer avec aptitude install mailx

Puis on teste en direct sur le port 25 :(ce qu’il faut taper est précédé de --->, le reste c’est le retour du serveur) :

Page 10: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

---> telnet localhost 25220 [127.0.0.1] ESMTP Postfix---> HELO localhost250 [127.0.0.1]---> MAIL FROM: <>250 2.1.0 Sender OK---> RCPT TO: <[email protected]> 250 2.1.5 OK---> DATA354 End data with <CR><LF>.<CR><LF>---> .250 2.0.0 Ok: queued as 079474CE44---> QUIT221 2.0.0 ByeConnection closed by foreign host

On regarde les logs pour vérifier.

Note : Le fichier .mailfilter crée plus haut est commun à tous les comptes et sera appliqué à chaque mail. Si l’on veut appliquer des règles spécifiques à un utilisateur, il suffit de créer un autre fichier .mailfilter dans son Maildir. On pourra par exemple rediriger des emails dans des répertoires spécifiques de cette facon. On verra dans un autre article comment paramétrer le webmail Horde pour générer ces fichiers personnels.

Exemple de fichier .mailfilter personnel :#elimine les messages en provenance de l'adresse ci-dessous if( \ /^From: .*actu@b\.linternaute\.com/:h \ ) exception { to "/dev/null" }

##### annonces ##### if( \ /^From: .*alerte@avendrealouer\.fr/:h \ || /^From: .*mailing_pap@pap\.fr/:h \ || /^Sender: .*alertemail@pap\.fr/:h \ ) exception { to "${DEFAULT}/.annonces/" }

Note : Pour la création assistée et autonome (par les utilisateurs eux-memes) des fichiers mailfilter personnels on pourra utiliser un module du Webmail horde. L’article sur l’installation du Webmail traite en détail de ce point .

Courier-Imap

On a déjà configuré la partie la plus importante de courier-imap, c’est à dire l’authentification mysql, dans la partie sur Maildrop.On va simplement ajouter une fonctionnalité très utile à Courier-IMAP : le ENHANCEDIDLECela permet de rafraichir en temps réel la boîte de réception dans le client de messagerie sans besoin de la planifier ou autre.Un nouveau message apparaitra instantanément dans le client.

Page 11: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Attention :• il faut que le client de messagerie supporte cette fonction. C’est le cas d’Outlook et de

Thunderbird.• Pour fonctionner cette fonction utilise FAM, le File Alteration Monitor.

Sur des serveurs avec de très nombreuses boîtes email cela peut être un problème pour les performances. Il faut donc activer cette fonction en connaissance de cause et surveiller la charge au fil du temps. De plus FAM a tendance à planter sur de très grosses manipulations sur les boîtes (avec plusieurs milliers de mail). Dans ce cas de figure, Courier-Imap continuera à fonctionner sans problème (mais sans le temps réel bien sur) et des messages d’erreurs apparaitront dans mail.log jusqu’au redémarrage de FAM. Il peut donc être judicieux de surveiller le process FAM et de le relancer automatiquement en cas d’arrêt. (un module Webmin fait cela très correctement)

Pour activer la fonction, rechercher ces paramètres dans /etc/courier/imapd et mettre leur valeur à 1 (IMAP_USELOCKS devrait déjà être sur 1 par défaut)IMAP_USELOCKS=1IMAP_ENHANCEDIDLE=1On redémarre ensuite le daemon d’authentification et courier-imap :/etc/init.d/courier-authdaemon restart/etc/init.d/courier-imap restartPour activer le SSL sur l’imap, il faut simplement lancer le daemon courier-imap-ssl, la création du certificat ayant été faite automatiquement lors de l’installation par les paquets Debian./etc/init.d/courier-imap-ssl restartOn teste la connection depuis un client mail (outlook, thunderbird..)Ne pas oublier de spécifier [email protected] comme login de la boite et non ’user’ tout seul.On rappelle que le password est ’secret’.Paramétrer le SMTP sans authentification pour le moment.On doit pouvoir consulter les mail envoyés localement tout à l’heure.On teste un envoi de mail depuis le client sur sa propre adresse. On vérifie les logs et l’arrivée du nouveau mail dans la boîte.

Notes : Par défaut IMAP est configuré pour démarrer au maximum 40 serveurs IMAP. Cela

permettra à 40 utilisateurs de se connecter simultanément. (MAXDAEMONS=40) Par défault, il limite également à 20 le nombre d’utilisateurs simultanés depuis la même IP. (MAXPERIP=20)On modifiera donc ces paramètres en fonction du nombre de boites email. /etc/courier/imapd contient des paramètres généraux de configuration qui s’appliqueront

également à imap-ssl. (par exemple le ENHANCEDIDLE). Cependant le nombre de daemons et de connections par IP se configure indépendamment dans /etc/courier/imapd et /etc/courier/imapd-ssl.

Authentification SASL

Pour le moment Postfix utilise l’adresse IP du client qui se connecte pour déterminer si il peut relayer ou non les mails (ou accepter seulement des mails pour les users locaux).Pour pouvoir utiliser son serveur mail depuis l’extérieur (cas des laptops) on doit permettre une authentification sécurisée :On crée le fichier /etc/pam.d/smtp :vi /etc/pam.d/smtpet on colle le contenu suivant :

Page 12: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

auth required pam_mysql.so user=postfix passwd=yourpass host=127.0.0.1 db=postfix table=mailbox usercolumn=username passwdcolumn=password crypt=1 md5=1

"yourpass" est le password d’accès à la table Postfix par le user postfixOn sécurise ce fichier car le password est stocké en clair :chmod 640 /etc/pam.d/smtpOn crée le fichier /etc/postfix/sasl/smtpd.conf :vi /etc/postfix/sasl/smtpd.confet on colle le contenu suivant :pwcheck_method: saslauthdmech_list: PLAIN LOGINlog_level: 5

On édite le /etc/default/saslauthd comme ceci (ne pas modifier les autres paramètres déjà présents dans le fichier original) :START=yesMECHANISMS="pam"OPTIONS="-c -r -m /var/spool/postfix/var/run/saslauthd"

On crée le répertoire du socket et on lui donne les droits adaptés :mkdir /var/spool/postfix/var/ mkdir /var/spool/postfix/var/run/ mkdir /var/spool/postfix/var/run/saslauthdchown -R root:sasl /var/spool/postfix/var/chmod 710 /var/spool/postfix/var/run/saslauthdadduser postfix saslOn crée un lien symbolique au cas où :ln -s /var/spool/postfix/var/run/saslauthd /var/run/saslauthdOn ajoute ceci au /etc/postfix/main.cf :smtpd_sasl_auth_enable = yessmtpd_sasl_security_options = noanonymoussmtpd_sasl_local_domain = broken_sasl_auth_clients = yessmtpd_sasl_authenticated_header = yes

On ajoute également "permit_sasl_authenticated" dans "smtpd_recipient_restrictions" pour valider les restrictions (attention à bien placer le paramètre exactement à l’endroit indiqué) :.....permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination,......

On édite /etc/init.d/postfix, on recherche la variable FILES et on ajoute etc/postfix/sasl/smtpd.conf à la liste :FILES="etc/localtime etc/services etc/resolv.conf etc/hosts \ etc/nsswitch.conf etc/nss_mdns.config etc/postfix/sasl/smtpd.conf"

On redémarre Postfix et Saslauthd :/etc/init.d/postfix restart/etc/init.d/saslauthd restartOn vérifie que les paramètres sont bien passés au daemon Saslauthd :ps waux | grep saslauthddoit donner plusieurs lignes avec comme paramètres :/usr/sbin/saslauthd -a pam -c -r -m /var/spool/postfix/var/run/saslauthd -n 5

Page 13: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Activation du TLS

On crée le certificat SSL :mkdir /etc/postfix/tlscd /etc/postfix/tlsopenssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024openssl req -new -key smtpd.key -out smtpd.csr

Note : le paramètre le plus important est le Common Name qui doit être le nom de domaine de votre serveur de mail : starbridge.org

On laisse "challenge password" vide.openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out smtpd.crt openssl rsa -in smtpd.key -out smtpd.key.unencrypted mv -f smtpd.key.unencrypted smtpd.key openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650 On sécurise :chmod 400 /etc/postfix/tls/*On ajoute ceci au /etc/postfix/main.cf :smtp_tls_security_level = maysmtpd_tls_security_level = maysmtpd_tls_auth_only = yessmtpd_tls_key_file = /etc/postfix/tls/smtpd.keysmtpd_tls_cert_file = /etc/postfix/tls/smtpd.crtsmtpd_tls_CAfile = /etc/postfix/tls/cacert.pemsmtpd_tls_loglevel = 1smtpd_tls_received_header = yessmtpd_tls_session_cache_timeout = 3600stls_random_source = dev:/dev/urandom

On redémarre Postfix :/etc/init.d/postfix restartOn vérifie le fonctionnement depuis un client mail configuré pour l’authentification SASL sur un chiffrement TLS avec les mêmes identifiants que pour la connection IMAP (ne pas oublier le @starbridge.org).Pour le type d’authentication, il faut sélectionner "en clair" (le terme dépend du client mail).C’est le chiffrage de la connection par le TLS qui sécurisera le transfert du password.C’est pour cela qu’il ne faut pas dissocier TLS et authentification.

Note : la directive smtpd_tls_auth_only = yes impose l’usage d’une connection sécurisée pour l’authentification SASL, ce qui limitera les erreurs de configuration des utilisateurs.

Installation PostfixAdmin

Pour faciliter la création des users et la gestion des boîtes et des comptes, on utilise postfixadmin.La dernière version est la 2.1.0 mais elle présente de nombreux bugs. Nous utiliserons la version SVN.Activation du SSL dans ApacheLe SSL est indispensable pour sécuriser les échanges, en particulier les mots de passe utilisateurs.On active le SSL par la commande :a2enmod sslPuis on crée le virtual host:vi /etc/apache2/sites-available/ssl

Page 14: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Et on colle :NameVirtualHost *:443<VirtualHost *:443> ServerAdmin [email protected] ServerName www.starbridge.org DocumentRoot /var/www/ <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all # This directive allows us to have apache2's default start page # in /apache2-default/, but still have / go to the right place # Commented out for Ubuntu #RedirectMatch ^/$ /apache2-default/ </Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None AllowOverride AuthConfig Options ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn

CustomLog /var/log/apache2/access.log combined ServerSignature On

SSLEngine OnSSLCertificateFile /etc/apache2/ssl/starbridge.crtSSLCertificateKeyFile /etc/apache2/ssl/starbridge.key

SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown</VirtualHost>

On édite le fichier ports.conf pour activer le port 443.

Note : dans les dernières versions d’Apache 2.2 sous debian cette ligne est ajouté automatiquement lors de l’activation du module SSL.vi /etc/apache2/ports.conf et on ajoute la ligne

listen 443

puis on active le virtual host :a2ensite sslGénération des certificats :mkdir /etc/apache2/sslcd /etc/apache2/ssl

openssl genrsa -des3 -rand /etc/hosts -out starbridge.key 1024openssl req -new -key starbridge.key -out starbridge.csr

Page 15: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

openssl x509 -req -days 3650 -in starbridge.csr -signkey starbridge.key -out starbridge.crtopenssl rsa -in starbridge.key -out starbridge.key.unencryptedmv -f starbridge.key.unencrypted starbridge.keyopenssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650 chmod 400 /etc/apache2/ssl/*

On redémarre Apache : /etc/init.d/apache2 restartOn teste la connection parhttps://www.starbridge.orgLe navigateur va demander la validation du certificat car celui ci n’est pas reconnu par une autorité de confiance. Ceci est normal (c’est un certificat self-signed).Pour un serveur en production, il serait préférable d’utiliser un véritable certificat (payant).aptitude install subversioncd /var/wwwsvn -r 157 co https://postfixadmin.svn.sourceforge.net/svnroot/postfixadmin/trunk postfixadmin chown -R www-data: /var/www/postfixadmincd postfixadminchmod 640 *.php *.csscd /var/www/postfixadmin/admin/chmod 640 *.php .ht*cd /var/www/postfixadmin/images/chmod 640 *.gif *.pngcd /var/www/postfixadmin/languages/chmod 640 *.langcd /var/www/postfixadmin/templates/chmod 640 *.tplcd /var/www/postfixadmin/users/chmod 640 *.phpcd /var/www/postfixadmin/mv config.inc.php.sample config.inc.phpon édite le config.php :<?php//// Postfix Admin// by Mischa Peters <mischa at high5 dot net>// Copyright (c) 2002 - 2005 High5!// Licensed under GPL for more info check GPL-LICENSE.TXT//// File: config.inc.php//if (ereg ("config.inc.php", $_SERVER['PHP_SELF'])){ header ("Location: login.php"); exit;}

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!* The following line needs commenting out or removing before the* application will run!* Doing this implies you have changed this file as required.*/$CONF['configured'] = true;

// Postfix Admin Path

Page 16: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

// Set the location of your Postfix Admin installation here.// You must enter complete url (http://domain.tld/) and full path (/var/www/postfixadmin)$CONF['postfix_admin_url'] = 'https://www.starbridge.org/postfixadmin';$CONF['postfix_admin_path'] = dirname(__FILE__);

// Language config// Language files are located in './languages'.$CONF['default_language'] = 'en';

// Database Config// mysql = MySQL 3.23 and 4.0// mysqli = MySQL 4.1// pgsql = PostgreSQL$CONF['database_type'] = 'mysql';$CONF['database_host'] = 'localhost';$CONF['database_user'] = 'postfix';$CONF['database_password'] = '*****';$CONF['database_name'] = 'postfix';$CONF['database_prefix'] = '';

// Here, if you need, you can customize table names.$CONF['database_prefix'] = '';$CONF['database_tables'] = array ( 'admin' => 'admin', 'alias' => 'alias', 'domain' => 'domain', 'domain_admins' => 'domain_admins', 'log' => 'log', 'mailbox' => 'mailbox', 'vacation' => 'vacation', 'vacation_notification' => 'vacation_notification');

// Site Admin// Define the Site Admins email address below.// This will be used to send emails from to create mailboxes.$CONF['admin_email'] = '[email protected]';

// Mail Server// Hostname (FQDN) of your mail server.// This is used to send email to Postfix in order to create mailboxes.$CONF['smtp_server'] = 'localhost';$CONF['smtp_port'] = '25';

// Encrypt// In what way do you want the passwords to be crypted?// md5crypt = internal postfix admin md5// system = whatever you have set as your PHP system default// cleartext = clear text passwords (ouch!)$CONF['encrypt'] = 'md5crypt';

// Minimum length required for passwords. Postfixadmin will not// allow users to set passwords which are shorter than this value.$CONF['min_password_length'] = 5;

// Generate Password// Generate a random password for a mailbox or admin and display it.// If you want to automagically generate paswords set this to 'YES'.$CONF['generate_password'] = 'NO';

// Show Password// Always show password after adding a mailbox or admin.// If you want to always see what password was set set this to 'YES'.$CONF['show_password'] = 'NO';

Page 17: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

// Page Size// Set the number of entries that you would like to see// in one page.$CONF['page_size'] = '10';

// Default Aliases// The default aliases that need to be created for all domains.$CONF['default_aliases'] = array (

'abuse' => '[email protected]','hostmaster' => '[email protected]','postmaster' => '[email protected]','webmaster' => '[email protected]'

);

// Mailboxes// If you want to store the mailboxes per domain set this to 'YES'.// Example: /usr/local/virtual/domain.tld/[email protected]$CONF['domain_path'] = 'NO';// If you don't want to have the domain in your mailbox set this to 'NO'.// Example: /usr/local/virtual/domain.tld/username$CONF['domain_in_mailbox'] = 'YES';

// Default Domain Values// Specify your default values below. Quota in MB.$CONF['aliases'] = '0';$CONF['mailboxes'] = '0';$CONF['maxquota'] = '500';

// Quota// When you want to enforce quota for your mailbox users set this to 'YES'.$CONF['quota'] = 'YES';// You can either use '1024000' or '1048576'$CONF['quota_multiplier'] = '1024000';

// Transport// If you want to define additional transport options for a domain set this to 'YES'.// Read the transport file of the Postfix documentation.$CONF['transport'] = 'NO';// Transport options// If you want to define additional transport options put them in array below.$CONF['transport_options'] = array ( 'virtual', // for virtual accounts 'local', // for system accounts 'relay' // for backup mx);// Transport default// You should define default transport. It must be in array above.$CONF['transport_default'] = 'virtual';

// Virtual Vacation// If you want to use virtual vacation for you mailbox users set this to 'YES'.// NOTE: Make sure that you install the vacation module. http://high5.net/postfixadmin/$CONF['vacation'] = 'YES';// This is the autoreply domain that you will need to set in your Postfix// transport maps to handle virtual vacations. It does not need to be a// real domain (i.e. you don't need to setup DNS for it).$CONF['vacation_domain'] = 'autoreply.starbridge.org';

// Vacation Control// If you want users to take control of vacation set this to 'YES'.// TODO: not implemented$CONF['vacation_control'] ='YES';

// Vacation Control for admins// Set to 'YES' if your domain admins should be able to edit user vacation.

Page 18: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

$CONF['vacation_control_admin'] = 'YES';

// Alias Control// Postfix Admin inserts an alias in the alias table for every mailbox it creates.// The reason for this is that when you want catch-all and normal mailboxes// to work you need to have the mailbox replicated in the alias table.// If you want to take control of these aliases as well set this to 'YES'.$CONF['alias_control'] = 'NO';

// Alias Control for admins// Set to 'NO' if your domain admins shouldn't be able to edit user aliases.$CONF['alias_control_admin'] = 'NO';

// Special Alias Control// Set to 'NO' if your domain admins shouldn't be able to edit default aliases.$CONF['special_alias_control'] = 'NO';

// Alias Goto Field Limit// Set the max number of entries that you would like to see// in one 'goto' field in overview, the rest will be hidden and "[and X more...]" will be added.// '0' means no limits.$CONF['alias_goto_limit'] = '0';

// Backup// If you don't want backup tab set this to 'NO';$CONF['backup'] = 'YES';

// Send Mail// If you don't want sendmail tab set this to 'NO';$CONF['sendmail'] = 'YES';

// Logging// If you don't want logging set this to 'NO';$CONF['logging'] = 'YES';

// Header$CONF['show_header_text'] = 'NO';$CONF['header_text'] = ':: Postfix Admin ::';

// link to display under 'Main' menu when logged in as a user.$CONF['user_footer_link'] = "https://www.starbridge.org/postfixadmin/main";

// Footer// Below information will be on all pages.// If you don't want the footer information to appear set this to 'NO'.$CONF['show_footer_text'] = 'YES';$CONF['footer_text'] = 'Return to starbridge.org';$CONF['footer_link'] = 'https://www.starbridge.org/postfixadmin';

// Welcome Message// This message is send to every newly created mailbox.// Change the text between EOM.$CONF['welcome_text'] = <<<EOMHi,

Welcome to your new account.EOM;

// When creating mailboxes, check that the domain-part of the// address is legal by performing a name server look-up.$CONF['emailcheck_resolve_domain']='YES';

// Optional:// Analyze alias gotos and display a colored block in the first column// indicating if an alias or mailbox appears to deliver to a non-existent

Page 19: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

// account. Also, display indications, for POP/IMAP mailboxes and// for custom destinations (such as mailboxes that forward to a UNIX shell// account or mail that is sent to a MS exchange server, or any other// domain or subdomain you use)// See http://www.w3schools.com/html/html_colornames.asp for a list of// color names available on most browsers //set to YES to enable this feature$CONF['show_status']='NO';//display a guide to what these colors mean$CONF['show_status_key']='NO';// 'show_status_text' will be displayed with the background colors// associated with each status, you can customize it here$CONF['show_status_text']='&nbsp;&nbsp;';// show_undeliverable is useful if most accounts are delivered to this// postfix system. If many aliases and mailboxes are forwarded// elsewhere, you will probably want to disable this.$CONF['show_undeliverable']='NO';$CONF['show_undeliverable_color']='tomato';$CONF['show_undeliverable_exceptions']=array("unixmail.domain.ext","exchangeserver.domain.ext","gmail.com");$CONF['show_popimap']='NO';$CONF['show_popimap_color']='darkgrey';// set 'show_custom_count' to 0 to disable custom indicators$CONF['show_custom_count']=2;$CONF['show_custom_domains']=array("subdomain.domain.ext","domain2.ext");$CONF['show_custom_colors']=array("lightgreen","lightblue"); // Optional:// Script to run after creation of mailboxes.// Note that this may fail if PHP is run in "safe mode", or if// operating system features (such as SELinux) or limitations// prevent the web-server from executing external scripts.// $CONF['mailbox_postcreation_script']='sudo -u courier /usr/local/bin/postfixadmin-mailbox-postcreation.sh';

// Optional:// Script to run after deletion of mailboxes.// Note that this may fail if PHP is run in "safe mode", or if// operating system features (such as SELinux) or limitations// prevent the web-server from executing external scripts.// $CONF['mailbox_postdeletion_script']='sudo -u courier /usr/local/bin/postfixadmin-mailbox-postdeletion.sh';

// Optional:// Script to run after deletion of domains.// Note that this may fail if PHP is run in "safe mode", or if// operating system features (such as SELinux) or limitations// prevent the web-server from executing external scripts.// $CONF['domain_postdeletion_script']='sudo -u courier /usr/local/bin/postfixadmin-domain-postdeletion.sh';

// Optional:// Sub-folders which should automatically be created for new users.// The sub-folders will also be subscribed to automatically.// Will only work with IMAP server which implement sub-folders.// Will not work with POP3.// If you define create_mailbox_subdirs, then the// create_mailbox_subdirs_host must also be defined.//// $CONF['create_mailbox_subdirs']=array('Spam');// $CONF['create_mailbox_subdirs_host']='localhost';//// Normally, the TCP port number does not have to be specified.// $CONF['create_mailbox_subdirs_hostport']=143;//// If you have trouble connecting to the IMAP-server, then specify// a value for $CONF['create_mailbox_subdirs_hostoptions']. These// are some examples to experiment with:// $CONF['create_mailbox_subdirs_hostoptions']=array('notls');

Page 20: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

// $CONF['create_mailbox_subdirs_hostoptions']=array('novalidate-cert','norsh');// See also the "Optional flags for names" table at// http://www.php.net/manual/en/function.imap-open.php

//// END OF CONFIG FILE//?>

On sécurise ce fichier :chown -R www-data: /var/www/postfixadmin/config.inc.phpchmod 640 config.inc.phpIMPORTANT !!! : On crée un .htaccess pour sécuriser l’accès au répertoire admin.On se connecte à l’interface :https://www.starbridge.org/postfixadmin(bien sur on remplace starbridge par votre domaine sinon vous vous connectez chez moi !!)On lance le setup pour vérifier : Si tout est ok, on efface le setup :rm /var/www/postfixadmin/setup.phpOn se reconnecte à l’interface et on s’identifie avec [email protected] (on l’a créé plus tôt lors des inserts sql)On retrouve les élements entrés en ligne de commande au début du document. On crée un nouvel utilisateur pour valider.On rappelle que l’utilisation du SSL pour se connecter à Postfixadmin est INDISPENSABLE si on doit passer par internet pour gérer la plateforme. Sur un réseau local son utilisation serait préferable.

La gestion des Quotas

On l’a vu, on a compilé maildrop avec la gestion des quotas et on a parametré dans la base SQL des champs pour les gérer. Il faut maintenant les paramétrer :On crée un message d’alerte générique pour le dépassement de quotas :vi /etc/courier/quotawarnmsg

From: Postmaster domain.tld <[email protected]>Reply-To: [email protected]: Valued Customer:;Subject: Mail quota warningMime-Version: 1.0Content-Type: text/plain; charset=iso-8859-1Content-Transfer-Encoding: 7bit Your mailbox on the server is now more than 90% full. So that you can continue to receive mail you need to remove some messages from your mailbox.

Le reste est déjà paramétré dans Maildrop, Postfix et Courier-Imap.Pour une explication détaillée du fonctionnement voir cet article :Il suffit d’utiliser Postfixadmin pour régler un quota pour un utilisateur. Le faire avec l’utilisateur [email protected] qui par défaut n’a pas de quota.On teste en envoyant un mail.On regarde les logs.On vérifie qu’un fichier .maildirsize soit bien crée dans le Maildir du destinataire.Voila le serveur est configuré !A ce stade le serveur est sécurisé mais ne filtre ni les virus, ni le spam.

Page 21: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Antispam / Antivirus

paramètrage de postfix :Une grande majorité des spams ne respectent pas les règles d’envoi d’email : HELO incorrect, MAILFROM d’un domaine inconnu, etc, etc...Il est très fortement conseillé de lire des documents sur ce sujet, notamment les RFC pour bien comprendre le fonctionnement.La première chose à faire est de renforcer Postfix pour qu’il soit beaucoup plus restrictif.Pour cela on va utiliser les smtpd_recipient_restrictions.On ne détaillera pas ici les actions précises de chaque règle. (la documentation de Postfix est très précise sur le sujet et l’article sur la gestion du serveur de mail revient sur tous les points en les détaillant).On édite le main.cf et on remplace tout le smtpd_recipient_restrictions par celui ci :smtpd_recipient_restrictions =

reject_non_fqdn_recipient, reject_unknown_sender_domain, reject_non_fqdn_sender, reject_unknown_recipient_domain, reject_invalid_helo_hostname, reject_unlisted_recipient,

reject_unlisted_sender, permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_helo_hostname, reject_unauth_destination, check_client_access hash:/etc/postfix/internal_networks, check_sender_access hash:/etc/postfix/not_our_domain_as_sender, check_helo_access proxy:mysql:/etc/postfix/mysql-hello.cf, check_sender_access proxy:mysql:/etc/postfix/mysql-sender.cf, check_client_access proxy:mysql:/etc/postfix/mysql-client.cf, reject_rbl_client list.dsbl.org, reject_rbl_client zen.spamhaus.org, permit

On le voit, on a aussi paramétré des RBL (des blacklists) qui filtrent assez efficacement (parfois trop).ATTENTION : Il existe d’autres RBL (Spamcop...) qui peuvent rendre le filtrage encore plus restrictif mais cela est à déconseiller sur un serveur en production, bien que l’on puisse se servir des tables ci dessous (mysql-sender.cf et mysql-client.cf) pour whitelister certains clients ou expéditeurs).

Il vaut mieux gérer les RBL supplémentaires au travers d’une Policy Service de Postfix qui permettra plus de souplesse. (On détaillera ce point dans un autre article) Spamassassin gère aussi par défaut certaines RBL.Ensuite il faut limiter les possibilité de forging des expéditeurs en vérifiant les MAIL FROM (adresses expéditrices).Toujours dans le main.cf, on met au dessus du bloc smtpd_recipient_restrictions = :smtpd_sender_login_maps = proxy:mysql:/etc/postfix/mysql-sasl-sender-check.cf

smtpd_sender_restrictions = reject_unknown_sender_domain,reject_authenticated_sender_login_mismatch

smtpd_reject_unlisted_sender = yes

smtpd_restriction_classes = has_our_domain_as_sender

has_our_domain_as_sender = check_sender_access hash:/etc/postfix/our_domain_as_sender, reject

Page 22: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Cela permettra d’empécher des utilisateurs de mettre une autre adresse email dans le MAIL FROM. Ils seront obligés de passer par les domaines que l’on gère.De même les utilisateurs authentifiés par SASL seront tenus d’utiliser comme adresse email (MAIL FROM) un alias valide de leur mail principal. (on détaillera ce fonctionnement dans le document sur la gestion du serveur).Il faut maintenant créer les fichiers de lookup :On crée le fichier /etc/postfix/internal_networks : vi /etc/postfix/internal_networksOn spécifie son réseau local et son adresse publique à l’intérieur. Cela permet de spécifier la où les plages IP de notre réseau, qui seront autorisées à envoyer un mail avec nos domaines dans le MAIL FROM. Cela permet également de préciser les IP autorisées à envoyer un mail en se présentant avec notre HELO. On bloquera ainsi les clients SMTP extérieurs qui se présentent avec un HELO qui est le notre :10.0.0 has_our_domain_as_sender

On postmap ce fichier : postmap /etc/postfix/internal_networks Ensuite on crée le fichier /etc/postfix/mysql-hello.cf qui appelle une table SQL.vi /etc/postfix/mysql-hello.cfCette table SQL listera les HELO de nos domaines email (on peut en posséder plusieurs dans le cas d’un serveur multidomaine).user = postfixpassword = ****hosts = localhostdbname = postfixquery = SELECT access FROM postfix_hello WHERE source='%s'

On sécurise ce fichier :chown postfix /etc/postfix/mysql-hello.*chmod 640 /etc/postfix/mysql-hello.*On crée ensuite le fichier /etc/postfix/mysql-sender.cf.vi /etc/postfix/mysql-sender.cfIl sert à blacklister ou whitelister les MAILFROM, c’est à dire les expéditeurs, selon leur adresse email ou juste le domaine de celle ci :user = postfixpassword = ****hosts = localhostdbname = postfixquery = SELECT access FROM postfix_access WHERE source='%s' AND type = 'sender'On sécurise ce fichier :chown postfix /etc/postfix/mysql-sender.*chmod 640 /etc/postfix/mysql-sender.*On crée le fichier /etc/postfix/mysql-client.cf.vi /etc/postfix/mysql-client.cfIl sert à blacklister ou whitelister les clients par leur connection (ip/domaine) :user = postfixpassword = *****hosts = localhostdbname = postfixquery = SELECT access FROM postfix_access WHERE source='%s' AND type = 'client'

On sécurise ce fichier :chown postfix /etc/postfix/mysql-client.*chmod 640 /etc/postfix/mysql-client.*On crée le fichier /etc/postfix/mysql-sasl-sender-check.cf :vi /etc/postfix/mysql-sasl-sender-check.cf

Page 23: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Il sert à spécifier les adresses que les utilisateurs authentifiés par SASL peuvent utiliser comme MAIL FROM :user = postfixpassword = *****hosts = localhostdbname = postfixquery = SELECT goto FROM alias WHERE address='%s'

On remarquera que l’on fait appel à la table alias. En effet c’est le meilleur endroit pour connaitre les MAIL FROM d’un utilisateur, car un mail from valide doit être une adresse valide pour cet utilisateur. (donc un de ces alias)On sécurise ce fichier :chown postfix /etc/postfix/mysql-sasl-sender-check.*chmod 640 /etc/postfix/mysql-sasl-sender-check.*On crée le fichier /etc/postfix/our_domain_as_sender :vi /etc/postfix/our_domain_as_sender Il sert à spécifier les domaines autorisés comme MAIL FROM pour les users internes authentifiés par leur IP (les clients en local peuvent envoyer un email local sans s’authentifier dans notre configuration)starbridge.org OK<> OK

On postmap ce fichier : postmap /etc/postfix/our_domain_as_sender On crée enfin le fichier /etc/postfix/not_our_domain_as_sender :vi /etc/postfix/not_our_domain_as_sender Il sert à spécifier les domaines refusés comme MAIL FROM pour les users externes non authentifiés (c’est à dire quelqu’un de l’extérieur qui nous envoie un mail). Si il spécifie un de nos domaines en MAIL FROM, le message sera refusé.starbridge.org 554 You are not in our domain

On postmap ce fichier : postmap /etc/postfix/not_our_domain_as_sender On crée les tables en question :mysql -u root -puse postfix;CREATE TABLE `postfix_hello` ( `id` int(10) unsigned NOT NULL auto_increment, `source` varchar(128) NOT NULL default '', `access` varchar(128) NOT NULL default '', PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=37 DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;INSERT INTO `postfix_hello` (`id`, `source`, `access`) VALUES (36, 'starbridge.org', 'REJECT you are not me');CREATE TABLE `postfix_access` ( `id` int(10) unsigned NOT NULL auto_increment, `source` varchar(128) NOT NULL default '', `access` varchar(128) NOT NULL default '', `type` enum('recipient','sender','client') NOT NULL default 'sender', PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=107 DEFAULT CHARSET=latin1 AUTO_INCREMENT=107 ;INSERT INTO `postfix_access` (`id`, `source`, `access`, `type`) VALUES (1, 'yahoo.com', 'OK', 'client'), (14, '[email protected]', '554 Spam not tolerated here', 'sender');

Notez bien le INSERT sur la table postfix_hello et le modifier pour votre domaine.On relance postfix :postfix reloadon vérifie les logs et on teste.On a inséré des exemples de blacklist et de whitelist.Tout le détail du fonctionnement se trouve dans le document gestion serveur de mail.On peut utiliser PhpMyadmin pour gérer ces tables SQL.

Page 24: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Vérification des Headers, du Body et du Type Mime par Postfix.Postfix peut vérifier les mails entrants très simplement en analysant le header, le body et le type mime des pièces jointes.Ce type de blocage est très efficace, plus rapide que de laisser faire Amavisd ou SA, mais manque de souplesse.Il s’avère cependant très efficace pour bloquer des types de fichiers par exemple sans que le mail ne soit envoyé au serveur puis traité (économie de bande passante et de CPU).Cependant une trop grande quantité de règles et un fort trafic aurait l’effet inverse sur les performances.Il faut donc utiliser ces règles avec précaution.On crée les fichiers nécessaires :cd /etc/postfix/wget http://www.starbridge.org/spip/doc/Procmail/postfix/body_checks.cfwget http://www.starbridge.org/spip/doc/Procmail/postfix/header_checks.cfwget http://www.starbridge.org/spip/doc/Procmail/postfix/mime_headers_checks.cfOn édite le /etc/postfix/main.cf et on ajoute les lignes :header_checks = regexp:/etc/postfix/header_checks.cfbody_checks = regexp:/etc/postfix/body_checks.cfmime_header_checks = regexp:/etc/postfix/mime_headers_checks.cf

On relance postfix :postfix reloadOn teste en envoyant un mail classique puis un autre qui contient un des mots ou type bloqués par ces règles.Le blocage est immédiat et se traduit par un retour d’erreur au moment de l’envoi.

Installation Amavisd

on installe les prérequis :aptitude install libdb4.4-devOn lance CPAN en console :perl -MCPAN -e shellSi c’est la première fois, on répond par défaut aux questions qu’il pose pour la configuration de l’interface.Puis on met à jour Cpan et on installe les modules :install Bundle::CPANreload cpan install Archive::Zipinstall Convert::TNEF install Convert::UUlibinstall Net::Server install Time::HiRes install Unix::Syslog install BerkeleyDBinstall Email::Validinstall MIME::Charsetinstall MIME::EncWords

Page 25: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On installe aussi les softs nécessaires (les decoders ) si ils ne sont pas déjà installés :aptitude install file libcompress-bzip2-perl nomarch arc p7zip-full arj zoo lzop freeze tnef pax cabextractIl est très important également d’installer RAR depuis le site de rarlabs. Suivre les instructions d’installation sur le site.Télécharger les sources chez amavisd :cd ~wget http://www.ijs.si/software/amavisd/amavisd-new-2.5.2.tar.gztar xvzf amavisd-new-2.5.2.tar.gzcd amavisd-new-2.5.2Créer le user et le groupe amavis :addgroup amavisadduser --disabled-password --home /var/amavis --ingroup amavis amavisCréer un home pour le user amavis :mkdir /var/amavismkdir /var/amavis/tmp /var/amavis/var /var/amavis/db /var/amavis/homechown -R amavis: /var/amavisOn crée 2 lecteur tmpfs pour héberger les répertoires db et tmp d’amavis. Cela accroit notablement les performance de traitement :Modifier /etc/fstab :tmpfs /var/amavis/db tmpfs rw,size=10m,mode=700,uid=amavis,gid=amavis 0 0tmpfs /var/amavis/tmp tmpfs rw,size=150m,mode=700,uid=amavis,gid=amavis 0 0

Puis :mount /var/amavis/tmpmount /var/amavis/dbon vérifie par un :mount -lCopier l’exécutable :cp amavisd /usr/local/sbin/chown root /usr/local/sbin/amavisdchmod 755 /usr/local/sbin/amavisdCopier le fichier de conf :cp amavisd.conf /etc/chown root:amavis /etc/amavisd.confchmod 640 /etc/amavisd.confCréer la quarantaine :mkdir /var/virusmailschown amavis:amavis /var/virusmailschmod 750 /var/virusmailsEditer le /etc/amavisd.conf :Ci dessous les paramètres à modifier. Le reste du fichier reste le même. Evidemment il faut bien préciser son réseau local dans @mynetworks :$daemon_user = 'amavis'; $daemon_group = 'amavis'; $mydomain = 'starbridge.org'; $myhostname = 'mail.starbridge.org';$MYHOME = '/var/amavis'; $log_level = 2;@mynetworks = qw( 127.0.0.0/8 [::1] [FE80::]/10 [FEC0::]/10 10.0.0.0/24 );

On désactive temporairement l’antispam et l’antivirus pour tester :

Page 26: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On décommente pour cela les lignes (au début du fichier de conf) :@bypass_virus_checks_maps = (1); @bypass_spam_checks_maps = (1);

Démarrer amavisd en console pour voir si il manque des prérequis :/usr/local/sbin/amavisd debugNoter les erreurs éventuelles. Si amavisd ne démarre pas, arréter la et résoudre les problèmes.Si c’est ok, arréter amavisd par CTRL + C.On configure Postfix :A la fin du master.cf :smtp-amavis unix - - y - 2 smtp -o smtp_data_done_timeout=1200 -o smtp_send_xforward_command=yes -o disable_dns_lookups=yes -o max_use=20

127.0.0.1:10025 inet n - y - - 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 smtpd_data_restrictions=reject_unauth_pipelining -o smtpd_end_of_data_restrictions= -o mynetworks=127.0.0.0/8 -o strict_rfc821_envelopes=yes -o smtpd_error_sleep_time=0 -o smtpd_soft_error_limit=1001 -o smtpd_hard_error_limit=1000 -o smtpd_client_connection_count_limit=0 -o smtpd_client_connection_rate_limit=0 -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

et dans le main.cfcontent_filter = smtp-amavis:[127.0.0.1]:10024receive_override_options = no_address_mappings

Relancer postfix :postfix reloadSurveiller les logs :tail -f /var/log/mail.logSi tout est ok, lancer à nouveau amavisd debug :/usr/local/sbin/amavisd debuget taper en console :telnet 127.0.0.1 10024Il doit répondre :Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is '^]'.220 [127.0.0.1] ESMTP amavisd-new service readyquit pour sortirPareil pour tester le retour de Postfix :telnet 127.0.0.1 10025

Page 27: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Il doit répondre un truc du style :Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is '^]'.220 spike.starbridge.org ESMTP Postfix (Debian/GNU)QUIT pour sortir (en majuscules)Si les connections sont ok :Tester le fonctionnement de base (ce qu’il faut taper est précédé de ---> , le reste c’est le retour du serveur):---> telnet localhost 10024220 [127.0.0.1] ESMTP amavisd-new service ready---> HELO localhost250 [127.0.0.1]---> MAIL FROM: <>250 2.1.0 Sender <> OK---> RCPT TO: <postmaster>250 2.1.5 Recipient <postmaster> OK---> DATA354 End data with <CR><LF>.<CR><LF>---> From: virus-tester---> To: undisclosed-recipients:;---> Subject: amavisd test - simple - no spam test pattern---> This is a simple test message from the amavisd-new test-messages.---> .250 2.6.0 Ok, id=30897-02, from MTA([127.0.0.1]:10025): 250 2.0.0 Ok: queued as 079474CE44---> QUIT221 2.0.0 [127.0.0.1] amavisd-new closing transmission channel

L’aller-retour postfix/amavisd fonctionne bien !(on peut arréter le debug d’amavisd par un CTRL + C)

Installation Clamav

Prérequis :aptitude install zlib1g zlib1g-dev libgmpxx4ldbl libgmp3-devPour optimiser les performances de Clam, la base virale peut être localisée sur un ramdisk :Il faut créer une lecteur tmpfs :Modifier /etc/fstab :tmpfs /var/lib/clamav tmpfs rw,noexec,size=30m,mode=777,uid=amavis,gid=amavis 0 0

Puis :mkdir /var/lib/clamavmount /var/lib/clamavOn compile depuis les sources :cd ~wget http://mesh.dl.sourceforge.net/sourceforge/clamav/clamav-0.91.2.tar.gztar xvzf clamav-0.91.2.tar.gz cd clamav-0.91.2./configure --sysconfdir=/etc --with-user=amavis --with-group=amavis --with-dbdir=/var/lib/clamavmakemake installmkdir /var/run/clamavchown -R amavis: /var/run/clamavchmod -R 750 /var/run/clamav

Page 28: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Modifier le fichier de configuration de Clam comme celui :* /etc/clamd.conf#### Example config file for the Clam AV daemon## Please read the clamd.conf(5) manual before editing this file.##

# Comment or remove the line below.

# Uncomment this option to enable logging.# LogFile must be writable for the user running daemon.# A full path is required.# Default: disabledLogFile /var/log/clamav/clamd.log

# By default the log file is locked for writing - the lock protects against# running clamd multiple times (if want to run another clamd, please# copy the configuration file, change the LogFile variable, and run# the daemon with --config-file option).# This option disables log file locking.# Default: no#LogFileUnlock yes

# Maximum size of the log file.# Value of 0 disables the limit.# You may use 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes). To specify the size# in bytes just don't use modifiers.# Default: 1MLogFileMaxSize 20M

# Log time with each message.# Default: noLogTime yes

# Also log clean files. Useful in debugging but drastically increases the# log size.# Default: no#LogClean yes

# Use system logger (can work together with LogFile).# Default: no#LogSyslog yes

# Specify the type of syslog messages - please refer to 'man syslog'# for facility names.# Default: LOG_LOCAL6#LogFacility LOG_MAIL

# Enable verbose logging.# Default: no#LogVerbose yes

# This option allows you to save a process identifier of the listening# daemon (main thread).# Default: disabledPidFile /var/run/clamav/clamd.pid

# Optional path to the global temporary directory.# Default: system specific (usually /tmp or /var/tmp).TemporaryDirectory /tmp

# Path to the database directory.

Page 29: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# Default: hardcoded (depends on installation options)DatabaseDirectory /var/lib/clamav

# The daemon works in a local OR a network mode. Due to security reasons we# recommend the local mode.

# Path to a local socket file the daemon will listen on.# Default: disabled (must be specified by a user)LocalSocket /var/run/clamav/clamd.ctl

# Remove stale socket after unclean shutdown.# Default: noFixStaleSocket yes

# TCP port address.# Default: no#TCPSocket 3310

# TCP address.# By default we bind to INADDR_ANY, probably not wise.# Enable the following to provide some degree of protection# from the outside world.# Default: no#TCPAddr 127.0.0.1

# Maximum length the queue of pending connections may grow to.# Default: 15#MaxConnectionQueueLength 30

# Clamd uses FTP-like protocol to receive data from remote clients.# If you are using clamav-milter to balance load between remote clamd daemons# on firewall servers you may need to tune the options below.

# Close the connection when the data size limit is exceeded.# The value should match your MTA's limit for a maximum attachment size.# Default: 10M#StreamMaxLength 20M

# Limit port range.# Default: 1024#StreamMinPort 30000# Default: 2048#StreamMaxPort 32000

# Maximum number of threads running at the same time.# Default: 10#MaxThreads 20

# Waiting for data from a client socket will timeout after this time (seconds).# Value of 0 disables the timeout.# Default: 120#ReadTimeout 300

# Waiting for a new job will timeout after this time (seconds).# Default: 30#IdleTimeout 60

# Maximum depth directories are scanned at.# Default: 15#MaxDirectoryRecursion 20

# Follow directory symlinks.# Default: no#FollowDirectorySymlinks yes

Page 30: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# Follow regular file symlinks.# Default: no#FollowFileSymlinks yes

# Perform a database check.# Default: 1800 (30 min)#SelfCheck 600

# Execute a command when virus is found. In the command string %v will# be replaced with the virus name.# Default: no#VirusEvent /usr/local/bin/send_sms 123456789 "VIRUS ALERT: %v"

# Run as another user (clamd must be started by root for this option to work)# Default: don't drop privilegesUser amavis

# Initialize supplementary group access (clamd must be started by root).# Default: noAllowSupplementaryGroups yes

# Stop daemon when libclamav reports out of memory condition.#ExitOnOOM yes

# Don't fork into background.# Default: no#Foreground yes

# Enable debug messages in libclamav.# Default: no#Debug yes

# Do not remove temporary files (for debug purposes).# Default: no#LeaveTemporaryFiles yes

# Detect Possibly Unwanted Applications.# Default: no#DetectPUA yes

# In some cases (eg. complex malware, exploits in graphic files, and others),# ClamAV uses special algorithms to provide accurate detection. This option# controls the algorithmic detection.# Default: yes#AlgorithmicDetection yes

#### Executable files##

# PE stands for Portable Executable - it's an executable file format used# in all 32 and 64-bit versions of Windows operating systems. This option allows# ClamAV to perform a deeper analysis of executable files and it's also# required for decompression of popular executable packers such as UPX, FSG,# and Petite.# Default: yes#ScanPE yes

# Executable and Linking Format is a standard format for UN*X executables.# This option allows you to control the scanning of ELF files.# Default: yes#ScanELF yes

# With this option clamav will try to detect broken executables (both PE and

Page 31: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# ELF) and mark them as Broken.Executable.# Default: no#DetectBrokenExecutables yes

#### Documents##

# This option enables scanning of OLE2 files, such as Microsoft Office# documents and .msi files.# Default: yes#ScanOLE2 yes

# This option enables scanning within PDF files.# Default: no#ScanPDF yes

#### Mail files##

# Enable internal e-mail scanner.# Default: yes#ScanMail yes

# If an email contains URLs ClamAV can download and scan them.# WARNING: This option may open your system to a DoS attack.# Never use it on loaded servers.# Default: no#MailFollowURLs no

# Recursion level limit for the mail scanner.# Default: 64#MailMaxRecursion 128

# With this option enabled ClamAV will try to detect phishing attempts by using# signatures.# Default: yes#PhishingSignatures yes

# Scan URLs found in mails for phishing attempts using heuristics.# Default: yes#PhishingScanURLs yes

# Use phishing detection only for domains listed in the .pdb database. It is# not recommended to have this option turned off, because scanning of all# domains may lead to many false positives!# Default: yes#PhishingRestrictedScan yes

# Always block SSL mismatches in URLs, even if the URL isn't in the database.# This can lead to false positives.## Default: no#PhishingAlwaysBlockSSLMismatch no

# Always block cloaked URLs, even if URL isn't in database.# This can lead to false positives.## Default: no#PhishingAlwaysBlockCloak no

Page 32: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#### HTML##

# Perform HTML normalisation and decryption of MS Script Encoder code.# Default: yes#ScanHTML yes

#### Archives##

# ClamAV can scan within archives and compressed files.# Default: yes#ScanArchive yes

# The options below protect your system against Denial of Service attacks# using archive bombs.

# Files in archives larger than this limit won't be scanned.# Value of 0 disables the limit.# Default: 10M#ArchiveMaxFileSize 15M

# Nested archives are scanned recursively, e.g. if a Zip archive contains a RAR# file, all files within it will also be scanned. This options specifies how# deeply the process should be continued.# Value of 0 disables the limit.# Default: 8#ArchiveMaxRecursion 10

# Number of files to be scanned within an archive.# Value of 0 disables the limit.# Default: 1000#ArchiveMaxFiles 1500

# If a file in an archive is compressed more than ArchiveMaxCompressionRatio# times it will be marked as a virus (Oversized.ArchiveType, e.g. Oversized.Zip)# Value of 0 disables the limit.# Default: 250#ArchiveMaxCompressionRatio 300

# Use slower but memory efficient decompression algorithm.# only affects the bzip2 decompressor.# Default: no#ArchiveLimitMemoryUsage yes

# Mark encrypted archives as viruses (Encrypted.Zip, Encrypted.RAR).# Default: no#ArchiveBlockEncrypted no

# Mark archives as viruses (e.g. RAR.ExceededFileSize, Zip.ExceededFilesLimit)# if ArchiveMaxFiles, ArchiveMaxFileSize, or ArchiveMaxRecursion limit is# reached.# Default: no#ArchiveBlockMax no

# Enable support for Sensory Networks' NodalCore hardware accelerator.# Default: no#NodalCoreAcceleration yes

#### Clamuko settings

Page 33: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

## WARNING: This is experimental software. It is very likely it will hang## up your system!!!##

# Enable Clamuko. Dazuko (/dev/dazuko) must be configured and running.# Default: no#ClamukoScanOnAccess yes

# Set access mask for Clamuko.# Default: no#ClamukoScanOnOpen yes#ClamukoScanOnClose yes#ClamukoScanOnExec yes

# Set the include paths (all files inside them will be scanned). You can have# multiple ClamukoIncludePath directives but each directory must be added# in a seperate line.# Default: disabled#ClamukoIncludePath /home#ClamukoIncludePath /students

# Set the exclude paths. All subdirectories are also excluded.# Default: disabled#ClamukoExcludePath /home/bofh

# Don't scan files larger than ClamukoMaxFileSize# Value of 0 disables the limit.# Default: 5M#ClamukoMaxFileSize 10M

Modifier le fichier de configuration freshclam pour la mise à jour automatique de l’antivirus en particulier la ligne UpdateLogFile.* /etc/freshclam.conf#### Example config file for freshclam## Please read the freshclam.conf(5) manual before editing this file.##

# Comment or remove the line below.

# Path to the database directory.# WARNING: It must match clamd.conf's directive!# Default: hardcoded (depends on installation options)DatabaseDirectory /var/lib/clamav

# Path to the log file (make sure it has proper permissions)# Default: disabledUpdateLogFile /var/log/clamav/freshclam.log

# Enable verbose logging.# Default: noLogVerbose yes

# Use system logger (can work together with UpdateLogFile).# Default: noLogSyslog yes

# Specify the type of syslog messages - please refer to 'man syslog'# for facility names.# Default: LOG_LOCAL6#LogFacility LOG_MAIL

Page 34: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# This option allows you to save the process identifier of the daemon# Default: disabledPidFile /var/run/freshclam.pid

# By default when started freshclam drops privileges and switches to the# "clamav" user. This directive allows you to change the database owner.# Default: clamav (may depend on installation options)DatabaseOwner amavis

# Initialize supplementary group access (freshclam must be started by root).# Default: noAllowSupplementaryGroups yes

# Use DNS to verify virus database version. Freshclam uses DNS TXT records# to verify database and software versions. With this directive you can change# the database verification domain.# WARNING: Do not touch it unless you're configuring freshclam to use your# own database verification domain.# Default: current.cvd.clamav.netDNSDatabaseInfo current.cvd.clamav.net

# Uncomment the following line and replace XY with your country# code. See http://www.iana.org/cctld/cctld-whois.htm for the full list.DatabaseMirror db.fr.clamav.net

# database.clamav.net is a round-robin record which points to our most # reliable mirrors. It's used as a fall back in case db.XY.clamav.net is # not working. DO NOT TOUCH the following line unless you know what you# are doing.DatabaseMirror database.clamav.net

# How many attempts to make before giving up.# Default: 3 (per mirror)#MaxAttempts 5

# With this option you can control scripted updates. It's highly recommended# to keep it enabled.#ScriptedUpdates yes

# Number of database checks per day.# Default: 12 (every two hours)#Checks 24

# Proxy settings# Default: disabled#HTTPProxyServer myproxy.com#HTTPProxyPort 1234#HTTPProxyUsername myusername#HTTPProxyPassword mypass

# If your servers are behind a firewall/proxy which applies User-Agent# filtering you can use this option to force the use of a different# User-Agent header.# Default: clamav/version_number#HTTPUserAgent SomeUserAgentIdString

# Use aaa.bbb.ccc.ddd as client address for downloading databases. Useful for# multi-homed systems.# Default: Use OS'es default outgoing IP address.#LocalIPAddress aaa.bbb.ccc.ddd

# Send the RELOAD command to clamd.# Default: no#NotifyClamd /path/to/clamd.conf

Page 35: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# Run command after successful database update.# Default: disabled#OnUpdateExecute command

# Run command when database update process fails.# Default: disabled#OnErrorExecute command

# Run command when freshclam reports outdated version.# In the command string %v will be replaced by the new version number.# Default: disabled#OnOutdatedExecute command

# Don't fork into background.# Default: no#Foreground yes

# Enable debug messages in libclamav.# Default: no#Debug yes

# Timeout in seconds when connecting to database server.# Default: 30#ConnectTimeout 60

# Timeout in seconds when reading from database server.# Default: 30#ReceiveTimeout 60

Créer 2 taches cron pour la mise à jour :vi /etc/cron.d/freshclamet on colle :PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binMAILTO=root

0 0,6,12,18 * * * amavis /usr/local/bin/freshclam --log-verbose --log-verbose@reboot amavis /usr/local/bin/freshclam

Créer :mkdir /var/log/clamavchown -R amavis:amavis /var/log/clamavCréer un /etc/init.d/clamd :vi /etc/init.d/clamdet on colle :#!/bin/sh# clamd

case "$1" in'start')

/usr/local/sbin/clamd;;

'stop')/usr/bin/killall clamd > /dev/null 2>&1 && echo -n 'Clamd stopped'

;;*)

echo "Usage: $0 { start | stop }";;

esacexit 0

Page 36: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

puis :chmod 755 /etc/init.d/clamdupdate-rc.d clamd defaultsOn fait la mise à jour de la base virale :freshclamOn vérifie que les fichiers soient bien présents dans le répertoire :ls -la /var/lib/clamavOn lance clamd :/etc/init.d/clamd startEt on vérifie les logs :tail -f /var/log/clamav/clamd.logEt on vérifie bien que Clam tourne :ps aux | grep clamOn teste le fonctionnement (le dossier "test" est dans le répertoire clamav-0.91.1) :cd testclamdscan -l scan.txt clamav-x.yzclamav-x.yz etant un des fichiers de test présents dans le répertoire test

Spamassassin

On installe SA par CPAN :perl -MCPAN -e shell o conf prerequisites_policy askinstall HTML::Parserinstall LWPinstall IO::Zlibinstall Archive::Tarinstall DB_Fileinstall Net::SMTPinstall Net::DNSinstall Net::DNS::Resolver::Programmableinstall Errorinstall NetAddr::IPinstall IP::Country::Fastinstall Mail::SPFinstall DBIinstall DBD::mysqlinstall Mail::SpamAssassin

Note : Si l’installation de SA finit par une erreur (le make test ne passe pas) il faut alors forcer l’install par :force install Mail::SpamAssassin

SA est installé. Sa config de base se fait dans le fichier /etc/mail/spamassassin/local.cf mais pour la plupart des paramètres, c’est le fichier amavisd.conf qui sera prioritaire.Lorsqu’on utilise Amavisd pour appeler SA il est inutile de lancer spamd.

Page 37: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On édite le /etc/mail/spamassassin/local.cf comme ceci :lock_method flockrequired_score 4.3

rewrite_header Subject *****SPAM*****

report_safe 0

clear_internal_networksclear_trusted_networks#trusted networks doit TOUJOURS contenir les memes entrées que internal. On ajoutera eventuellement des réseaux de confiance dans ce paramètre.

internal_networks 82.239.58.131 10.0.0/24 192.168.1/24trusted_networks 82.239.58.131 10.0.0/24 192.168.1/24

use_bayes 1

bayes_auto_expire 0bayes_store_module Mail::SpamAssassin::BayesStore::MySQLbayes_sql_dsn DBI:mysql:spam:localhostbayes_sql_username spambayes_sql_password *****bayes_sql_override_username amavis

bayes_auto_learn 1bayes_auto_learn_threshold_nonspam 0.1bayes_auto_learn_threshold_spam 5.0

use_auto_whitelist 0

skip_rbl_checks 0dns_available yes

## Optional Score Increases

score BAYES_99 4.300score BAYES_80 3.000score MISSING_MIMEOLE 0.501 0.501 0.241 0.200score BAYES_60 0 0 2.502 2.502score NO_RELAYS -3.2

internal_networks et trusted_networks sont des paramètres très importants pour la pertinence de la détection. Il faut absolument les configurer correctement. On sécurise :chown amavis: /etc/mail/spamassassin/local.cfchmod 640 /etc/mail/spamassassin/local.cfSA fonctionne sur 2 types de tests :

• Heuristiques (ensemble de règles)• Bayesiens (apprentissage et statistiques)

Pour le filtre bayesien, on va installer directement la base dans une base Mysql. Les performances sont supérieures et on s’affranchit de diverses limitations :On crée la base :mysql -u root -pcreate database spam; GRANT SELECT, INSERT, UPDATE, DELETE ON spam.* TO 'spam'@'localhost' IDENTIFIED BY '*****'; FLUSH PRIVILEGES;quit

Page 38: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On importe la base sql :wget http://spamassassin.apache.org/full/3.2.x/dist/sql/bayes_mysql.sqlwget http://spamassassin.apache.org/gtube/gtube.txtmysql -u root -p spam < bayes_mysql.sqlOn initialise la base :su amavis -c 'sa-learn -D --spam gtube.txt'On peut vérifier avec phpmyadmin que la base s’est bien remplie.On améliore les performances de la base en changeant le moteur en InnoDB :mysql -u root -p

USE spam;ALTER TABLE bayes_expire TYPE=InnoDB;ALTER TABLE bayes_global_vars TYPE=InnoDB;ALTER TABLE bayes_seen TYPE=InnoDB;ALTER TABLE bayes_token TYPE=InnoDB;ALTER TABLE bayes_vars TYPE=InnoDB;ANALYZE TABLE bayes_expire;ANALYZE TABLE bayes_global_vars;ANALYZE TABLE bayes_seen;ANALYZE TABLE bayes_token;ANALYZE TABLE bayes_vars;

Pour améliorer les performances, on a désactivé le "opportunistic (automatic) Bayes auto-expiry" en spécifiant "bayes_auto_expire 0" dans /etc/mail/spamassassin/local.cf.Il faut donc créer une tache cron quotidienne pour effectuer l’expiration :Un crontab de l’user amavis fera l’affaire :crontab -e -u amaviset on ajoute16 3 * * * sa-learn --sync --force-expire

Mise à jour des Rules de SA et ajout des Rules SARE :On va mettre tout de suite à jour les règles de SA et en installer de nouvelles depuis le site de SARE :On lance l’update des règles de SA :sa-update -DCela aura pour effet de télécharger les règles à jour. Elles seront installés dans un dossier différent des règles d’origine : /var/lib/spamassassin/3.002003. (ce qui correspond à la version 3.2.3 de SA)SA considèrera désormais ce dossier comme celui par défaut.On vérifie que tout soit OK :su -c "spamassassin -D --lint" amavisIl ne doit pas il y a voir de message d’erreur à la fin de l’execution.On prépare l’installation des rules SARE :cd /etc/mail/spamassassin/wget http://daryl.dostech.ca/sa-update/sare/GPG.KEYsa-update --import GPG.KEYon installe le fichier contenant la liste des Rules :wget http://www.starbridge.org/spip/doc/Procmail/spamassassin/sare-sa-update-channels.txtOn pourra modifier ce fichier pour ne sélectionner que les RULES que l’on désire.On met à jour :sa-update --channelfile /etc/mail/spamassassin/sare-sa-update-channels.txt --gpgkey 856AA88ALes fichiers seront placés dans /var/lib/spamassassin :ls -la /var/lib/spamassassin/3.002003/On vérifie à nouveau que tout soit OK :su -c "spamassassin -D --lint" amavis

Page 39: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Pour une mise à jour réguliere (1 fois par jour maximum) on pourra créer une tache cron en n’oubliant pas de relancer amavisd à la fin du script.Pour cela, on crée un fichier sa-update.sh :vi /etc/sa-update.shet on colle :#!/bin/bashsa-updatecode1=$?if [[ $code1 > 1 ]]; then echo "problem with sa-update"fi sa-update --channelfile /etc/mail/spamassassin/sare-sa-update-channels.txt --gpgkey 856AA88Acode2=$?if [[ $code2 > 1 ]]; then echo "problem with sare update"fi if [[ `expr $code1 + $code2` < 2 ]]; then spamassassin --lint code3=$? if [[ $code3 = 0 ]]; then /etc/init.d/amavis stop && /etc/init.d/amavis start >/dev/null else echo "spamassassin failed to lint" fifi

On sécurise :chmod 755 /etc/sa-update.shOn édite la crontab :crontab -eet on ajoute la ligne :15 2 * * * /etc/sa-update.sh

Compilation des RulesetsDepuis la version 3.2, SA est un peu plus lent dans le traitement des messages. En revanche une nouvelle fonctionnalité est apparue : la compilation des règles.Pour celles qui le permettent, cela accelère sensiblement le traitement. Pour cela il faut installer au préalable le paquet re2c :aptitude install re2con lance ensuite la commande :sa-compile -Dcela prend un certain temps avant de se terminer. Les règles compilées seront placées dans le répertoire /var/lib/spamassassin/compiled.Il faut maintenant activer l’usage de ces règles grace au plugin Rule2XSBody :On édite /etc/mail/spamassassin/v320.pre et on décommente la ligne suivante :loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody

on vérifie que tout soit ok :su -c 'spamassassin -D --lint' amavisIl faut maintenant planifier une compilation hebdomadaire des règles.On crée un fichier /etc/cron.weekly/sa-compile :vi /etc/cron.weekly/sa-compileet on colle :#!/bin/bashif [ -x /usr/bin/re2c -a -x /usr/local/bin/sa-compile -a -d /var/lib/spamassassin/compiled ]; then /usr/local/bin/sa-compile > /dev/null 2>&1ficode1=$?if [[ $code1 > 0 ]]; then echo "problem with sa-compile, turning off Rule2XSBody plugin"

Page 40: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

sed -i 's/loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody/#loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody/' /etc/mail/spamassassin/v320.pre test -x /usr/local/sbin/amavisd || exit 0 /etc/init.d/amavis stop && /etc/init.d/amavis start >/dev/nullelse sed -i 's/#loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody/loadplugin Mail::SpamAssassin::Plugin::Rule2XSBody/' /etc/mail/spamassassin/v320.pre test -x /usr/local/sbin/amavisd || exit 0 /etc/init.d/amavis stop && /etc/init.d/amavis start >/dev/nullfi

on rend le fichier executable :chmod 755 /etc/cron.weekly/sa-compileSA est prêt et fonctionnel !!-Il faut maintenant activer SA dans amavisd :On édite amavisd.conf et on commente la ligne :# @bypass_spam_checks_maps = (1);

On démarre en debug-sa :/usr/local/sbin/amavisd debug-saon doit trouver dans la liste ceci :dbg: bayes: using username: amavis[30527] dbg: bayes: database connection established[30527] dbg: bayes: found bayes db version 3[30527] dbg: bayes: Using userid: 1[30527] dbg: bayes: not available for scanning, only 1 spam(s) in bayes DB < 200Bayes n’est pas encore disponible car il n’a pas analysé assez de mails pour fonctionner. Ceci est normal.On envoie un mail et on doit voir dans le debug le bon fonctionnement.On arrête amavisd par un CTRL + C.On édite le amavisd.conf et on change les lignes suivantes de cette manière :$sa_tag_level_deflt = -9999.9; # add spam info headers if at, or above that level$sa_tag2_level_deflt = 4.3; # add 'spam detected' headers at that level$sa_kill_level_deflt = 9999.9; # triggers spam evasive actions

$sa_mail_body_size_limit = 500*1024; # don't waste time on SA if mail is larger

$sa_spam_subject_tag = '***SPAM_SCORE_*** ';$sa_spam_report_header = 1;

$final_spam_destiny = D_PASS;

Avec cette modification, on dit à amavisd de laisser passer le spam mais de le tagguer dans le header du mail.On traitera le mail plus loin par Maildrop.On crée un fichier /etc/init.d/amavis :vi /etc/init.d/amaviset on colle :#!/bin/sh# amavisd-new

case "$1" in'start') /usr/local/sbin/amavisd start ;;'stop') /usr/local/sbin/amavisd stop ;;*) echo "Usage: $0 { start | stop }"

Page 41: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

;;esacexit 0

puis :chmod 755 /etc/init.d/amavisupdate-rc.d amavis defaultson lance amavisd :/etc/init.d/amavis startOn regarde les logs.On envoie un mail et on regarde l’entête de celui ci. on doit voir les X-Spam- headers.On paramètre Maildrop pour déposer le courier détecté comme spam dans le dossier spam de chaque utilisateur :On édite /home/virtual/.mailfilter et on le modifie comme ceci :logfile "/home/virtual/.maildrop.log" `[ -d $DEFAULT ] || (maildirmake $DEFAULT && maildirmake -f Spam $DEFAULT && maildirmake -f sent-mail $DEFAULT && maildirmake -f SpamToLearn $DEFAULT && maildirmake -f SpamFalse $DEFAULT)`

if ( /^X-Spam-Level: \*\*\*\*\*\*\*\*\*\*/ ){ log "--> X-Spam-toohigh."exception { to /home/virtual/[email protected]/

}}

if ( /^X-Spam-Flag: YES/ ){ log "--> X-Spam-Flag-ed." to $HOME/$DEFAULT.Spam}

`test -r $HOME/$DEFAULT.mailfilter`if( $RETURNCODE == 0 ) { log "(==) Including $HOME/$DEFAULT.mailfilter" exception { include $HOME/$DEFAULT.mailfilter } }

Explications :Le premier If permet d’envoyer le spam dont le score est au dessus de 10 dans une boite spécifique [email protected] qu’il faut créer (on peut utiliser postfixadmin pour ca).Le deuxième If permet d’envoyer le spam en dessous de 10 dans le dossier Spam de l’utilisateur.Pour améliorer l’apprentissage, on crée une tache qui scanne la boîte spamtrap et les 2 dossiers d’apprentissage SpamToLearn et SpamFalse des boîtes des utilisateurs (Dossiers crées automatiquement par maildrop à la première livraison) puis envoie leur contenu vers le filtre bayesien .On crée d’abord deux répertoires spéciaux de transit :mkdir /home/spamtrapchown amavis: /home/spamtrapchmod 777 /home/spamtrapmkdir /home/hamtrapchown amavis: /home/hamtrapchmod 777 /home/hamtrapon crée un fichier /etc/sa-learn :vi /etc/sa-learn

Page 42: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

et on colle :#!/bin/bashmv /home/virtual/[email protected]/new/* /home/spamtrap/ > /dev/null 2>&1mv /home/virtual/[email protected]/cur/* /home/spamtrap/ > /dev/null 2>&1mv /home/virtual/*/.SpamToLearn/cur/* /home/spamtrap/ > /dev/null 2>&1mv /home/virtual/*/.SpamToLearn/new/* /home/spamtrap/ > /dev/null 2>&1mv /home/virtual/*/.SpamFalse/new/* /home/hamtrap/ > /dev/null 2>&1mv /home/virtual/*/.SpamFalse/cur/* /home/hamtrap/ > /dev/null 2>&1chown amavis:amavis /home/spamtrap/* > /dev/null 2>&1chown amavis:amavis /home/hamtrap/* > /dev/null 2>&1chmod 777 /home/spamtrap/* > /dev/null 2>&1chmod 777 /home/hamtrap/* > /dev/null 2>&1su -c "/usr/local/bin/sa-learn -D --spam /home/spamtrap/" amavissu -c "/usr/local/bin/sa-learn -D --ham /home/hamtrap/" amavisrm /home/spamtrap/* > /dev/null 2>&1rm /home/hamtrap/* > /dev/null 2>&1

puis :chmod 755 /etc/sa-learnOn crée une tache cron qu’on lance par root : (une fois par jour ou plus suivant la puissance de la machine, cette tache etant tres gourmande en ressources)crontab -eet on ajoute (on change la fréquence si nécessaire) :30 3,10,15,22 * * * /etc/sa-learn

Tout sera automatique. Il suffira d’indiquer aux utilisateurs de déplacer les emails non détectés comme Spam dans le dossier SpamToLearn et les email légitimes détectés à tort comme Spam dans le Dossier SpamFalse. Le script déplacera lors de son execution tous ces emails et en fera l’apprentissage soit comme spam soit comme ham (non spam).Par sécurité on peut conserver les mails de la boite spamtrap (non consultables par les utilisateurs) un certain temps. Pour cela il suffira de changer les 2 premieres lignes en copie au lieu d’un déplacement (cp). On verra plus loin pour un script de nettoyage basé sur l’age des fichiers.On peut également enlever le -D des 2 lignes sa-learn pour limiter la sortie du script (debug). Cron envoie un mail à l’exécution de la commande, contenant la sortie.Activation de Clam dans AmavisdOn paramètre ensuite l’antivirus pour fonctionner avec amavisd :On édite le amavisd.conf :On remplace à la fin du fichier tout ce qui se trouve entre :@av_scanners = ( et1; # insure a defined returnpar :# ### http://www.clamav.net/ ['ClamAV-clamd', \&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd.ctl"], qr/\bOK$/, qr/\bFOUND$/, qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],);

@av_scanners_backup = (

### http://www.clamav.net/ - backs up clamd or Mail::ClamAV ['ClamAV-clamscan', 'clamscan', "--stdout --no-summary -r --tempdir=$TEMPBASE {}", [0], qr/:.*\sFOUND$/, qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ],

);

Et on commente :@bypass_virus_checks_maps = (1);

Page 43: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On relance amavisd :/etc/init.d/amavis stop && /etc/init.d/amavis startL’antivirus est chargé.On crée l’alias email : [email protected] vers [email protected] teste le fonctionnement :--> $ telnet 127.0.0.1 10024 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. 220 [127.0.0.1] ESMTP amavisd-new service ready

--> MAIL FROM:<[email protected]> 250 2.1.0 Sender [email protected] OK--> RCPT TO:<postmaster> 250 2.1.5 Recipient postmaster OK--> DATA 354 End data with <CR><LF>.<CR><LF>--> Subject: test2 - virus test pattern-->--> X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*--> .

--> QUIT 221 2.0.0 [127.0.0.1] (amavisd) closing transmission channel Connection closed by foreign host.

On doit voir dans les logs :Blocked INFECTED (Eicar-Test-Signature)On peut aussi tester l’envoi d’un mail infecté dans une archive (pour tester le travail de décompression) en récuperant des fichiers de test sur eicar.com et en les envoyant par email.Maintenance de Clam et de Spamassassin :Il faut penser à purger régulièrement le contenu de la boite spamtrap et la quarantaine de clam, c’est à dire le dossier /home/virtual/[email protected]/new/. et le /var/virusmails.Pour cela on peut utiliser un outil du genre tmpreaper.Il se configure très simplement dans /etc/tmpreaper.confOn modifie la ligne suivante comme ceci :TMPREAPER_DIRS='/tmp/. /var/virusmails/. /home/virtual/[email protected]/new/.'

DspamBeaucoup considère Dspam comme une alternative plus performante de SA.Je trouve qu’ils sont plutôt complémentaires.Amavisd permet de gérer les 2 en parallèle :cd ~wget http://dspam.nuclearelephant.com/sources/dspam-3.8.0.tar.gztar xvzf dspam-3.8.0.tar.gzcd dspam-3.8.0./configure --with-dspam-home=/var/amavis/dspam --enable-signature-headers --without-delivery-agent --without-quarantine-agent --with-storage-driver=mysql_drv --with-mysql-includes=/usr/include/mysqlmakemake installModifier les droits sur les exécutables (meme user qu’amavisd) et le dspam.conf :chown amavis: /usr/local/bin/dspam*chown amavis: /usr/local/etc/dspam.confchmod 750 /usr/local/bin/dspam*chmod 640 /usr/local/etc/dspam.conf

Page 44: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

Créer la base sql :mysql -u root -pcreate database dspam;GRANT SELECT, INSERT, UPDATE, DELETE ON dspam.* TO 'dspam'@'localhost' IDENTIFIED BY '******'; FLUSH PRIVILEGES;quit

On importe la base sql :mysql -u root -p dspam < /root/dspam-3.8.0/src/tools.mysql_drv/mysql_objects-4.1.sqlModifier le fichier /usr/local/etc/dspam.conf : exemple de fichier fonctionnel## $Id: dspam.conf.in,v 1.68 2006/02/11 20:13:14 jonz Exp $## dspam.conf -- DSPAM configuration file##

## DSPAM Home: Specifies the base directory to be used for DSPAM storage#Home /var/amavis/dspam

## StorageDriver: Specifies the storage driver backend (library) to use.# You'll only need to set this if you are using dynamic storage driver plugins.# The default when one storage driver is specified is to statically link. Be # sure to include the path to the library if necessary, and some systems may # use an extension other than .so.## Options include:## libmysql_drv.so libpgsql_drv.so libsqlite_drv.so# libsqlite3_drv.so libora_drv.so libdb4_drv.so# libdb3_drv.so libhash_drv.so## IMPORTANT: Switching storage drivers requires more than merely changing# this option. If you do not wish to lose all of your data, you will need to# migrate it to the new backend before making this change.#StorageDriver /usr/local/lib/libmysql_drv.so

## Trusted Delivery Agent: Specifies the local delivery agent DSPAM should call # when delivering mail as a trusted user. Use %u to specify the user DSPAM is # processing mail for. It is generally a good idea to allow the MTA to specify # the pass-through arguments at run-time, but they may also be specified here.## Most operating system defaults:#TrustedDeliveryAgent "/usr/bin/procmail" # Linux#TrustedDeliveryAgent "/usr/bin/mail" # Solaris#TrustedDeliveryAgent "/usr/libexec/mail.local" # FreeBSD#TrustedDeliveryAgent "/usr/bin/procmail" # Cygwin## Other popular configurations:#TrustedDeliveryAgent "/usr/cyrus/bin/deliver" # Cyrus#TrustedDeliveryAgent "/bin/maildrop" # Maildrop#TrustedDeliveryAgent "/usr/local/sbin/exim -oMr spam-scanned" # Exim#TrustedDeliveryAgent "no"

## Untrusted Delivery Agent: Specifies the local delivery agent and arguments# DSPAM should use when delivering mail and running in untrusted user mode.# Because DSPAM will not allow pass-through arguments to be specified to # untrusted users, all arguments should be specified here. Use %u to specify# the user DSPAM is processing mail for. This configuration parameter is only

Page 45: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# necessary if you plan on allowing untrusted processing.##UntrustedDeliveryAgent "/usr/bin/procmail -d %u"

## SMTP or LMTP Delivery: Alternatively, you may wish to use SMTP or LMTP # delivery to deliver your message to the mail server. You will need to # configure with --enable-daemon to use host delivery, however you do not need # to operate in daemon mode. Specify an IP address or UNIX path to a domain # socket below as a host.## If you would like to set up DeliveryHost's on a per-domain basis, use# the syntax: DeliveryHost.domain.com 1.2.3.4##DeliveryHost 127.0.0.1#DeliveryPort 24#DeliveryIdent localhost#DeliveryProto LMTP

## Quarantine Agent: DSPAM's default behavior is to quarantine all mail it # thinks is spam. If you wish to override this behavior, you may specify# a quarantine agent which will be called with all messages DSPAM thinks is# spam. Use %u to specify the user DSPAM is processing mail for.##QuarantineAgent "/usr/bin/procmail -d spam"

## DSPAM can optionally process "plused users" (addresses in the user+detail# form) by truncating the username just before the "+", so all internal# processing occurs for "user", but delivery will be performed for# "user+detail". This is only useful if the LDA can handle "plused users"# (for example Cyrus IMAP) and when configured for LMTP delivery above## NOTE: Plused detail presently only works when usernames are provided and# not fully qualified email address (@domain).##EnablePlusedDetail on

## Quarantine Mailbox: DSPAM's LMTP code can send spam mail using LMTP to a # "plused" mailbox (such as user+quarantine) leaving quarantine processing# for retraining or deletion to be performed by the LDA and the mail client.# "plused" mailboxes are supported by Cyrus IMAP and possibly other LDAs.# The mailbox name must have the +##QuarantineMailbox +quarantine

## OnFail: What to do if local delivery or quarantine should fail. If set# to "unlearn", DSPAM will unlearn the message prior to exiting with an# un successful return code. The default option, "error" will not unlearn# the message but return the appropriate error code. The unlearn option# is use-ful on some systems where local delivery failures will cause the# message to be requeued for delivery, and could result in the message# being processed multiple times. During a very large failure, however, # this could cause a significant load increase.#OnFail error

# Trusted Users: Only the users specified below will be allowed to perform# administrative functions in DSPAM such as setting the active user and# accessing tools. All other users attempting to run DSPAM will be restricted;# their uids will be forced to match the active username and they will not be# able to specify delivery agent privileges or use tools.

Page 46: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#Trust rootTrust mailTrust mailnull Trust smmspTrust daemonTrust amavis#Trust nobody#Trust majordomo

## Debugging: Enables debugging for some or all users. IMPORTANT: DSPAM must# be compiled with debug support in order to use this option. DSPAM should# never be running in production with debug active unless you are # troubleshooting problems.## DebugOpt: One or more of: process, classify, spam, fp, inoculation, corpus# process standard message processing# classify message classification using --classify# spam error correction of missed spam# fp error correction of false positives# inoculation message inoculations (source=inoculation)# corpus corpusfed messages (source=corpus)##Debug *#Debug bob bill##DebugOpt process spam fp

## ClassAlias: Alias a particular class to spam/nonspam. This is useful if# classifying things other than spam.#ClassAliasSpam badstuff#ClassAliasNonspam goodstuff

## Training Mode: The default training mode to use for all operations, when# one has not been specified on the commandline or in the user's preferences.# Acceptable values are: toe, tum, teft, notrain#TrainingMode teft

## TestConditionalTraining: By default, dspam will retrain certain errors# until the condition is no longer met. This usually accelerates learning.# Some people argue that this can increase the risk of errors, however.#TestConditionalTraining on

## Features: Specify features to activate by default; can also be specified# on the commandline. See the documentation for a list of available features.# If _any_ features are specified on the commandline, these are ignored.## NOTE: For standard "CRM114" Markovian weighting, use sbph##Feature sbph#Feature noise#Feature chainedFeature whitelist

# Training Buffer: The training buffer waters down statistics during training.# It is designed to prevent false positives, but can also dramatically reduce# dspam's catch rate during initial training. This can be a number from 0# (no buffering) to 10 (maximum buffering). If you are paranoid about false

Page 47: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# positives, you should probably enable this option.#Feature tb=5

## Algorithms: Specify the statistical algorithms to use, overriding any# defaults configured in the build. The options are:# naive Naive-Bayesian (All Tokens)# graham Graham-Bayesian ("A Plan for Spam")# burton Burton-Bayesian (SpamProbe)# robinson Robinson's Geometric Mean Test (Obsolete)# chi-square Fisher-Robinson's Chi-Square Algorithm## You may have multiple algorithms active simultaneously, but it is strongly# recommended that you group Bayesian algorithms with other Bayesian# algorithms, and any use of Chi-Square remain exclusive.## NOTE: For standard "CRM114" Markovian weighting, use 'naive', or consider# using 'burton' for slightly better accuracy## Don't mess with this unless you know what you're doing##Algorithm chi-square#Algorithm naiveAlgorithm graham burton

# ajout manuel migration 3.6 vers 3.8# Tokenizer: Specify the tokenizer to use. The tokenizer is the piece# responsible for parsing the message into individual tokens. Depending on# how many resources you are willing to trade off vs. accuracy, you may# choose to use a less or more detailed tokenizer:# word uniGram (single word) tokenizer# Tokenizes message into single individual words/tokens# example: "free" and "viagra"# chain biGram (chained tokens) tokenizer (default)# Single words + chains adjacent tokens together# example: "free" and "viagra" and "free viagra"# sbph Sparse Binary Polynomial Hashing tokenizer# Creates sparse token patterns across sliding window of 5-tokens# example: "the quick * fox jumped" and "the * * fox jumped"# osb Orthogonal Sparse biGram# Similar to SBPH, but only uses the biGrams# example: "the * * fox" and "the * * * jumped"#Tokenizer chain

## PValue: Specify the technique used for calculating PValues, overriding any# defaults configured in the build. These options are:# graham Graham's Technique ("A Plan for Spam")# robinson Robinson's Technique # markov Markovian Weighted Technique## Unlike algorithms, you may only have one of these defined. Use of the# chi-square algorithm automatically changes this to robinson.## Don't mess with this unless you know what you're doing.##PValue robinson#PValue markovPValue graham

## SupressWebStats: Enable this if you are not using the CGI, and don't want# .stats files written.

Page 48: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#SupressWebStats on

#ajout manuel# WebStats: Enable this if you are using the CGI, which writes .stats filesWebStats off

## ImprobabilityDrive: Calculate odds-ratios for ham/spam, and add to# X-DSPAM-Improbability headers#ImprobabilityDrive on

## Preferences: Specify any preferences to set by default, unless otherwise# overridden by the user (see next section) or a default.prefs file.# If user or default.prefs are found, the user's preferences will override any# defaults.#Preference "spamAction=quarantine"Preference "signatureLocation=message" # 'message' or 'headers'Preference "showFactors=on"#Preference "spamAction=tag"#Preference "spamSubject=SPAM"

## Overrides: Specifies the user preferences which may override configuration# and commandline defaults. Any other preferences supplied by an untrusted user# will be ignored.#AllowOverride trainingModeAllowOverride spamAction spamSubjectAllowOverride statisticalSedationAllowOverride enableBNRAllowOverride enableWhitelistAllowOverride signatureLocationAllowOverride showFactorsAllowOverride optIn optOutAllowOverride whitelistThreshold

# --- MySQL ---

## Storage driver settings: Specific to a particular storage driver. Uncomment# the configuration specific to your installation, if applicable.#MySQLServer /var/run/mysqld/mysqld.sock#MySQLPortMySQLUser spamMySQLPass ******MySQLDb dspam#MySQLCompress true

# Use this if you have the 4.1 quote bug (see doc/mysql.txt)#MySQLSupressQuote on

# If you're running DSPAM in client/server (daemon) mode, uncomment the# setting below to override the default connection cache size (the number# of connections the server pools between all clients). The connection cache# represents the maximum number of database connections *available* and should# be set based on the maximum number of concurrent connections you're likely# to have. Each connection may be used by only one thread at a time, so all# other threads _will block_ until another connection becomes available.##MySQLConnectionCache 10

# If you're using vpopmail or some other type of virtual setup and wish to

Page 49: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# change the table dspam uses to perform username/uid lookups, you can over-# ride it below

#MySQLVirtualTable dspam_virtual_uids#MySQLVirtualUIDField uid#MySQLVirtualUsernameField username

# UIDInSignature: MySQL supports the insertion of the user id into the DSPAM # signature. This allows you to create one single spam or fp alias # (pointing to some arbitrary user), and the uid in the signature will# switch to the correct user. Result: you need only one spam alias

#MySQLUIDInSignature on

# --- PostgreSQL ---

#PgSQLServer 127.0.0.1#PgSQLPort 5432#PgSQLUser dspam#PgSQLPass changeme#PgSQLDb dspam

# If you're running DSPAM in client/server (daemon) mode, uncomment the# setting below to override the default connection cache size (the number# of connections the server pools between all clients).##PgSQLConnectionCache 3

# UIDInSignature: PgSQL supports the insertion of the user id into the DSPAM # signature. This allows you to create one single spam or fp alias # (pointing to some arbitrary user), and the uid in the signature will# switch to the correct user. Result: you need only one spam alias

#PgSQLUIDInSignature on

# If you're using vpopmail or some other type of virtual setup and wish to# change the table dspam uses to perform username/uid lookups, you can over-# ride it below

#PgSQLVirtualTable dspam_virtual_uids#PgSQLVirtualUIDField uid#PgSQLVirtualUsernameField username

# --- Oracle ---

#OraServer "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SID=PROD)))"#OraUser dspam#OraPass changeme#OraSchema dspam

# --- SQLite ---

#SQLitePragma "synchronous = OFF"

# --- Hash ---

# HashRecMax: Default number of records to create in the initial segment when# building hash files. 100,000 yields files 1.6MB in size, but can fill up# fast, so be sure to increase this (to a million or more) if you're not using# autoextend.## Primes List:# 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613,

Page 50: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, # 100663319, 201326611, 402653189, 805306457, 1610612741, 3221225473, # 4294967291#HashRecMax 98317

# HashAutoExtend: Autoextend hash databases when they fill up. This allows# them to continue to train by adding extents (extensions) to the file. There # will be a small delay during the growth process, as everything needs to be # closed and remapped. #HashAutoExtend on

# HashMaxExtents: The maximum number of extents that may be created in a single# hash file. Set this to zero for unlimited#HashMaxExtents 0

# HashExtentSize: The record size for newly created extents. Creating this too# small could result in many extents being created. Creating this too large# could result in excessive disk space usage.#HashExtentSize 49157

# HashMaxSeek: The maximum number of records to seek to insert a new record# before failing or adding a new extent. Setting this too high will exhaustively# scan each segment and kill performance. Typically, a low value is acceptable# as even older extents will continue to fill over time.#HashMaxSeek 100

# HashConcurrentUser: If you are using a single, stateful hash database in# daemon mode, specifying a concurrent user will cause the user to be # permanently mapped into memory and shared via rwlocks.##HashConcurrentUser user

# HashConnectionCache: If running in daemon mode, this is the max # of# concurrent connections that will be supported. NOTE: If you are using# HashConcurrentUser, this option is ignored, as all connections are read-# write locked instead of mutex locked.HashConnectionCache 10

# LDAP: Perform various LDAP functions depending on LDAPMode variable.# Presently, the only mode supported is 'verify', which will verify the existence# of an unknown user in LDAP prior to creating them as a new user in the system.# This is useful on some systems acting as gateway machines.##LDAPMode verify#LDAPHost ldaphost.mydomain.com#LDAPFilter "(mail=%u)"#LDAPBase ou=people,dc=domain,dc=com

# Optionally, you can specify storage profiles, and specify the server to# use on the commandline with --profile. For example:##Profile DECAlpha#MySQLServer.DECAlpha 10.0.0.1#MySQLPort.DECAlpha 3306#MySQLUser.DECAlpha dspam#MySQLPass.DECAlpha changeme#MySQLDb.DECAlpha dspam#MySQLCompress.DECAlpha true##Profile Sun420R

Page 51: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#MySQLServer.Sun420R 10.0.0.2#MySQLPort.Sun420R 3306#MySQLUser.Sun420R dspam#MySQLPass.Sun420R changeme#MySQLDb.Sun420R dspam#MySQLCompress.Sun420R false##DefaultProfile DECAlpha

## If you're using storage profiles, you can set failovers for each profile.# Of course, if you'll be failing over to another database, that database# must have the same information as the first. If you're using a global# database with no training, this should be relatively simple. If you're# configuring per-user data, however, you'll need to set up some type of# replication between databases.##Failover.DECAlpha SUN420R#Failover.Sun420R DECAlpha

# If the storage fails, the agent will follow each profile's failover up to# a maximum number of failover attempts. This should be set to a maximum of# the number of profiles you have, otherwise the agent could loop and try# the same profile multiple times (unless this is your desired behavior).##FailoverAttempts 1

## Ignored headers: If DSPAM is behind other tools which may add a header to# incoming emails, it may be beneficial to ignore these headers - especially# if they are coming from another spam filter. If you are _not_ using one of# these tools, however, leaving the appropriate headers commented out will# allow DSPAM to use them as telltale signs of forged email.##IgnoreHeader X-Spam-Status#IgnoreHeader X-Spam-Scanned#IgnoreHeader X-Virus-Scanner-Result

## Lookup: Perform lookups on streamlined blackhole list servers (see# http://www.nuclearelephant.com/projects/sbl/). The streamlined blacklist# server is machine-automated, unsupervised blacklisting system designed to# provide real-time and highly accurate blacklisting based on network spread.# When performing a lookup, DSPAM will automatically learn the inbound message # as spam if the source IP is listed. Until an official public RABL server is # available, this feature is only useful if you are running your own # streamlined blackhole list server for internal reporting among multiple mail # servers. Provide the name of the lookup zone below to use.## This function performs standard reverse-octet.domain lookups, and while it# will function with many RBLs, it's strongly discouraged to use those# maintained by humans as they're often inaccurate and could hurt filter# learning and accuracy.##Lookup "sbl.yourdomain.com"

## RBLInoculate: If you want to inoculate the user from RBL'd messages it would# have otherwise missed, set this to on.##RBLInoculate off

## Notifications: Enable the sending of notification emails to users (first# message, quarantine full, etc.)

Page 52: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#Notifications off

## Purge configuration: Set dspam_clean purge default options, if not otherwise# specified on the commandline#PurgeSignatures 14 # Stale signaturesPurgeNeutral 90 # Tokens with neutralish probabilitiesPurgeUnused 90 # Unused tokensPurgeHapaxes 30 # Tokens with less than 5 hits (hapaxes)PurgeHits1S 15 # Tokens with only 1 spam hitPurgeHits1I 15 # Tokens with only 1 innocent hit

## Purge configuration for SQL-based installations using purge.sql##PurgeSignature off # Specified in purge.sql#PurgeNeutral 90#PurgeUnused off # Specified in purge.sql#PurgeHapaxes off # Specified in purge.sql#PurgeHits1S off # Specified in purge.sql#PurgeHits1I off # Specified in purge.sql

## Local Mail Exchangers: Used for source address tracking, tells DSPAM which# mail exchangers are local and therefore should be ignored in the Received:# header when tracking the source of an email. Note: you should use the address# of the host as appears between brackets [ ] in the Received header.#LocalMX 127.0.0.1

## Logging: Disabling logging for users will make usage graphs unavailable to# them. Disabling system logging will make admin graphs unavailable.#SystemLog onUserLog on

## TrainPristine: for systems where the original message remains server side # and can therefore be presented in pristine format for retraining. This option# will cause DSPAM to cease all writing of signatures and DSPAM headers to the # message, and deliver the message in as pristine format as possible. This mode# REQUIRES that the original message in its pristine format (as of delivery) # be presented for retraining, as in the case of webmail, imap, or other # applications where the message is actually kept server-side during reading, # and is preserved. DO NOT use this switch unless the original message can be # presented for retraining with the ORIGINAL HEADERS and NO MODIFICATIONS.##TrainPristine on

## Opt: in or out; determines DSPAM's default filtering behavior. If this value# is set to in, users must opt-in to filtering by dropping a .dspam file in# /var/dspam/opt-in/user.dspam (or if you have homedirs configured, a .dspam# folder in their home directory). The default is opt-out, which means all # users will be filtered unless a .nodspam file is dropped in # /var/dspam/opt-out/user.nodspam#Opt out

## TrackSources: specify which (if any) source addresses to track and report# them to syslog (mail.info). This is useful if you're running a firewall or

Page 53: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

# blacklist and would like to use this information. Spam reporting also drops# RABL blacklist files (see http://www.nuclearelephant.com/projects/rabl/). ##TrackSources spam nonspam

## ParseToHeaders: In lieu of setting up individual aliases for each user,# DSPAM can be configured to automatically parse the To: address for spam and# false positive forwards. From there, it can be configured to either set the# DSPAM user based on the username specified in the header and/or change the# training class and source accordingly. The options below can be used to # customize most common types of header parsing behavior to avoid the need for# multiple aliases, or if using LMTP, aliases entirely..## ParseToHeader: Parse the To: headers of an incoming message. This must be# set to 'on' to use either of the following features.# # ChangeModeOnParse: Automatically change the class (to spam or innocent)# depending on whether spam- or notspam- was specified, and change the source# to 'error'. This is convenient if you're not using aliases at all, but# are delivering via LMTP.## ChangeUserOnParse: Automatically change the username to match that specified# in the To: header. For example, [email protected] will set the username# to bob, ignoring any --user passed in. This may not always be desirable if# you are using virtual email addresses as usernames. Options:# on or user take the portion before the @ sign only# full take everything after the initial {spam,notspam}-.##ParseToHeaders on#ChangeModeOnParse on#ChangeUserOnParse on

## Broken MTA Options: Some MTAs don't support the proper functionality# necessary. In these cases you can activate certain features in DSPAM to# compensate. 'returnCodes' causes DSPAM to return an exit code of 99 if# the message is spam, 0 if not, or a negative code if an error has occured.# Specifying 'case' causes DSPAM to force the input usernames to lowercase.# Spceifying 'lineStripping' causes DSPAM to strip ^M's from messages passed# in.##Broken returnCodes#Broken case#Broken lineStripping

## MaxMessageSize: You may specify a maximum message size for DSPAM to process.# If the message is larger than the maximum size, it will be delivered # without processing. Value is in bytes.##MaxMessageSize 4194304

## Virus Checking: If you are running clamd, DSPAM can perform stream-based# virus checking using TCP. Uncomment the values below to enable virus# checking. ## ClamAVResponse: reject (reject or drop the message with a permanent failure)# accept (accept the message and quietly drop the message)# spam (treat as spam and quarantine/tag/whatever)##ClamAVPort 3310#ClamAVHost 127.0.0.1#ClamAVResponse accept

Page 54: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

## Daemonized Server: If you are running DSPAM as a daemonized server using# --daemon, the following parameters will override the default. Use the# ServerPass option to set up accounts for each client machine. The DSPAM# server will process and deliver the message based on the parameters # specified. If you want the client machine to perform delivery, use# the --stdout option in conjunction with a local setup. ##ServerPort 24#ServerQueueSize 32#ServerPID /var/run/dspam.pid

## ServerMode specifies the type of LMTP server to start. This can be one of:# dspam: DSPAM-proprietary DLMTP server, for communicating with dspamc# standard: Standard LMTP server, for communicating with Postfix or other MTA# auto: Speak both DLMTP and LMTP; auto-detect by ServerPass.IDENT##ServerMode dspam

# If supporting DLMTP (dspam) mode, dspam clients will require authentication # as they will be passing in parameters. The idents below will be used to# determine which clients will be speaking DLMTP, so if you will be using# both LMTP and DLMTP from the same host, be sure to use something other# than the server's hostname below (which will be sent by the MTA during a # standard LMTP LHLO).# #ServerPass.Relay1 "secret"#ServerPass.Relay2 "password"

# If supporting standard LMTP mode, server parameters will need to be specified# here, as they will not be passed in by the mail server. The ServerIdent# specifies the 250 response code ident sent back to connecting clients and# should be set to the hostname of your server, or an alias.## NOTE: If you specify --user in ServerParameters, the RCPT TO will be# used only for delivery, and not set as the active user for processing.##ServerParameters "--deliver=innocent -d %u"#ServerIdent "localhost.localdomain"

# If you wish to use a local domain socket instead of a TCP socket, uncomment# the following. It is strongly recommended you use local domain sockets if# you are running the client and server on the same machine, as it eliminates# much of the bandwidth overhead.##ServerDomainSocketPath "/tmp/dspam.sock"

## Client Mode: If you are running DSPAM in client/server mode, uncomment and# set these variables. A ClientHost beginning with a / will be treated as# a domain socket.##ClientHost /tmp/dspam.sock#ClientIdent "secret@Relay1"##ClientHost 127.0.0.1#ClientPort 24#ClientIdent "secret@Relay1"

# RABLQueue: Touch files in the RABL queue# If you are a reporting streamlined blackhole list participant, you can# touch ip addresses within the directory the rabl_client process is watching.#

Page 55: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

#RABLQueue /var/spool/rabl

# DataSource: If you are using any type of data source that does not include# email-like headers (such as documents), uncomment the line below. This# will cause the entire input to be treated like a message "body"##DataSource document

# ProcessorWordFrequency: By default, words are only counted once per message.# If you are classifying large documents, however, you may wish to count once# per occurrence instead.##ProcessorWordFrequency occurrence

#Ajout manuel# ProcessorURLContext: By default, a URL context is generated for URLs, which# records their tokens as separate from words found in documents. To use# URL tokens in the same context as words, turn this feature off. #ProcessorURLContext on

# ProcessorBias: Bias causes the filter to lean more toward 'innocent', and# usually greatly reduces false positives. It is the default behavior of# most Bayesian filters (including dspam). ## NOTE: You probably DONT want this if you're using Markovian Weighting, unless# you are paranoid about false positives.#ProcessorBias on

## EOF

On modifie ou on ajoute les lignes suivantes :Trust amavisMySQLServer /var/run/mysqld/mysqld.sock#MySQLPortMySQLUser dspamMySQLPass ******MySQLDb dspam#MySQLCompress true

Créer le répertoire de dspam dans le home d’amavisd :mkdir /var/amavis/dspamchown -R amavis: /var/amavis/dspamPour activer dspam, il faut décommenter la ligne suivante dans amavisd.conf :# $dspam = 'dspam';

On relance amavisd :/etc/init.d/amavis stop && /etc/init.d/amavis startOn vérifie les logs. On doit voir :Found $dspam at /usr/local/bin/dspamOn envoie un email :On vérifie les logs, les headers des email pour les tags X-DSPAM et le remplissage de la base de données.Principe de fontionnement :Dans cette configuration, Dspam marque simplement les mails (il ajoute un tag dans le header). Pour que le filtrage devienne effectif, il faut donc indiquer à Spamassasssin le score à attribuer en fonction de la valeur du tag X-DSPAM dans le header.De préférence, il vaut mieux attendre quelques jours après l’installation de dspam afin de le laisser apprendre sur un volume de mail conséquent, avant d’activer ces rules SA.Dès que l’on estime que les tags sont pertinents dans les headers (c’est à dire que Dspam détecte bien

Page 56: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

du spam et du non-spam (ham) correctement), on peut ajouter ceci au /etc/mail/spamassassin/local.cf :header DSPAM_SPAM X-DSPAM-Result =~ /^Spam$/describe DSPAM_SPAM DSPAM claims it is spamscore DSPAM_SPAM 2.8

header DSPAM_HAM X-DSPAM-Result =~ /^Innocent$/describe DSPAM_HAM DSPAM claims it is hamscore DSPAM_HAM -0.2

On peut ameliorer les performances de la base en changeant le moteur en InnoDB : mysql -u root -p

USE dspam;ALTER TABLE dspam_preferences TYPE=InnoDB;ALTER TABLE dspam_signature_data TYPE=InnoDB;ALTER TABLE dspam_stats TYPE=InnoDB;ALTER TABLE dspam_token_data TYPE=InnoDB;ANALYZE TABLE dspam_preferences;ANALYZE TABLE dspam_signature_data;ANALYZE TABLE dspam_stats;ANALYZE TABLE dspam_token_data;

On crée les taches de maintenance de dspam :une tache cron avec le user amavis :crontab -e -u amaviset on ajoute :14 2 * * * /usr/bin/mysql -u dspam -p'******' dspam < /root/dspam-3.8.0/src/tools.mysql_drv/purge-4.1.sql

Et on modifie le fichier /root/dspam-3.8.0/src/tools.mysql_drv/purge-4.1.sql :On ajoute à la fin :START TRANSACTION;optimize table dspam_signature_data, dspam_token_data;COMMIT;

On crée une tache cron de purge des log avec le user amavis :crontab -e -u amavison ajoute :3 3 1 * * /usr/local/bin/dspam_logrotate -a 30 -v -d /var/amavis/dspam

Filtrage par extensions et type mime dans amavisdOn peut également renforcer le blocage des fichiers par extension et type mime dans amavisd, indépendamment de l’antivirus.Ce blocage est très efficace et peut être complémentaire du premier blocage par postfix sur ces fichiers (headers, body, type mime), car il utilise cette fois les capacités de décodage et de décompression d’Amavisd.Par exemple, on pourra facilement bloquer un fichier exe à l’intérieur d’un fichier zip.Voir mon fichier amavisd.conf pour des exemples de type mime et d’extensions de fichiers.Installation des signatures additionnelles pour Clam (détection du spam, phising...)Il s’agit de fichiers supplémentaires que l’on place dans le dossier /var/lib/clamav :aptitude install curl rsyncmkdir /var/tmp/clamdbchown amavis: /var/tmp/clamdbchmod 660 /var/tmp/clamdbcd /usr/sbinwget http://www.starbridge.org/spip/doc/Procmail/usr/sbin/UpdateSaneSecurity.shchmod 755 UpdateSaneSecurity.shOn lance le script :UpdateSaneSecurity.shAttention le script mets 5 minutes pour se lancer

Page 57: Serveur Mail Postfix, Amavisd, Mysql - Index of - Free

On vérifie que les fichiers sont bien présents dans le répertoire de clam :ls -l /var/lib/clamavOn doit trouver les fichiers suivants en plus des fichers classiques :MSRBL-Images.hdbMSRBL-SPAM.ndbphish.ndbphish.ndb.gzscam.ndbscam.ndb.gzOn crée une tache cron pour mettre à jour ces fichiers :crontab -e5 */4 * * * /usr/sbin/UpdateSaneSecurity.sh

Voila le serveur de mail et le filtrage sont configurés!