Pour
les deux techniques
Pour tous vos utilisateurs il faudra
créer un répertoire .spamassassin
dans chaque homedirectory, ce répertoire .spamassassin
doit avoir les droits 777 pour que l'utilisateur mail puisse y avoir
accès. Maintenant si un mail venant d'un expéditeur particulier (les
sites de vente par internet par exemple avec leur email bourré de
HTML) est considéré comme spam alors qu'il ne devrait pas l'être.
Rajoutez dans le fichier de configuration de l'utilisateur
/home/user/.spamassasin/user_prefs
la ligne
whitelist_from *@ldlc.fr
*@rueducommerce.com *@fnac.com
C'est pas des masses pratiques d'avoir
à modifier un fichier pour rajouter des adresses e-mails, on pourra
passer par webmin pour gérer les listes autorisées ou pas pour
que ça soit plus convivial
Les listes seront communes à tous les
utilisateurs et sauvegardées dans le fichier /etc/mail/spamassassin/local.cf.
Attention pour que le fichier global soit pris en compte il faudra
supprimer le fichier user_prefs. Ce n'est pas l'idéal d'avoir
à rajouter ces listes dans le fichier local.cf, du coup je les
ai placés dans un fichier /etc/mail/spamassassin/white-black-list.cf.
Petit bémol les modifications de ce fichier ne sont prises en compte
qu'en relançant SpamAssassin et non pas de manière dynamique.
Plus d'info sur le fichier de
configuration de SpamAssassin
à cet endroit http://spamassassin.org/doc/Mail_SpamAssassin_Conf.html
En plus de la méthode manuelle, il
existe une méthode automatique de classement dite auto-whitelist
qui se base sur certains algorithmes (voir par là https://cwiki.apache.org/confluence/display/SPAMASSASSIN/AutoWhitelist).
La base de donnée de cette méthode est sauvegardée dans le fichier auto-whitelist
qui se trouve sous .spamassassin de chaque utilisateur.
Pour visualiser ce qu'il y a dedans il faudra taper
sa-awl ~/.spamassassin/auto-whitelist
cela va donner quelque chose comme cela
(extrait)
12.3 (12.3/1)
-- antoine-poirier@vme-147.com|ip=37.59
15.3
(15.3/1) -- edm@e8.zonfrontek.com|ip=70.39
28.9
(28.9/1) -- geykrapulyngalwyan@outlook.com|ip=37.207
16.8
(16.8/1) -- hicks+1761@bdis.fr|ip=79.247
14.8
(14.8/1) --
investissement-residence-service-211748@vme-uyt.com|ip=81.93
11.3
(22.6/2) -- mail6@nouvelle-vision.net|ip=178.33
15.1
(15.1/1) -- mutuelle_senior@cible-directe.fr|ip=185.52
10.0
(20.0/2) -- news@unmailundeal.com|ip=212.18
2.0 (6.1/3)
-- newsletter@mabellephoto.com|ip=85.158
12.7
(12.7/1) -- protection@news7.sedem.info|ip=5.135
4.9 (4.9/1)
-- abidjahan9@gmail.com|ip=209.85
4.6 (4.6/1)
-- automated@e.airbnb.com|ip=199.7
7.2 (28.7/4)
-- bcastuae@gmail.com|ip=110.36
17.9
(17.9/1) -- contact@efsr26.info|ip=37.59
11.0
(11.0/1) -- contact@infos-pro.com|ip=8.8
Le premier chiffre est le score moyen,
entre parenthèse le premier correspond au score total des mails et le
deuxième le nombre de mails concernés. Pour supprimer un mail de la
liste on tapera
spamassassin
--remove-addr-from-whitelist=foo@bar
la commande suivante permettra de
supprimer les entrées vues moins de trois fois
sa-awl --clean --min 3 ~/.spamassassin/auto-whitelist
SpamAssassin s'interface
facilement avec sendmail, le filtrage s'opère aussi bien
à la réception qu'à l'envoi d'email de manière totalement
transparente ou presque, car il faut savoir que SpamAssassin est
assez gourmand en ressource et que ça ralentit beaucoup la réception
et l'envoi de mails.
On va récupérer ensuite une
"rustine" pour que
SpamAssassin
puisse s'interfacer avec
sendmail
sur le site
http://savannah.nongnu.org/projects/spamass-milt.
Avant d'aller plus loin, il faudra installer le package
sendmail-devel
si ce n'est pas déjà fait. On décompresse l'archive en tapant
tar xvfz spamass-milter-0.4.0.tar.gz
Cela donne le répertoire
spamass-milter-0.4.0
dans le quel on tape successivement
./configure
make
Puis en tant que root
make install
Tout d'abord on doit lancer le daemon
SpamAssassin
en tant que root
spamd -d -D -u mail -H
/var/spool/mail
-d mode daemon
-D mode debug (optionnel,
utile au tout début)
-u mail l'utilisateur mail
sera propriétaire du process.
-H le répertoire où se trouve
la base de données bayésienne
Toujours en tant que root on lance
spamass-milter en tapant
spamass-milter -u mail -p
/var/run/spamass.sock -f
On modifie à présent le fichier de configuration de
sendmail,
en supposant qu'il soit sous
/usr/share/sendmail-cf/cf
et qu'il s'appelle
config.mc
cd /usr/share/sendmail-cf/cf
On rajoute à la fin les lignes suivantes
INPUT_MAIL_FILTER(`spamassassin', `S=local:/var/run/spamass.sock,
F=, T=C:15m;S:4m;R:4m;E:10m')dnl
define(`confMILTER_MACROS_CONNECT',`t, b, j, _, {daemon_name},
{if_name}, {if_addr}')dnl
define(`confMILTER_MACROS_HELO',`s, {tls_version}, {cipher},
{cipher_bits}, {cert_subject}, {cert_issuer}')dnl
define(`confMILTER_MACROS_ENVFROM',`i, {auth_authen},
{auth_type}')dnl
define(`confMILTER_MACROS_ENVRCPT',`r, v, Z')dnl
on génère un nouveau fichier de configuration de
sendmail en tapant
m4
config.mc > /etc/mail/sendmail.cf
dans ce fichier au niveau de
# Milter options
#O Milter.LogLevel
O Milter.macros.connect=t, b, j, _, {daemon_name}, {if_name},
{if_addr}
O Milter.macros.helo=s, {tls_version}, {cipher}, {cipher_bits},
{cert_subject}, {cert_issuer}
O Milter.macros.envfrom=i, {auth_authen}, {auth_type}
O Milter.macros.envrcpt=r, v, Z
O Milter.macros.eom={msg_id}
#O Milter.macros.eoh
#O Milter.macros.data
on modifie ainsi
# Milter options
#O Milter.LogLevel
O Milter.macros.connect=t, b, j, _, {daemon_name}, {if_name},
{if_addr}
O Milter.macros.helo=s, {tls_version}, {cipher}, {cipher_bits},
{cert_subject}, {cert_issuer}
O Milter.macros.envfrom=i
O Milter.macros.envfrom=i, {auth_authen}, {auth_type}
O Milter.macros.envrcpt=r, v, Z
O Milter.macros.eom={msg_id}
#O Milter.macros.eoh
#O Milter.macros.data
cette modification est utile pour éviter ce genre d'erreur
spamass-milter[2246]: Could not retrieve sendmail macro "i"!.
Please add it to confMILTER_MACROS_ENVFROM for better spamassassin
results
On relance
sendmail
systemctl stop sendmail
systemctl start sendmail
Lancement automatique
Pour
un lancement automatique de
spamd
et
spamass-milter on créera
le fichier
spamassassin.service
qu'on place sous
/usr/lib/systemd/system/ voilà son contenu
[Unit]
Description=Spamassassin daemon
After=syslog.target
network.target
[Service]
Type=forking
ExecStart=/usr/local/bin/spamd
-d -D -u mail -H /var/spool/mail --pidfile
/var/run/spamd.pid
[Install]
WantedBy=multi-user.target
à noter que l'option -D
correspond au mode debug facultatif, maintenant pour que le service
soit lancé à chaque boot de la machine il faudra taper
systemctl enable
spamassassin.service
voillà le résultat
Created symlink from
/etc/systemd/system/multi-user.target.wants/spamassassin.service
to /usr/lib/systemd/system/spamassassin.service.
pour le lancer il suffit maintenant de taper
systemctl start spamassassin.service
A noter que si lors d'un upgrade vous obtenez
l'erreur suivante avec la commande suivante
oct. 04 20:59:54 mana.kervao.fr spamd[1634]: config: no rules were
found! Do you need to run 'sa-update'?
oct. 04 20:59:55 mana.kervao.fr spamd[1516]: child process [1634]
exited or timed out without signaling production of a PID file: exit
25...ne 2989.
il faudra penser à taper d'abord
sa-update voilà ce que donne la commande suivante
systemctl status spamassassin
● spamassassin.service - Spamassassin daemon
Loaded: loaded
(/usr/lib/systemd/system/spamassassin.service; enabled; vendor
preset: disabled)
Active: active (running) since Sat
2021-09-11 19:23:31 CEST; 6s ago
Process: 279097 ExecStart=/usr/local/bin/spamd -d
-u mail -H /var/spool/mail --pidfile /var/run/spamd.pid
(code=exited, status=0/SUCCESS)
Main PID: 279101 (spamd)
Tasks: 3 (limit: 4677)
Memory: 108.3M
CPU: 3.032s
CGroup: /system.slice/spamassassin.service
├─279101 /usr/bin/perl -T -w /usr/local/bin/spamd -d -u mail -H
/var/spool/mail --pidfile /var/run/spamd.pid
├─279105 spamd child
└─279106 spamd child
sept. 11 19:23:26 mana.kervao.fr spamd[279097]: logger: removing
stderr method
sept. 11 19:23:28 mana.kervao.fr spamd[279103]: util: setuid: ruid=0
euid=0 rgid=0 egid=0
sept. 11 19:23:30 mana.kervao.fr spamd[279104]: util: setuid: ruid=0
euid=0 rgid=0 egid=0
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: spamd: server
started on IO::Socket::IP [::1]:783, IO::Socket::IP [127.0.0.1]:783
(running version 3.4.6)
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: spamd: server pid:
279101
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: spamd: server
successfully spawned child process, pid 279105
sept. 11 19:23:31 mana.kervao.fr systemd[1]: Started Spamassassin
daemon.
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: spamd: server
successfully spawned child process, pid 279106
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: prefork: child
states: IS
sept. 11 19:23:31 mana.kervao.fr spamd[279101]: prefork: child
states: II
passons maintenant à
spamass-milter
on va créer le fichier
spamass-milter.service
sous
/usr/lib/systemd/system voici
son contenu
[Unit]
Description = Mail filter for
SpamAssassin
Wants = spamassassin.service
After = syslog.target
local-fs.target network.target remote-fs.target nss-lookup.target
spamassassin.service
Before = sendmail.service
[Service]
Type = simple
ExecStart =
/usr/local/sbin/spamass-milter -u mail -p /var/run/spamass.sock
[Install]
WantedBy = multi-user.target
maintenant pour que le service soit lancé à chaque boot de la
machine il faudra taper
systemctl enable
spamass-milter.service
voillà le résultat
Created symlink from
/etc/systemd/system/multi-user.target.wants/spamass-milter.service
to /usr/lib/systemd/system/spamass-milter.service.
pour le lancer il suffit maintenant de taper
systemctl start spamass-milter.service
voilà le résultat de la commande systemctl
status spamass-milter.service
● spamass-milter.service - Mail
filter for SpamAssassin
Loaded: loaded
(/usr/lib/systemd/system/spamass-milter.service; enabled; vendor
preset: disabled)
Active: active (running) since Sat
2021-09-11 14:08:35 CEST; 5h 15min ago
Main PID: 2094 (spamass-milter)
Tasks: 2 (limit: 4677)
Memory: 552.0K
CPU: 126ms
CGroup:
/system.slice/spamass-milter.service
└─2094 /usr/local/sbin/spamass-milter -u mail -p
/var/run/spamass.sock
sept. 11 14:08:35 mana.kervao.fr systemd[1]: Started Mail filter
for SpamAssassin.
sept. 11 14:08:35 mana.kervao.fr spamass-milter[2094]:
spamass-milter 0.4.0 starting
Fonctionnement
Voilà c'est fait, plus
besoin de modifier le fichier
.procmailrc (il peut être vide)
sendmail va s'en charger pour vous
en amont.
J'ai eu un soucis quand je récupérais les mails de mes utilisateurs,
l'utilisateur mail ne pouvant créer de fichier dans leur homedirectory
Oct 2 09:58:53 tosh
spamd[1676]: debug: open of AWL file failed: lock: 1676 cannot
create tmp lockfile
/home/olivier/.spamassassin/auto-whitelist.lock.tosh.kervao.fr.1676
for /home/olivier/.spamassassin/auto-whitelist.lock: Permission
denied
Pour résoudre cela, le répertoire .spamassassin de tous mes
utilisateurs (à créer éventuellement) appartient à
l'utilisateur mail ou de mettre les droits à 777. Pour info AWL
(autowhitelist) permet de mettre un score aux adresses email que
vous utilisez le plus pour mieux démarquer vos interlocuteurs
habituels et les autres.
Vous trouverez
ici
une idée de ce que donne
journalctl
-f avec un lancement en mode debug du daemon
spamd
à la réception d'un spam
.
A noter qu'il faut au moins 200 spams dans la base de données
bayésienne pour que le filtre puisse fonctionner. Dans le cas de la
mise à jour, vous pouvez très bien récupérer vos fichiers
bayes_seen et
bayes_toks et les placer sous
/var/spool/mail/.spamassassin avant lancement du daemon.
Voilà ce que ça donne en réception d'un spam (mode non debug) avec un
spam
sept. 12 09:22:00 mana.kervao.fr
spamd[6483]: spamd: connection from ::1 [::1]:39960 to port 783, fd
5
sept. 12 09:22:00 mana.kervao.fr spamd[6483]: spamd: processing
message <JTPAGIHLMVACQAOZRYBA@mega.nz> for olivier:8
sept. 12 09:22:01 mana.kervao.fr spamd[6682]: util: setuid: ruid=8
euid=8 rgid=12 12 12 egid=12 12 12
sept. 12 09:22:02 mana.kervao.fr spamd[6683]: util: setuid: ruid=8
euid=8 rgid=12 12 12 egid=12 12 12
sept. 12 09:22:05 mana.kervao.fr spamd[6483]: spamd: identified spam
(38.9/5.0) for olivier:8 in 4.4 seconds, 2089 bytes.
sept. 12 09:22:05 mana.kervao.fr spamd[6483]: spamd: result: Y 38 -
BAYES_50,DATE_IN_FUTURE_03_06,DCC_CHECK,DIGEST_MULTIPLE,FSL_BULK_SIG,HK_RANDOM_ENVFROM,HK_RANDOM_FROM,HK_RANDOM_REPLYTO,MIME_BOUND_DD_DIGITS,MISSING_MIMEOLE,MSGID_SPAM_CAPS,MSMAIL_PRI_ABNORMAL,PYZOR_CHECK,RAZOR2_CF_RANGE_51_100,RAZOR2_CHECK,RCVD_IN_PBL,RCVD_IN_SBL_CSS,RCVD_IN_VALIDITY_RPBL,RCVD_IN_XBL,RDNS_NONE,SPF_HELO_FAIL,URIBL_ABUSE_SURBL,URIBL_BLACK,URIBL_DBL_SPAM,URIBL_SBL
scantime=4.4,size=2089,user=olivier,uid=8,required_score=5.0,rhost=::1,raddr=::1,rport=39960,mid=<JTPAGIHLMVACQAOZRYBA@mega.nz>,bayes=0.500561,autolearn=spam
autolearn_force=no,shortcircuit=no
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) add: header: X-Spam-Flag: YES
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) add: header: X-Spam-Status: Yes, score=38.9
required=5.0
tests=BAYES_50,\n\tDATE_IN_FUTURE_03_06,DCC_CHECK,DIGEST_MULTIPLE,FSL_BULK_SIG,\n\tHK_RANDOM_ENVFROM,HK_RANDOM_FROM,HK_RANDOM_REPLYTO,\n\tMIME_BOUND_DD_DIGITS,MISSING_MIMEOLE,MSGID_SPAM_CAPS,\n\tMSMAIL_PRI_ABNORMAL,PYZOR_CHECK,RAZOR2_CF_RANGE_51_100,RAZOR2_CHECK,\n\tRCVD_IN_PBL,RCVD_IN_SBL_CSS,RCVD_IN_VALIDITY_RPBL,RCVD_IN_XBL,\n\tRDNS_NONE,SPF_HELO_FAIL,URIBL_ABUSE_SURBL,URIBL_BLACK,URIBL_DBL_SPAM,\n\tURIBL_SBL
shortcircuit=no autolearn=spam autolearn_force=no\n\tversion=3.4.6
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) add: header: X-Spam-Level:
**************************************
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) add: header: X-Spam-Checker-Version:
SpamAssassin 3.4.6 (2021-04-09) on mana.kervao.fr
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) change: header Content-Type: from
multipart/alternative;\n\tboundary="--105292551296024" to
multipart/mixed; boundary="----------=_613DAA9C.7CE1E3F3"
sept. 12 09:22:05 mana.kervao.fr sendmail[6677]: 18C7M0kH006677:
Milter (spamassassin) message: body replaced
sept. 12 09:22:05 mana.kervao.fr spamd[6479]: prefork: child states:
II
sept. 12 09:22:05 mana.kervao.fr sendmail[6684]: 18C7M0kH006677:
to=<olivier@localhost>, delay=00:00:05, xdelay=00:00:00,
mailer=local, pri=38997, dsn=2.0.0, stat=Sent
Et voilà une partie du corps d'un spam après traitement par
SpamAssassin.
Return-Path: <ymjlbdob@mega.nz>
Received: from online.net
by online.net
(8.16.1/8.16.1/Sendmail de FUNIX) with ESMTP id 18C7M0kH006677
for
<olivier@localhost>; Sun, 12 Sep 2021 09:22:00 +0200
Delivered-To: <olivier.hoarau@funix.org>
Received: from pop.online.net [62.210.16.34]
by mana.kervao.fr with POP3 (fetchmail-6.4.8)
for <olivier@localhost> (single-drop); Sun,
12 Sep 2021 09:22:00 +0200 (CEST)
Received: from exim-proxy-dc2-2.online.net ([10.41.2.92])
by exim-backend-17.online.net (Dovecot) with LMTP
id cMz4Op32PGEGDAAAi1FXbQ
for <olivier.hoarau@funix.org>; Sat, 11 Sep
2021 20:37:42 +0200
Received: from [10.41.2.137] (helo=mega.nz)
by exim-proxy-dc2-2.online.net with smtp (Exim
4.86_2)
(envelope-from <ymjlbdob@mega.nz>)
id 1mP7sU-0007yr-Eb; Sat, 11 Sep 2021 20:37:26
+0200
Received: from mega.nz ([223.240.124.148])
by mx-vit.online.net (MXproxy) ; Sat, 11 Sep 2021
20:37:41 +0200 (CEST)
X-ProXaD-SC: X-ProXaD-SC: state=SPAM score=300
Message-ID: <JTPAGIHLMVACQAOZRYBA@mega.nz>
From: "ONLINE PHARMACY" <ymjlbdob@mega.nz>
Reply-To: "CANADA-DRUGSTORE" <ymjlbdob@mega.nz>
To: <webmaster@funix.org>
Subject: Online drugs and medicine at very cheap prices
Date: Sun, 12 Sep 2021 03:33:54 -0800
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----------=_613DAA9C.7CE1E3F3"
X-Priority: 3
X-MSMail-Priority: #PRIORITY_STRING
X-online-proxy-in:
FLEX_NG9VRzBLR00wV1FPRXdXUQ==p+VqiBlqYiJEx5cmoKt6Nz4wU4ErnbRl
X-online-to: olivier.hoarau@funix.org
X-original-for: olivier.hoarau@funix.org
X-Spam-Flag: YES
X-Spam-Status: Yes, score=38.9 required=5.0 tests=BAYES_50,
DATE_IN_FUTURE_03_06,DCC_CHECK,DIGEST_MULTIPLE,FSL_BULK_SIG,
HK_RANDOM_ENVFROM,HK_RANDOM_FROM,HK_RANDOM_REPLYTO,
MIME_BOUND_DD_DIGITS,MISSING_MIMEOLE,MSGID_SPAM_CAPS,
MSMAIL_PRI_ABNORMAL,PYZOR_CHECK,RAZOR2_CF_RANGE_51_100,RAZOR2_CHECK,
RCVD_IN_PBL,RCVD_IN_SBL_CSS,RCVD_IN_VALIDITY_RPBL,RCVD_IN_XBL,
RDNS_NONE,SPF_HELO_FAIL,URIBL_ABUSE_SURBL,URIBL_BLACK,URIBL_DBL_SPAM,
URIBL_SBL shortcircuit=no autolearn=spam
autolearn_force=no
version=3.4.6
X-Spam-Level: **************************************
X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on
mana.kervao.fr
This is a multi-part message in MIME format.
------------=_613DAA9C.7CE1E3F3
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
------------------ Début de Rapport SpamAssassin
---------------------
Ce message est probablement du SPAM (message non sollicité envoyé en
masse, publicité, escroquerie...).
Cette notice a été ajoutée par le système d'analyse "SpamAssassin"
sur
votre serveur de courrier "mana.kervao.fr", pour vous
aider à identifier ce type de messages.
Le système SpamAssassin ajoute un en-tête "X-Spam-Flag: YES" aux
messages qu'il considère comme étant probablement du Spam.
Vous pouvez si vous le souhaitez utiliser cette caractéristique
pour régler un filtre dans votre logiciel de lecture de courrier,
afin de détruire ou de classer à part ce type de message.
Si ce robot a classifié incorrectement un message qui vous était
destiné, ou pour toute question, veuillez contacter l'administrateur
du système par e-mail à olivier .
Voir https://spamassassin.apache.org/tag/ pour plus de détails (en
anglais).
Détails de l'analyse du message: (38.9 points, 5.0
requis)
0.8
BAYES_50
BODY: L'algorithme Bayésien a évalué la probabilité de
spam entre 40 et 60%
[score: 0.5006]
1.4 MIME_BOUND_DD_DIGITS Spam tool pattern in MIME
boundary
1.0 HK_RANDOM_ENVFROM Envelope
sender username looks random
3.1 MSGID_SPAM_CAPS
Spam tool Message-Id: (caps variant)
1.0
HK_RANDOM_FROM From
username looks random
1.0 HK_RANDOM_REPLYTO Reply-To
username looks random
2.5
URIBL_DBL_SPAM
Contains a spam URL listed in the Spamhaus DBL
blocklist
[URIs: healingfirstmall.ru]
3.3
RCVD_IN_PBL
RBL: Received via a relay in Spamhaus PBL
[223.240.124.148 listed in zen.spamhaus.org]
0.4
RCVD_IN_XBL
RBL: Received via a relay in Spamhaus XBL
3.3 RCVD_IN_SBL_CSS
RBL: Received via a relay in Spamhaus SBL-CSS
3.0 DATE_IN_FUTURE_03_06 Date: est 3 à 6 heures
après la date de
l'en-tête Received:
1.2 URIBL_ABUSE_SURBL Contains
an URL listed in the ABUSE SURBL
blocklist
[URIs: healingfirstmall.ru]
1.3 RCVD_IN_VALIDITY_RPBL RBL: Relay in Validity RPBL,
https://senderscore.org/blocklistlookup/
[223.240.124.148 listed in bl.score.senderscore.com]
1.7
URIBL_BLACK
Contains an URL listed in the URIBL blacklist
[URIs: healingfirstmall.ru]
0.0
SPF_HELO_FAIL
SPF: HELO does not match SPF record (fail)
[SPF failed: Please see
http://www.openspf.org/Why?s=helo;id=mega.nz;ip=223.240.124.148;r=mana.kervao.fr]
1.1
DCC_CHECK
Message listé par DCC:
http://www.www.dcc-servers.net/dcc/
1.6
URIBL_SBL
Contains an URL's NS IP listed in the Spamhaus SBL
blocklist
[URIs: healingfirstmall.ru]
0.9
RAZOR2_CHECK
Message listé par Razor2, voir
http://razor.sourceforge.net
1.9 RAZOR2_CF_RANGE_51_100 Razor2 donne un indice de confiance
entre
51 et 100
[cf: 100]
1.4
PYZOR_CHECK
Message listé par Pyzor, voir
https://pyzor.readthedocs.io/en/latest/
1.9 MISSING_MIMEOLE
Possède un en-tête X-MSMail-Priority, mais pas
de X-MimeOLE
… escamotage de 1 ligne
0.3 DIGEST_MULTIPLE
Message hits more than one network digest check
0.8
RDNS_NONE
Delivered to internal network by a host with no rDNS
1.4 MSMAIL_PRI_ABNORMAL Email priority often
abused
-------------------- Fin de Rapport SpamAssassin
---------------------
Le message original n'étant pas au format text brut, il est
peut-être
dangereux de l'ouvrir avec votre logiciel e-mail ; en particulier il
pourrait contenir un virus, ou confirmer à l'expéditeur que votre
adresse e-mail est active, et peut recevoir du spam. Si vous voulez
lire ce message, et n'êtes pas certain de la sécurité de votre
logiciel
e-mail, il est plus prudent d'enregistrer ce message sur votre
disque
dur, et de l'afficher ensuite avec un éditeur de texte.
Chaque mail reçoit les informations suivantes en en tête du
style
X-Spam-Flag: YES
X-Spam-Status: Yes, score=30.2 required=4.0
tests=BAYES_99,BAYES_999,
CK_HELO_DYNAMIC_SPLIT_IP,CK_HELO_GENERIC,GOOG_REDIR_NORDNS,
HELO_DYNAMIC_IPADDR2,HTML_MESSAGE,HTTP_EXCESSIVE_ESCAPES,IMPOTENCE,
MIME_HTML_ONLY,RCVD_IN_BRBL_LASTEXT,RCVD_IN_PBL,RCVD_IN_RP_RNBL,RCVD_IN_XBL,
RDNS_NONE,TVD_RCVD_SPACE_BRACKET,T_ANY_PILL_PRICE,UNPARSEABLE_RELAY,
URIBL_BLACK,URIBL_DBL_SPAM,URIBL_JP_SURBL,URIBL_SBL,URIBL_SBL_A,
URIBL_WS_SURBL
autolearn=unavailable autolearn_force=no version=3.4.1
X-Spam-Level: ******************************
X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on
mana.kervao.fr
En cas de réception de mail en langue
arabe ou chinois, vous allez voir apparaître dans le rapport spamassassin
en plus cette mention
10 UNWANTED_LANGUAGE_BODY BODY:
Message dans une langue non désirée
(config locale)
et dans le corps du mail on retrouve UNWANTED_LANGUAGE_BODY
X-Spam-Flag: YES
X-Spam-Status: Yes, score=11.7 required=5.0
tests=BAYES_40,DKIM_SIGNED,
DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_ENVFROM_END_DIGIT,
FREEMAIL_FROM,HTML_MESSAGE,NO_RDNS_DOTCOM_HELO,RCVD_IN_DNSWL_NONE,
RDNS_NONE,SPF_HELO_NONE,UNWANTED_LANGUAGE_BODY shortcircuit=no
autolearn=no
autolearn_force=no version=3.4.6
X-Spam-Level: ***********
Il peut arriver que vous ayez un spam qui
ne soit pas analysé par spamassassin, dans les logs vous allez avoir
le message suivant
févr. 12 02:36:41 ultra.kervao.fr
spamc[3659916]: skipped message, greater than max message size
(512000 bytes)
En fait c'est une petite faille du
système, par défaut spamc ne va pas analyser le mail dès lors
que la taille du fichier dépasse 512ko, les spammeurs profitent de
cela et attachent une image de quelques Mo pour passer au travers. Il
suffit donc d'augmenter la taille en créant le fichier
/etc/mail/spamassassin/spamc.conf qui contiendra
-s 5000000
Si la blacklist a bien été prise en
compte vous devriez voir quelque chose comme cela
Détails de l'analyse du
message: (100.0 points, 5.0 requis)
0.0
SHORTCIRCUIT
Not all rules were run, due to a shortcircuited
rule
100 USER_IN_BLACKLIST From:
address is in the user's black-list
et voilà ce que ce qu'on retrouve dans le
corps du mail pour un expéditeur qui se trouve dans la whitelist
X-Spam-Status: No, score=-100.0
required=5.0 tests=SHORTCIRCUIT,
USER_IN_WELCOMELIST,USER_IN_WHITELIST shortcircuit=ham
autolearn=disabled
version=3.4.6
L'activation
du
shortcircuit (cour circuit) permet de stopper tous les
tests dès lors que l'expéditeur se trouve dans la blacklist ou dans
la whitelist. A présent vous devez aider
SpamAssassin
à identifier les spams en lui indiquant les mails qui auraient
du être qualifiés de spam et ceux qui n'auraient pas du être
identifiés comme spam. Avec la technique
procmail/
kmail qui me sert à lire
la boîte aux lettres de spam, j'ai créé un dossier
fauxspams
où je déplace les mails qui n'auraient pas du être classés comme
spams.
Maintenant la commande à
taper en tant que root pour qu'il ne prenne plus en compte les mails
comme spams est la suivante
sa-learn --ham --dir /home/olivier/.Mail/fauxspam/cur
Avec la technique
thunderbird qui me sert à lire la boîte aux lettres
des mails normaux, j'ai créé deux répertoires spams
et fauxspams dans lequel je
déplace les mails qui auraient dû être classés comme spam.
Maintenant la commande à taper en tant que root pour qu'il ne
prenne plus en compte les mails comme spams est la suivante
/usr/local/bin/sa-learn --ham --dir /export/home/user/fauxspams
/usr/local/bin/sa-learn --spam --dir /export/home/user/spams
Voilà le résultat
Learned from 3 message(s) (3 message(s) examined).
Pour automatiser tout cela vous
pouvez créer le fichir
/etc/cron.daily/bayes contenant
#!/bin/bash
/usr/local/bin/sa-learn --ham --dir
/export/home/user1/fauxspams
/usr/local/bin/sa-learn --spam --dir /export/home/user1/spams
/usr/local/bin/sa-learn --ham
--dir /export/home/user2/fauxspams
/usr/local/bin/sa-learn --spam --dir /export/home/user2/spams
Et lui donner des droits en exécution
chmod 755 /etc/cron.daily/bayes
Si dans un mail classé comme spam, je
vois dans les entêtes
-2.3
AWL
AWL: From: address is in the auto white-list
c'est qu'il n'a pas été considéré comme
spam au titre de l'auto whitelist, dans ce cas il faudra déplacer le
mail dans le répertoire spams pour apprentissage ou simplement
rajouter l'expéditeur dans la blacklist.
Autres astuces si vous voulez sauvegarder
votre base de données bayes il faudra taper
sa-learn --backup >
base-bayes.txt
puis pour la restaurer
sa-learn --restore base-bayes.txt
Cette sauvegarde peut être évidemment
automatisée. Pour voir ce que la base contient on tapera
sa-learn --dump magic
voilà le résultat
0.000
0
3 0
non-token data: bayes db version
0.000
0
9041 0
non-token data: nspam
0.000
0
12164 0
non-token data: nham
0.000
0
171108 0
non-token data: ntokens
0.000 0
1603119662
0 non-token data: oldest atime
0.000 0
1605952921
0 non-token data: newest atime
0.000 0
1605952891
0 non-token data: last journal sync atime
0.000 0
1605927677
0 non-token data: last expiry atime
0.000
0
2764800
0 non-token data: last expire atime delta
0.000
0
3481 0
non-token data: last expire reduction count
Dans l'exemple ci-dessus, il y a 9041
spams et 12164 non spams et 171108 "tokens" les tokens sont des
éléments qui caractérisent le spam ou a contrario le non spam.
A noter que si vous obtenez cela dans les
logs
févr. 23
11:58:10 mana.kervao.fr spamd[1635]: dns: sendto() to [127.0.0.1]:53
failed: Connection refused, failing over to [::1]:53
févr. 23 11:58:10 mana.kervao.fr spamd[1635]: dns: sendto() to
[::1]:53 failed: Connection refused, failing over to [127.0.0.1]:53
févr. 23 11:58:10 mana.kervao.fr spamd[1635]: dns: bad dns reply:
bgread: recv() failed: Connection refused at
/usr/local/share/perl5/Mail/SpamAssassin/DnsResolver.pm line 742,
<GEN353> line 525.
févr. 23 11:58:10 mana.kervao.fr spamd[1635]: dns: bad dns reply:
bgread: recv() failed: Connection refused at
/usr/local/share/perl5/Mail/SpamAssassin/DnsResolver.pm line 742.
c'est que SpamAssassin s'est
lancé avant que le service DNS soit opérationnel, il suffit de
relancer le service spamd pour supprimer l'erreur.
Mettre
en
place un anti virus
Présentation et
installation
Clam Anti virus (
clamav)
comme son nom l'indique est un anti virus qui est totalement libre, le
site officiel est
http://www.clamav.net/
on y récupérera l'archive qu'on décompresse en tapant
tar xvfz clamav-1.0.0.tar.gz
Cela donne
clamav-1.0.0 avant
d'aller
plus
loin vous pouvez récupérer la trés bonne documentation
disponible à cet endroit
http://wiki.clamav.net/Main/WebHome.
En suivant les instructions on doit d'abord en tant que root créer un
utilisateur
clamav
groupadd
clamav
useradd -g clamav -s /bin/false -c
"Clam Anti Virus" clamav
Ensuite en tant que simple utilisateur dans le répertoire clamav-0.105.1
on doit taper
mkdir build
cd build
cmake
..
il sera peut être nécessaire
d'installer les packages lib64pcre2-devel, cargo, rust,
lib64check-devel, lib64json-c-devel et sendmail-devel
et python3-pytest
voilà le résultat
-- Configuration Options Summary --
Package
Version: ClamAV 1.0.0
libclamav version:
11:0:0
libfreshclam version: 2:2:0
Install
prefix: /usr/local
Install database dir:
/usr/local/share/clamav
Install config dir:
/usr/local/etc
Host
system:
Linux-5.15.50-desktop-1.mga8
Target
system:
Linux-5.15.50-desktop-1.mga8
Compiler:
Build
type: RelWithDebInfo
C
compiler:
/usr/bin/cc
C++
compiler: /usr/bin/c++
Rust
toolchain: /usr/bin/cargo (1.60.0)
CFLAGS:
-O2 -g
CXXFLAGS:
-O2 -g
WARNCFLAGS:
-Wall -Wextra -Wformat-security
Build
Options:
Build
apps: ON
Shared
library: ON
Static
library: OFF
Enable
UnRAR: ON
Examples:
OFF
Tests:
ON
Build man
pages: ON
Build doxygen HTML: OFF
Maintainer
Mode: OFF
Build
Extras:
Build
milter: ON (toggle with
-DENABLE_MILTER=ON/OFF)
Build
clamonacc: ON (toggle with
-DENABLE_CLAMONACC=ON/OFF)
-- Engine Options --
Bytecode
Runtime:
interpreter
-- Test Dependencies --
Unit Test Framework:
libcheck /usr/include
/usr/lib64/libcheck.so
Feature Test Framework:
python3
/usr/bin/python3.8
test command pytest;-v
-- libclamav Dependencies --
Compression support:
bzip2
/usr/include
/usr/lib64/libbz2.so
zlib
/usr/include
/usr/lib64/libz.so
XML
support:
libxml2
/usr/include/libxml2;/usr/include/libxml2
/usr/lib64/libxml2.so
RegEx
support:
libpcre2 /usr/include
/usr/lib64/libpcre2-8.so
Crypto
support:
openssl /usr/include
/usr/lib64/libssl.so;/usr/lib64/libcrypto.so
JSON
support:
json-c
/usr/include/json-c
/usr/lib64/libjson-c.so
Threading support:
pthread
Locale
support:
iconv
/usr/include
/usr/lib64/libc.so
-- libfreshclam Extra Dependencies --
HTTP
support:
curl
/usr/include
/usr/lib64/libcurl.so
-- Application Extra Dependencies --
GUI
support:
ncurses /usr/include
/usr/lib64/libncurses.so;/usr/lib64/libtinfo.so
systemd:
not found
Milter
Support:
libmilter /usr/include
/usr/lib64/libmilter.so
-- Warning: libjson-c is known to
share symbol names with other JSON libraries which may result in
crashes for applications that use libclamav. Consider providing a
static json-c library that was compiled with: CFLAGS="-fPIC".
Default build settings for json-c 0.15+ should also work. Use the
`-DENABLE_JSON_SHARED=OFF` option to prefer detection of the static
library, or use -DJSONC_INCLUDE_DIR and -DJSONC_LIBRARY to specify
the static JSON library.
-- Configuring done
-- Generating done
-- Build files have been written to:
/usr/local/linux/mail/clamav-1.0.0/build
j'ai passé outre l'avertissement car la
compilation se passe mal si je rajoute l'option -DENABLE_JSON_SHARED=OFF
On tape ensuite
make
puis en tant que root
make install
On rajoute si ce n'est déjé fait la ligne
/usr/local/lib (et
/usr/local/lib64 pour une version 64bits) dans le fichier
/etc/ld.so.conf et on tape
ldconfig
Maintenant on crée le répertoire de log de
clamav,
l'utilisateur
clamav doit en
étre propriétaire
mkdir /var/log/clamav
chown clamav:clamav /var/log/clamav
Configuration
On édite le fichier
/usr/local/etc/clamd.conf
voici comment je l'ai configuré
##
## 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.
#Example
# Uncomment this option to enable
logging.
# LogFile must be writable for the
user running daemon.
# A full path is required.
# Default: disabled
#LogFile /tmp/clamd.log
LogFile /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. If LogFileMaxSize is enabled, log
# rotation (the LogRotate option)
will always be enabled.
# Default: 1M
LogFileMaxSize 2M
# Log time with each message.
# Default: no
#LogTime 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
# Enable log rotation. Always
enabled when LogFileMaxSize is enabled.
# Default: no
#LogRotate yes
# Log additional information about
the infected file, such as its
# size and hash, together with the
virus name.
#ExtendedDetectionInfo yes
# This option allows you to save a
process identifier of the listening
# daemon (main thread).
# Default: disabled
PidFile /var/log/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.
# Default: hardcoded (depends on
installation options)
DatabaseDirectory
/usr/local/share/clamav
# Only load the official signatures
published by the ClamAV project.
# Default: no
#OfficialDatabaseOnly no
# The daemon can work in local
mode, network mode or both.
# 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 /tmp/clamd.socket
LocalSocket
/var/log/clamav/clamd.sock
# Sets the group ownership on the
unix socket.
# Default: disabled (the primary
group of the user running clamd)
#LocalSocketGroup virusgroup
# Sets the permissions on the unix
socket to the specified mode.
# Default: disabled (socket is
world accessible)
#LocalSocketMode 660
# Remove stale socket after unclean
shutdown.
# Default: yes
FixStaleSocket 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. This
option can be specified multiple
# times if you want to listen on
multiple IPs. IPv6 is now supported.
# Default: no
#TCPAddr 127.0.0.1
# Maximum length the queue of
pending connections may grow to.
# Default: 200
#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: 25M
#StreamMaxLength 10M
# 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).
# Default: 120
ReadTimeout 300
# This option specifies the time
(in seconds) after which clamd should
# timeout if a client doesn't
provide any initial command after connecting.
# Default: 5
#CommandReadTimeout 5
# This option specifies how long to
wait (in miliseconds) if the send buffer is full.
# Keep this value low to prevent
clamd hanging
#
# Default: 500
#SendBufTimeout 200
# Maximum number of queued items
(including those being processed by MaxThreads threads)
# It is recommended to have this
value at least twice MaxThreads if possible.
# WARNING: you shouldn't increase
this too much to avoid running out of file descriptors,
# the following condition should
hold:
# MaxThreads*MaxRecursion +
(MaxQueue - MaxThreads) + 6< RLIMIT_NOFILE (usual max is 1024)
#
# Default: 100
#MaxQueue 200
# Waiting for a new job will
timeout after this time (seconds).
# Default: 30
#IdleTimeout 60
# Don't scan files and directories
matching regex
# This directive can be used
multiple times
# Default: scan all
#ExcludePath ^/proc/
#ExcludePath ^/sys/
# Maximum depth directories are
scanned at.
# Default: 15
#MaxDirectoryRecursion 20
# Follow directory symlinks.
# Default: no
#FollowDirectorySymlinks yes
# Follow regular file symlinks.
# Default: no
#FollowFileSymlinks yes
# Scan files and directories on
other filesystems.
# Default: yes
#CrossFilesystems yes
# Perform a database check.
# Default: 600 (10 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 privileges
User clamav
# Initialize supplementary group
access (clamd must be started by root).
# Default: no
#AllowSupplementaryGroups no
# 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
# Permit use of the ALLMATCHSCAN
command. If set to no, clamd will reject
# any ALLMATCHSCAN command as
invalid.
# Default: yes
#AllowAllMatchScan no
# Detect Possibly Unwanted
Applications.
# Default: no
#DetectPUA yes
# Exclude a specific PUA category.
This directive can be used multiple times.
# See
https://github.com/vrtadmin/clamav-faq/blob/master/faq/faq-pua.md
for
# the complete list of PUA
categories.
# Default: Load all categories (if
DetectPUA is activated)
#ExcludePUA NetTool
#ExcludePUA PWTool
# Only include a specific PUA
category. This directive can be used multiple
# times.
# Default: Load all categories (if
DetectPUA is activated)
#IncludePUA Spy
#IncludePUA Scanner
#IncludePUA RAT
# 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
# This option causes memory or
nested map scans to dump the content to disk.
# If you turn on this option, more
data is written to disk and is available
# when the LeaveTemporaryFiles
option is enabled.
#ForceToDisk yes
# This option allows you to disable
the caching feature of the engine. By
# default, the engine will store an
MD5 in a cache of any files that are
# not flagged as virus or that hit
limits checks. Disabling the cache will
# have a negative performance
impact on large scans.
# Default: no
#DisableCache 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. If you turn off this
option, the original files will still be
# scanned, but without additional
processing.
# Default: yes
ScanPE yes
# Certain PE files contain an
authenticode signature. By default, we check
# the signature chain in the PE
file against a database of trusted and
# revoked certificates if the file
being scanned is marked as a virus.
# If any certificate in the chain
validates against any trusted root, but
# does not match any revoked
certificate, the file is marked as whitelisted.
# If the file does match a revoked
certificate, the file is marked as virus.
# The following setting completely
turns off authenticode verification.
# Default: no
#DisableCertCheck yes
# Executable and Linking Format is
a standard format for UN*X executables.
# This option allows you to control
the scanning of ELF files.
# If you turn off this option, the
original files will still be scanned, but
# without additional processing.
# Default: yes
ScanELF yes
# With this option clamav will try
to detect broken executables (both PE and
# 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.
# If you turn off this option, the
original files will still be scanned, but
# without additional processing.
# Default: yes
ScanOLE2 yes
# With this option enabled OLE2
files with VBA macros, which were not
# detected by signatures will be
marked as "Heuristics.OLE2.ContainsMacros".
# Default: no
#OLE2BlockMacros no
# This option enables scanning
within PDF files.
# If you turn off this option, the
original files will still be scanned, but
# without decoding and additional
processing.
# Default: yes
ScanPDF yes
# This option enables scanning
within SWF files.
# If you turn off this option, the
original files will still be scanned, but
# without decoding and additional
processing.
# Default: yes
ScanSWF yes
##
## Mail files
##
# Enable internal e-mail scanner.
# If you turn off this option, the
original files will still be scanned, but
# without parsing individual
messages/attachments.
# Default: yes
ScanMail yes
# Scan RFC1341 messages split over
many emails.
# You will need to periodically
clean up $TemporaryDirectory/clamav-partial directory.
# WARNING: This option may open
your system to a DoS attack.
#
Never use it on loaded servers.
# Default: no
ScanPartialMessages yes
# 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
# 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
# Detect partition intersections in
raw disk images using heuristics.
# Default: no
#PartitionIntersection no
# Allow heuristic match to take
precedence.
# When enabled, if a heuristic scan
(such as phishingScan) detects
# a possible virus/phish it will
stop scan immediately. Recommended, saves CPU
# scan-time.
# When disabled, virus/phish
detected by heuristic scans will be reported only at
# the end of a scan. If an archive
contains both a heuristically detected
# virus/phish, and a real malware,
the real malware will be reported
#
# Keep this disabled if you intend
to handle "*.Heuristics.*" viruses
# differently from "real" malware.
# If a non-heuristically-detected
virus (signature-based) is found first,
# the scan is interrupted
immediately, regardless of this config option.
#
# Default: no
#HeuristicScanPrecedence yes
##
## Data Loss Prevention (DLP)
##
# Enable the DLP module
# Default: No
#StructuredDataDetection yes
# This option sets the lowest
number of Credit Card numbers found in a file
# to generate a detect.
# Default: 3
#StructuredMinCreditCardCount 5
# This option sets the lowest
number of Social Security Numbers found
# in a file to generate a detect.
# Default: 3
#StructuredMinSSNCount 5
# With this option enabled the DLP
module will search for valid
# SSNs formatted as xxx-yy-zzzz
# Default: yes
#StructuredSSNFormatNormal yes
# With this option enabled the DLP
module will search for valid
# SSNs formatted as xxxyyzzzz
# Default: no
#StructuredSSNFormatStripped yes
##
## HTML
##
# Perform HTML normalisation and
decryption of MS Script Encoder code.
# Default: yes
# If you turn off this option, the
original files will still be scanned, but
# without additional processing.
#ScanHTML yes
##
## Archives
##
# ClamAV can scan within archives
and compressed files.
# If you turn off this option, the
original files will still be scanned, but
# without unpacking and additional
processing.
# Default: yes
ScanArchive yes
# Mark encrypted archives as
viruses (Encrypted.Zip, Encrypted.RAR).
# Default: no
#ArchiveBlockEncrypted no
##
## Limits
##
# The options below protect your
system against Denial of Service attacks
# using archive bombs.
# This option sets the maximum
amount of data to be scanned for each input file.
# Archives and other containers are
recursively extracted and scanned up to this
# value.
# Value of 0 disables the limit
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 100M
#MaxScanSize 150M
# Files larger than this limit
won't be scanned. Affects the input file itself
# as well as files contained inside
it (when the input file is an archive, a
# document or some other kind of
container).
# Value of 0 disables the limit.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 25M
#MaxFileSize 30M
# 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.
# Note: setting this limit too high
may result in severe damage to the system.
# Default: 16
#MaxRecursion 10
# Number of files to be scanned
within an archive, a document, or any other
# container file.
# Value of 0 disables the limit.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 10000
#MaxFiles 15000
# Maximum size of a file to check
for embedded PE. Files larger than this value
# will skip the additional analysis
step.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 10M
#MaxEmbeddedPE 10M
# Maximum size of a HTML file to
normalize. HTML files larger than this value
# will not be normalized or
scanned.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 10M
#MaxHTMLNormalize 10M
# Maximum size of a normalized HTML
file to scan. HTML files larger than this
# value after normalization will
not be scanned.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 2M
#MaxHTMLNoTags 2M
# Maximum size of a script file to
normalize. Script content larger than this
# value will not be normalized or
scanned.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 5M
#MaxScriptNormalize 5M
# Maximum size of a ZIP file to
reanalyze type recognition. ZIP files larger
# than this value will skip the
step to potentially reanalyze as PE.
# Note: disabling this limit or
setting it too high may result in severe damage
# to the system.
# Default: 1M
#MaxZipTypeRcg 1M
# This option sets the maximum
number of partitions of a raw disk image to be scanned.
# Raw disk images with more
partitions than this value will have up to the value number
# partitions scanned. Negative
values are not allowed.
# Note: setting this limit too high
may result in severe damage or impact performance.
# Default: 50
#MaxPartitions 128
# This option sets the maximum
number of icons within a PE to be scanned.
# PE files with more icons than
this value will have up to the value number icons scanned.
# Negative values are not allowed.
# WARNING: setting this limit too
high may result in severe damage or impact performance.
# Default: 100
#MaxIconsPE 200
##
## On-access Scan Settings
##
# Enable on-access scanning.
Currently, this is supported via fanotify.
# Clamuko/Dazuko support has been
deprecated.
# Default: no
#ScanOnAccess yes
# Don't scan files larger than
OnAccessMaxFileSize
# Value of 0 disables the limit.
# Default: 5M
#OnAccessMaxFileSize 10M
# Set the include paths (all files
inside them will be scanned). You can have
# multiple OnAccessIncludePath
directives but each directory must be added
# in a separate line. (On-access
scan only)
# Default: disabled
#OnAccessIncludePath /home
#OnAccessIncludePath /students
# Set the exclude paths. All
subdirectories are also excluded.
# (On-access scan only)
# Default: disabled
#OnAccessExcludePath /home/bofh
# With this option you can
whitelist specific UIDs. Processes with these UIDs
# will be able to access all files.
# This option can be used multiple
times (one per line).
# Default: disabled
#OnAccessExcludeUID 0
##
## Bytecode
##
# With this option enabled ClamAV
will load bytecode from the database.
# It is highly recommended you keep
this option on, otherwise you'll miss detections for many new
viruses.
# Default: yes
Bytecode yes
# Set bytecode security level.
# Possible values:
#
None - no security at all, meant for debugging. DO NOT USE THIS ON
PRODUCTION SYSTEMS
#
This value is only available if clamav was built with
--enable-debug!
#
TrustSigned - trust bytecode loaded from signed .c[lv]d files,
#
insert
runtime safety checks for bytecode loaded from other sources
#
Paranoid - don't trust any bytecode, insert runtime checks for all
# Recommended: TrustSigned, because
bytecode in .cvd files already has these checks
# Note that by default only signed
bytecode is loaded, currently you can only
# load unsigned bytecode in
--enable-debug mode.
#
# Default: TrustSigned
#BytecodeSecurity TrustSigned
# Set bytecode timeout in
miliseconds.
#
# Default: 5000
# BytecodeTimeout 1000
##
## Statistics gathering and
submitting
##
# Enable statistical reporting.
# Default: no
#StatsEnabled yes
# Disable submission of individual
PE sections for files flagged as malware.
# Default: no
#StatsPEDisabled yes
# HostID in the form of an UUID to
use when submitting statistical information.
# Default: auto
#StatsHostID auto
# Time in seconds to wait for the
stats server to come back with a response
# Default: 10
#StatsTimeout 10
Le fichier de configuration de
clamav-milter
s'appelle
/usr/local/etc/clamav-milter.conf
le voici, voilà les lignes que j'ai modifiées
#Example
MilterSocket
/var/log/clamav/clmilter.sock
ClamdSocket
unix:/var/log/clamav/clamd.sock
AddHeader Replace
LogFile
/var/log/clamav/clamav-milter.log
pour le reste tout est en commentaire
On configure maintenant le fichier
/usr/local/etc/freshclam.conf
en mettant en commentaire la ligne suivante
#Example
Puis en modifiant la ligne suivante conformément à ce qui
a été défini dans le fichier
clamd.conf
# définition de la base des données des virus
DatabaseDirectory /usr/local/share/clamav
J'ai modifié ensuite les lignes suivantes
# définition du fichier de log de
freshclam
UpdateLogFile /var/log/clamav/freshclam.log
# serveur miroir à contacter pour
récupérer les mises oà jour
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
on pensera à créer préalablement les fichiers de log
touch /var/log/clamav/clamd.log
touch /var/log/clamav/freshclam.log
touch /var/log/clamav/clamav-milter.log
clamav doit être le propriétaire des deux premiers fichiers
chown clamav:clamav /var/log/clamav/clamd.log
chown clamav:clamav /var/log/clamav/freshclam.log
on doit créer préalablement le répertoire contenant la base de
données des virus et clamav doit
en être propriétaire
mkdir /usr/local/share/clamav
chown clamav:clamav /usr/local/share/clamav
La commande freshclam
permet de mettre à jour la base de données à partir
d'informations récupérées sur internet, en tant que root tapez freshclam voilà le résultat:
ClamAV update process started at Sat Sep 11
20:28:42 2021
daily database available for update (local version: 26290, remote
version: 26291)
Current database is 1 version behind.
Downloading database patch # 26291...
Time: 0.2s, ETA: 0.0s
[========================>] 17.73KiB/17.73KiB
Testing database:
'usr/local/share/clamav/tmp.5de5da9833/clamav-52dabdec3bbe9561999e684abb126f7b.tmp-daily.cld'
...
Database test passed.
daily.cld updated (version: 26291, sigs: 1971981, f-level: 90,
builder: raynman)
main.cld database is up-to-date (version: 61, sigs: 6607162,
f-level: 90, builder: sigmgr)
bytecode.cld database is up-to-date (version: 333, sigs: 92,
f-level: 63, builder: awillia2)
Pour information quand cette commande
est lancée c'est l'utilisateur
clamav
qui devient propriétaire du process.
Premiers tests
On lance maintenant
clamd en
tant que root
clamd
On va faire un test maintenant sur le répertoire
clamav-0.104.1
en tant que simple utilisateur
clamscan -r -l log.txt
clamav-0.104.1/
L'option -r
permet d'avoir une recherche récursive (à travers le répertoire et
ses sous répertoires), -l pour
logger dans le fichier log.txt.
Voilà un extrait du contenu du dit-fichier aprés l'exécution
de la commande
----------- SCAN SUMMARY -----------
Known viruses: 8573774
Engine version: 0.105.1
Scanned directories: 277
Scanned files: 2630
Infected files: 49
Data scanned: 120.16 MB
Data read: 84.88 MB (ratio 1.42:1)
Time: 86.862 sec (1 m 26 s)
Start Date: 2021:11:04 18:42:38
End Date: 2021:11:04 18:44:04
Il y a des virus qui ont été
volontairement placés dans ce répertoire pour mener des essais. Pour
scanner le répertoire de mail
/var/spool/mail
il faudra être root et rajouter l'option
--mbox.
Lancement automatique
On peut configurer un lancement
automatique pour les mises à jour de la base de donnée avec cron, pour une mise à jour
tous les jours on créera dans le fichier
/etc/cron.daily le fichier freshclam
#!/bin/bash
/usr/local/bin/freshclam --quiet -l
/var/log/clamav/clam-update.log
Avec les droits d'exécution
chmod 755 freshclam
On va créer maintenant un fichier de log pour les mises à jour
et rendre l'utilisateur
clamav
propriétaire
touch /var/log/clamav/clam-update.log
chmod 600
/var/log/clamav/clam-update.log
chown clamav:clamav
/var/log/clamav/clam-update.log
Autre solution pour un lancement simple en tant que daemon (lancement
six fois par jour) on tape
freshclam -d -c 6 -l
/var/log/clamav/clam-update.log
Maintenant pour un lancement automatique du daemon
clamd
on va créer le fichier
clamd.service
sous
/usr/lib/systemd/system voici
son contenu
[Unit]
Description = clamd scanner daemon
After = syslog.target
nss-lookup.target network.target
[Service]
Type = simple
ExecStart = /usr/local/sbin/clamd -c
/usr/local/etc/clamd.conf
Restart = on-failure
PrivateTmp = true
[Install]
WantedBy=multi-user.target
maintenant pour que le service soit lancé à chaque boot de la
machine il faudra taper
systemctl enable clamd.service
voillà le résultat
Created symlink from
/etc/systemd/system/multi-user.target.wants/clamd.service to
/usr/lib/systemd/system/clamd.service.
pour le lancer il suffit maintenant de taper
systemctl start clamd.service
et voilà ce que ça donne quand on tape
systemctl status clamd
●
clamd.service - clamd scanner daemon
Loaded: loaded
(/usr/lib/systemd/system/clamd.service; enabled; vendor preset:
disabled)
Active: active (running) since Thu
2021-11-04 18:46:59 CET; 38s ago
Main PID: 3153340 (clamd)
Tasks: 2 (limit: 4677)
Memory: 1.1G
CPU: 17.231s
CGroup: /system.slice/clamd.service
└─3153340 /usr/local/sbin/clamd -c /etc/clamd.conf
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: ELF support enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: Mail files support
enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: Mail: RFC1341
handling enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: OLE2 support
enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: PDF support enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: SWF support enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: HTML support
enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: XMLDOCS support
enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: HWP3 support
enabled.
nov. 04 18:47:18 mana.kervao.fr clamd[3153340]: Self checking every
600 seconds.
Lancement automatique du
scanner
Pour un lancement automatique du scanner vous pouvez utiliser
cron,
créer un fichier
scanvirus
à placer sous
/etc/cron.daily
(chaque jour) ou
/etc/cron.hourly
(chaque heure) contenant
#!/bin/bash
/usr/local/bin/clamscan -r -l
/var/log/clamscan/scan.log /home
/usr/local/bin/clamscan -r --mbox
/var/spool/mail
Il faut le rendre exécutable
chmod 755 /etc/cron.daily/scanvirus.
Il scannera tous les jours les répertoires
/home et
/var/spool/mail.
Libre à vous de rajouter des scans dans les partages
samba
ou vos partitions windows.
Interfaçage avec sendmail
L'intérêt maintenant d'un anti
virus est un scan automatique à la réception mais également à
l'envoi d'emails. Pour cela Clam
Anti Virus peut très facilement s'interfacer avec sendmail.
Si la compilation s'est bien passée vous devriez trouver un fichier
clamav-milter sous /usr/local/sbin.
Dans le fichier de config de sendmail
(sous /etc/mail/ ou
/usr/share/sendmail-cf/cf) on rajoutera tout à la fin
les lignes
INPUT_MAIL_FILTER(`clmilter',
`S=local:/var/log/clamav/clmilter.sock, F=, T=S:4m;R:4m')dnl
define(`confINPUT_MAIL_FILTERS',
`clmilter')
Dans l'hypothèse où
SpamAssassin
est déjà interfacé avec
sendmail,
il faudra modifier les dernières lignes comme cela.
INPUT_MAIL_FILTER(`clmilter',
`S=local:/var/log/clamav/clmilter.sock, F=, T=S:4m;R:4m')dnl
INPUT_MAIL_FILTER(`spamassassin', `S=local:/var/run/spamass.sock,
F=, T=C:15m;S:4m;R:4m;E:10m')dnl
define(`confMILTER_MACROS_CONNECT',`t, b, j, _, {daemon_name},
{if_name}, {if_addr}')dnl
define(`confMILTER_MACROS_HELO',`s, {tls_version}, {cipher},
{cipher_bits}, {cert_subject}, {cert_issuer}')dnl
define(`confMILTER_MACROS_ENVFROM',`i, {auth_authen},
{auth_type}')dnl
define(`confMILTER_MACROS_ENVRCPT',`r, v, Z')dnl
define(`confINPUT_MAIL_FILTERS', `clmilter,spamassassin')
Dans le fichier
/etc/clamd.conf
on modifiera la ligne suivante
# Path to the local socket. The
daemon doesn't change the mode of the
# created file (portability reasons).
You may want to create it in a directory
# which is only accessible for a user
running daemon.
# je n'ai pas mis le répertoire par
défaut car l'utilisateur clamav
# ne peut écrire sous /var/run
LocalSocket
/var/log/clamav/clamd.sock
On relance maintenant
clamd
systemctl restart clamd.service
Et on lance
clamav-milter
clamav-milter -c /usr/local/etc/clamav-milter.conf
Pour information même en le lançant en tant que root, ce sera
l'utilisateur
clamav qui sera
le propriétaire du process
clamav-milter.
Maintenant on relance
sendmail en
supposant
que votre fichier de conf se trouve sous
/usr/share/sendmail-cf/cf
et se nomme
config.mc
systemctl stop sendmail
cd
/usr/share/sendmail-cf/cf/
m4 config.mc >
/etc/mail/sendmail.cf
systemctl start sendmail
Maintenant pour lancer
clamav-milter
automatiquement, on créera le fichier
clamav-milter.service
dans le répertoire
/usr/lib/systemd/system/
[Unit]
Description='ClamAV Milter'
After=clamd.service
[Service]
Type=forking
ExecStart=/usr/local/sbin/clamav-milter
--config-file /usr/local/etc/clamav-milter.conf
[Install]
WantedBy=multi-user.target
maintenant pour que le service soit lancé à chaque boot de la machine
il faudra taper
systemctl enable
clamav-milter.service
voillà le résultat
Created symlink from
/etc/systemd/system/multi-user.target.wants/clamav-milter.service
to /usr/lib/systemd/system/clamav-milter.service.
pour le lancer il suffit maintenant de taper
systemctl start clamav-milter.service
et voilà ce que donne la commande systemctl
status clamav-milter.service
● clamav-milter.service - 'ClamAV
Milter'
Loaded: loaded
(/usr/lib/systemd/system/clamav-milter.service; enabled; vendor
preset: disabled)
Active: active (running) since Sat
2021-09-11 20:34:04 CEST; 6s ago
Process: 292092
ExecStart=/usr/local/sbin/clamav-milter --config-file
/usr/local/etc/clamav-milter.conf (code=exited, status=0/SUCCESS)
Main PID: 292093 (clamav-milter)
Tasks: 3 (limit: 4677)
Memory: 2.6M
CPU: 10ms
CGroup:
/system.slice/clamav-milter.service
└─292093 /usr/local/sbin/clamav-milter --config-file
/usr/local/etc/clamav-milter.conf
sept. 11 20:34:04 mana.kervao.fr systemd[1]: Starting 'ClamAV
Milter'...
sept. 11 20:34:04 mana.kervao.fr systemd[1]: Started 'ClamAV
Milter'.
Si au lancement
vous avez
l'erreur suivante
/usr/local/sbin/clamav-milter:
--max-children must be given if --external is not given
Vérifiez bien que vous avez décommenté la ligne suivante dans
le fichier
/usr/local/etc/clamd.conf
# Maximal number of threads running at the same time.
# Default: 10
MaxThreads 20
Maintenant comment sait-on si un virus a été intercepté ? Avec
fetchmail quand on récupére le
courrier on a un message de ce genre
fetchmail: lecture du message
olivier.hoarau@funix.org@pop.pro.proxad.net:36 parmi 37 (3143
octets) fetchmail: éliminé
fetchmail: Le serveur SMTP a refusé de délivrer le courrier
Pour
que le mail soit purement et simplement supprimé. Dans votre
fichier .fetchmailrc il
faudra rajouter la ligne suivante
poll pop.fai.net protocol pop3
user
olivier.hoarau@funix.org with password machinchose is olivier
here
options antispam 550 554;
Sinon il restera dans
/var/spool/mail. Plus en détail avec
journalctl on obtient
sept. 12 09:22:10 mana.kervao.fr sendmail[6686]: 18C7M6rl006686:
from=<bounce@news.lahalle.com>, size=51557, class=-60,
nrcpts=1,
msgid=<NM6259F1697003B606Fkorbenl_mid_prod1-Ym91bmNlQG5ld3MubGFoYWxsZS5jb20=@news.lahalle.com>,
proto=ESMTP, daemon=MTA, relay=localhost [127.0.0.1]
sept. 12 09:22:10 mana.kervao.fr sendmail[6686]: 18C7M6rl006686:
Milter (clmilter) add: header: X-Virus-Scanned: clamav-milter
0.104.0 at mana.kervao.fr
sept. 12 09:22:10 mana.kervao.fr sendmail[6686]: 18C7M6rl006686:
Milter (clmilter) add: header: X-Virus-Status: Clean
Chaque
mail se voit rajouter la ligne suivante dans son entête
X-Virus-Scanned: clamav-milter 0.105.1 at mana.kervao.fr
X-Virus-Status: Clean