Gérer des mails avec Perl
- L'envoi de message : Utilisation du module MIME::Lite
- Automatiser la réception
- Traiter les spams et les virus
Utilisation du module MIME::Lite
Installation de MIME::Lite
- Sous Windows
Installation via ppm :
C:\>ppm PPM interactive shell (1.1.1) - type 'help' for available commands. PPM> search MIME Packages available from http://www.activestate.com/Packages/: MIME-Base64 [2.11 ] Encoding and decoding of base64 strings MIME-Lite [1.135] low-calorie MIME generator MIME-tools [4.124] Modules for parsing (and creating!) MIME entities PPM> install MIME-Lite Install package 'MIME-Lite?' (y/N): y Retrieving package 'MIME-Lite'... Installing D:\perlNT\html\lib\site\MIME\Lite.html Installing D:\perlNT\htmlhelp\pkg-MIME-Lite.chm Installing D:\perlNT\htmlhelp\pkg-MIME-Lite.hhc Installing D:\perlNT\site\lib\MIME\Lite.pm Writing D:\perlNT\site\lib\auto\MIME\Lite\.packlist PPM> - Sous Unix
Récupérer l'archive sur le serveur CPAN :
Puis :$ gzip -d MIME-Lite-xxx.tar.gz $ tar xvf MIME-Lite-xxx.tar $ cd MIME-Lite-xxx $ perl Makefile.PL $ make # make install
Documentation disponible
Une documentation est fournie est fournie au format HTML. Pour windows c'est dans le répertoire <perl>\html\lib\site\MIME, pour Unix dans le répetoire où vous avez décompressé l'archive.
Utilisation
- Envoi d'un simple mail texte
my $msg = new MIME::Lite From =>'me@myhost.com', To =>'you@yourhost.com', Cc =>'some@other.com, some@more.com', Subject =>'A simple text message', Type =>'TEXT', Data =>"Efficace non ?"; $msg -> send; - Envoi d'un mail avec pièces attachées
# Creation d'un message avec plusieurs parties (multipart) my $msg = new MIME::Lite From =>'me@myhost.com', To =>'you@yourhost.com', Cc =>'some@other.com, some@more.com', Subject =>'A message with 2 parts...', Type =>'multipart/mixed'; # Ajout des pieces attachées # Chaque "attach" a les memes arguments que "new": attach $msg Type =>'TEXT', Data =>"Here's the GIF file you wanted"; attach $msg Type =>'image/gif', Path =>'aaa000123.gif', Filename =>'logo.gif'; $msg->send; - Envoi d'un mail au format HTML avec des images :
Tout le travail consiste à déterminer des clefs (cid) à remplacer dans le document sur tous les liens vers les images à inclure. Ce travail peut être executé par le module MIME::Lite::HTML
Voici un exemple de son utilisation pour faire un cgi comme "Envoyer cette url à un ami":
#!/usr/bin/perl -w # # A cgi program that do "Mail this page to a friend"; # # Call this script like this : # # script.cgi?email=myfriend@isp.com&url=http://www.go.com use strict; use CGI qw/:standard/; use CGI::Carp qw/fatalsToBrowser/; use MIME::Lite::HTML; my $mailHTML = new MIME::Lite::HTML From => 'MIME-Lite@alianwebserver.com', To => param('email'), Subject => 'Your url: '.param('url'), Debug => 3; my $MIMEmail = $mailHTML->parse(param('url')); MIMEmail->send; # or for win user : $mail->send_by_smtp('smtp.fai.com'); print header,"Mail envoye (", param('url'), " to ", param('email'),")<br>\n";
Pour plus d'exemples, voir la documentation POD et les exemples de la distribution.
La réception de messages avec Perl
Ce paragraphe traite du cas où l'ont veut automatiser la réception de messages, et passer un parser sur les mails reçus.
La redirection
Il faut commencer par faire une redirection des mails par un programme. Attention: Le script doit etre valide, et avec des droits corrects (755). Vous n'aurez aucune trace de l'execution du script, si ce n'est un code d'erreur du serveur de messagerie. On peut faire la redirection:
- Dans le fichier /etc/aliases. (taper newaliases pour regenerer le fichier .db)
nobody: "|/home/alian/bin/parser_mail.pl"
- Ou au niveau d'un .forward:
|/home/alian/bin/parser_mail
- Ou encore si vous utilisez procmail via un .procmailrc:
:0fw | /home/alian/bin/parser_mail
Analyse des mails
Divers modules existent pour cela:
MIME-Tools
Dans le corps d'un programme, utiliser le module MIME::Parser inclu dans le package MIME-tools. Son utilisation ressemble à quelque chose comme ca:
#!/usr/bin/perl -Tw
use strict;
use MIME::Parser;
# Decodage des mails recus
my $parser = new MIME::Parser;
# Lecture sur l'entree standart du mail
my $entity = $parser->read(\*STDIN)
|| die "couldn't parse MIME stream";
# On recupere l'entete du message
my $head = $entity->head();
# On recupere l'expediteur du message
my $expediteur = $head->get('From:');
...
Ensuite voir la doc de MIME::Parser pour plus d'info en fonction de ce que vous voulez faire.
Mail-Audit
Disponible sur le CPAN. Example de parser n'acceptant que les messages provenant d'addresses de @good:
#!/usr/bin/perl -w
use strict;
use Mail::Audit;
my $mail = Mail::Audit->new();
# Adressses acceptees sans scan
my @good qw/samba-technical-request\@lists.samba.org
cpan-testers-digest-help\@perl.org
\@albert\.com
\@albert-inc.com/;
foreach my $fr (@good) {
if ($mail->from =~ /$fr/) {
$mail->accept();
}
}
Exterminer les spam et les virus en Perl
C'est une bonne idée, mais bon ... tres gourmande. On peut limiter le traffic en amont en utilisant un .procmailrc, beaucoup moins couteux que de lancer un interpreteur ... Ex:
# Directory for storing procmail configuration and log files
# You can name this environment variable anything you like
# (for example PROCMAILDIR) or, if you prefer, don't set it
# (but then don't refer to it!)
PMDIR=$HOME/Procmail
# LOGFILE should be specified ASAP so everything below it is logged
# Put ## before LOGFILE if you want no logging (not recommended)
LOGFILE=$PMDIR/pmlog
# To insert a blank line between each message's log entry,
# uncomment next two lines (this is helpful for debugging)
## LOG="
## "
# Set to yes when debugging; VERBOSE default is no
## VERBOSE=yes
# Replace $HOME/Msgs with your mailbox directory
# Mutt and elm use $HOME/Mail
# Pine uses $HOME/mail
# Netscape Messenger uses $HOME/nsmail
# Some NNTP clients, such as slrn & nn, use $HOME/News
# Mailboxes in maildir format are often put in $HOME/Maildir
#
# IMPORTANT: Upon reading an instruction that contains MAILDIR=,
# Procmail does a chdir to $MAILDIR and
# relative paths are relative to $MAILDIR
# MAILDIR=$HOME/Msgs # Make sure this directory exists!
# SpamAssassin sample procmailrc
#
# Pipe the mail through spamassassin (replace 'spamassassin' with 'spamc'
# if you use the spamc/spamd combination)
# The condition line ensures that only messages smaller than 250 kB
# (250 * 1024 = 256000 bytes) are processed by SpamAssassin. Most spam
# isn't bigger than a few k and working with big messages can bring
# SpamAssassin to its knees.
#:0fw
#* < 256000
#| /usr/local/bin/spamc
# Mails with a score of 15 or higher are almost certainly spam (with 0.05%
# false positives according to rules/STATISTICS.txt). Let's put them in a
# different mbox. (This one is optional.)
#:0:
#* ^X-Spam-Level: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
#almost-certainly-spam
# MyDoom Virus
:0
* ! ^Subject: Hi$
* ! ^Subject: test$
* ! ^Subject: TEST$
* ! ^Subject: Status$
* ! ^Subject: Error$
* ! ^Subject: hello$
* ! ^Subject: Server Report$
{ }
:0 E
{
LOG="MyDoom virus detected : "
:0
/dev/null
}
:0 B
* ! ^Mail transaction failed. Partial message is available.
* ! ^The message cannot be represented in 7-bit ASCII encoding and has been sent as a binary attachment.
* ! ^The message contains Unicode characters and has been sent as a binary attachment.
{ }
:0 E
{
LOG="MyDoom virus detected : "
:0
/dev/null
}
:0 B
* name="(document|readme|doc|text|file|data|test|message|body)\..*(pif|scr|exe|cmd|bat|zip)
* > 25000
* < 38000
{
LOG="MyDoom virus detected : "
:0
/dev/null
}
# Others virus ...
:0
* ! ^Subject: Use this patch immediately !$
* ! ^Subject: Important information for you. Read it immediately !$
* ! ^Subject: Japanese lass' sexy pictures$
* ! ^Subject: Fw: goldfish$
{ }
:0 E
{
LOG='Another virus detected : '
:0
/dev/null
}
:0
* ! ^Subject: InterScan NT Alert$
* ! ^Subject: Virus Alert$
* ! ^Subject: Virus Detected by Network Associates
* ! ^Subject: Virus found
* ! ^Subject: virus found
* ! ^Subject: VIRUS
{ }
:0 E
{
LOG='Antivirus rapport : '
:0
Antivirus
}
:0
* ! ^Subject: =\?ISO-8859-1\?Q\?Notification_d'=E9tat_de_la_distribution\?=$
* ! ^Subject: Returned mail:
* ! ^Subject: Undeliverable:
* ! ^Subject: Undelivered Mail Returned to Sender$
* ! ^Subject: Delivery
* ! ^Subject: Mail Delivery
* ! ^Subject: Mail delivery
* ! ^Subject: failure notice$
{ }
:0 E
{
LOG='Returned mail : '
:0
ReturnedMail
}
Les spams
Spam-Assassin
Disponible sur le CPAN. Son module comme son nom l'indique sert à rejeter/filtrer les spams recus. Il s'utilise avec le module Mail-Audit. Exemple:
#!/usr/bin/perl
use Mail::Audit;
use Mail::SpamAssassin;
my $mail = Mail::Audit->new();
# Le filtre a spam
my $spamtest = Mail::SpamAssassin->new();
my $status = $spamtest->check($mail);
if ($status->is_spam ()) {
$status->rewrite_mail();
$mail->accept();
}
$mail->accept();
Voir les exemples pour effectuer la liaison avec les messages.
Un ensemble de regles va être passé sur chacun des messages. Si le score total des règles
dépasse un certain score, on peut décider de réecrire l'entete du message ou de le supprimer.
Exemple de message reecrit:
SPAM: -------------------- Start SpamAssassin results ---------------------- SPAM: This mail is probably spam. The original message has been altered SPAM: so you can recognise or block similar unwanted mail in future. SPAM: See http://spamassassin.org/tag/ for more details. SPAM: SPAM: Content analysis details: (8.70 hits, 5 required) SPAM: SUBJ_HAS_SPACES (2.6 points) Subject contains lots of white space SPAM: ADVERT_CODE2 (1.7 points) Subject: contains advertising tag SPAM: NO_REAL_NAME (1.3 points) From: does not include a real name SPAM: ADVERT_CODE (0.6 points) Subject: starts with advertising tag SPAM: FREE_QUOTE (0.6 points) BODY: Free Quote SPAM: NO_OBLIGATION (0.4 points) BODY: There is no obligation. SPAM: SAVE_MONEY (0.3 points) BODY: Save big money SPAM: SAVE_UP_TO (0.3 points) BODY: Save Up To SPAM: ACT_NOW (0.3 points) BODY: Act Now! Don't Hesitate! SPAM: SPAM_PHRASE_01_02 (0.5 points) BODY: Spam phrases score is 01 to 02 (low) SPAM: [score: 1] SPAM: UNSUB_PAGE (0.1 points) URI: URL of page called "unsubscribe" SPAM: SPAM: -------------------- End of SpamAssassin results ---------------------Si certaines addresses ne doivent pas etre analysés, on peut lui spécifier vi le fichier $HOME/.spamassassin/user_prefs:
# Whitelist and blacklist addresses are now file-glob-style patterns, so
# "friend@somewhere.com", "*@isp.com", or "*.domain.net" will all work.
whitelist_from *@albert.com *@albert-inc.com *.alianet *@perl.org
*.samba.org
Les virus
Amavis-perl
Ce programme est un intermédiaire entre un antivirus quelconque et le serveur de messagerie. Les dernières versions sont disponible ici.
Il est chargé de deencoder/décompresser les mails/pieces jointes pour ensuite passer chaque fichier à l'antivirus.
Je l'utilise en duo avec Clamav, un antivirus open-source se basant sur la base de donnée de http://www.openantivirus.org
Pour chaque mail contaminé, l'administrateur recoit un mail du genre:
A virus was found in an email from: fucker@truefriends.org The message was addressed to: -> alian The message has been quarantined as: /var/virusmails/virus-20021212-202406-10615 Here is the output of the scanner: /var/amavis/amavis-08722618/parts/msg-10615-1.html: OK /var/amavis/amavis-08722618/parts/msg-10615-2.scr: W32/Yaha.E FOUND /var/amavis/amavis-08722618/parts/part-00001: W32/Yaha.E FOUND ----------- SCAN SUMMARY ----------- Known viruses: 1774 Scanned directories: 1 Scanned files: 3 Infected files: 2 Data scanned: 0.03 Mb I/O buffer size: 131072 bytes Time: 6.919 sec (0 m 6 s) Here are the headers: ...
| Dernière modification le Mon Feb 2 22:49:46 2004 |
© Alain & Estelle BARBET Textes et images 1997-2003 |