Anti-Spam Corporativo

Proteja sua rede da praga do spam. Aqui você irá encontrar instruções de como integrar uns dos melhores anti-spam que existe OSBF-LUA com o servidor de e-mail Exim.


OSBF-LUA

O que é o OSBF-LUA

Descrição retirada do site OSBF-LUA :

“O OSBF-Lua é um modulo C Lua para classificação de texto. Ele foi portado para o Lua da implementação do classificador do projeto CRM114. Esta implementação tem como foco a tarefa de classificar usando Lua como linguagem de script, o que torna mais fácil testar e eleborar filtros e métodos de treino.”

Exim

Descrição retirada do site Exim:

“O Exim é um MTA (message transfer agent) desenvolvido na Universidade de Cambridge para uso em sistema Unix conectados a Internet. Ele está disponível gratuitamente sobre os termos da GPL. Em estilo ele é similar ao Smail 3, mas suas facilidades são mais genéricas. Há uma grande variedades de facilidades na forma em que um e-mail pode ser roteado, e a ínumeras facilidades para verificar um e-mail recebido. O Exim pode ser instalado em substituição ao sendmail, apesar de que a configuração do exim difere em muito a do sendmail.”

Integrando o Exim 4 e o OSBF-LUA



  • Requerimentos

Exim 4.60 ou uma versão mais atual
Lua 5.1
OSBF-LUA 2.0.2 ou uma versão mais atual

  • Instalação do Exim 4

Este guia não cobrirá a instalação do exim 4, favor verificar a documentação da sua distribuição Linux de preferência.

  • Instalação do OSBF-LUA
tar xvzf osbf-lua-x.y.z.tar.gz
cd osbf-lua-x.y.z
make
make install
make install_spamfilter

Os arquivos do spamfilter são instalados em /usr/local/osbf-lua. Se o diretório não existe o mesmo será criado.

  • Configurando as contas de e-mail para usar o OSBF-LUA
    mkdir $HOME/osbf-lua/log
    mkdir $HOME/osbf-lua/cache

Copie o arquivo de configuração do spamfilter para o seu diretório:

    cp /usr/local/osbf-lua/spamfilter_config.lua $HOME/osbf-lua

Edite o arquivo spamfilter_config.lua com a sua senha. Vá para o diretório osbf-lua no seu diretório home e crie as bases de dados do spamfilter:

  cd $HOME/osbf-lua
  lua /usr/local/osbf-lua/create_databases.lua   





  • Configuração do Exim 4

Na configuração a seguir o Exim executa o OSBF-Lua em tempo de entrega, usando a diretiva transport_filter . mais detalhes sobre o transport_filter podem ser encontrados aqui.

Adicione a linha abaixo na seção MAIN do exim.conf:

OSBF_LUA_DIR=/usr/local/osbf-lua

na seção TRANSPORT, adicione a diretiva transport_filter ao local_delivery transport:

   driver = appendfile
      check_string = ""
      create_directory
      delivery_date_add
      directory = ${home}/Maildir/
      directory_mode = 700
      envelope_to_add
      return_path_add
      group = mail
      maildir_format
      maildir_tag = ,S=$message_size
      message_prefix = ""
      message_suffix = ""
      mode = 0600
      quota = ${lookup{$local_part}lsearch*{/etc/mail/quota_usr}{$value}{4M}}
      quota_size_regex = S=(\d+)$
      quota_warn_threshold = 75%
      transport_filter = OSBF_LUA_DIR/spamfilter.lua --udir $home/osbf-lua


OBS.: O Exim deve ser reiniciado após as alterações do exim.conf.




  • Usando OSBF-LUA + Exim 4

Novas mensagens ser/ao processadas pelo OSBF-Lua em “tempo de entrega”. O Exim irá executar um script chamado spamfilter.lua. Ele lê mensagens da entrada padrão e classifica-os como spam ou não spam. Após a mensagem ser classificada, o spamfilter.lua a imprime para a saída padrão, adicionando ao assunto as seguintes tags:

“[–]” - A mensagem tem pontuação de SPAM fora da região de reforço;
“[-]” - A mensagem tem pontuação de SPAM dentro da região de reforço;
“[+]” - A mensagem tem pontuação de não SPAM dentro da região de reforço;
““ - A mensagem tem pontuação de não SPAM fora da região de reforço.

A região de reforço é onde o valor absoluto da pontuação é menor que o valor definido no arquivo de configuração. Menagens com pontuação na região de reforço, mesmo quando corretamente classificada, deve ser treinado para manter a precição alta.
A região de reforço padrão é [-20.0, 20.0]. Você pode alterá-la editando os valores do cfg.osbf.threshold no spamfilter_config.lua. voc também pode mudar as tags e outras opções no arquivo de configuração.

spamfilter.lua também adiciona a seguinte linha no cabeçalho da mensagem:

X-OSBF-Lua-Score: <score>/0.0 [tag] (2.0.2, Spamfilter 2.0)

o formato da pontuação é <score_value>/<reference>. Uma pontaução abaixo do valor de <reference> indica que a mensagem foi classificado como spam;um valor igual ou maior que a <reference> indica que a mensagem não é spam, é claro.

A tag do cabeçalho é um dos [B], [S], [s], [h], [H] ou [W], para blacklisted, spam, spam reforço, ham reforço, ham ou whitelisted.

Você pode mandar comandos para o spamfilter através da mensagem propriamente dita.
Os seguintes comandos em letras minúsculas, são aceitos no assunto da mensagem:

learn <password> spam|nonspam [<sfid> | body]
Aprende que a mensagem respondida é pertencente a classe spam o não-spam, respectivamente. Esse comando requere um “responder”. <sfid> e “body” são parâmetros opcionais que você pode usar para informar um lugar alternativo para onde procurar a mensagem. veja a nota abaixo para maiores detalhes.

batch_train <password>
executa comandos no corpo da mensagem. Os comandos são uma seqüência de linhas contendo um sifd e o respectivo comando no seguinte formato:

<sfid>=<command>

Onde <commando> pode ser um dos

spam - treinar como spam
nonspam - treinar como não-spam
undo - desfaz o treinamento anterior
whitelist_from - adiciona o ‘From:’ na whitelist
whitelist_subject - adiciona ‘Subject:’ na whitelist
recover - recupera a mensagem do cache
remove - remove a mensagem do cache

Exemplo:

Resultado do comando batch_train:

train_form <password>
Executa o script “cache_report.lua”, o qual envia um email com o formulário de treinamento para o usuário.

Exemplo:

unlearn <password> spam|nonspam [<sfid> | body]
“Desaprende” em qual classe (spam ou não-spam) uma mensagem foi classificada. É usado para desfazer um treinamento errôneo. Este comando requere um “responder”.

classify <password> [<sfid> | body]
Classifica a mensagem e retorna a sua pontuação. Requere um “responder”.

recover <password> [<sfid>]
Verifica se a cópia original de uma mensagem está disponível a a envia de volta para o você como um anexo, completo com cabeçalhos. Requere um “responder”.

whitelist <password> add|del|show <string>
Add or delete <string> to/from the whitelist. If <string> is found in the header, the message will be accepted. The “show” command ignores <string>, if any, and shows the contents of the list.

Note: white and black lists don’t use regex by default. If you want enable Lua regex, change the option osbf.cfg_lists_use_regex to “true” in the config file, or add it if it’s not present. If you do so, take care of special chars in your strings. You’ll have to escape them with “%” to get their literal meaning, also in your previously defined strings. The magic chars to be protected are ^$()%.[]*+-?) Check the PIL book for more details on pattern-matching functions.

blacklist <password> add|del|show <string>
Add or delete <string> to/from the blacklist. If <string> is found in the header the message will be rejected. The “show” command ignores <string>, if any, and shows the contents of the list.

stats <password>
Return statistics of the spam and nonspam databases.

help <password>
Return this help.

OBS: You must do a “reply” to the message to be used with the commands “learn”, “unlearn”, “classify” and “recover”, changing the “To:” to your own address. The reply is required because the ID originally given to the message by the spamfilter, the “sfid”, is needed to recover the original message and it is automatically returned in the reply.

If your email client doesn’t return it, you can inform the sfid directly in the subject as the last parameter of the command. In this case, you don’t have to use a reply, just send the command to your own address.

The sfid can be found in the header of the message as a comment added by the spamfilter to the Message-ID field or to the References field, depending on the version/configuration, when the message was classified.

The message to be trained can also be sent as the body of the command message. In this case, the optional parameter “body” must be used to inform the filter to extract the message from the body, instead of looking for a sfid.

Example of sfid in the References :

[... header ...] References: sfid-H20060408-003814-000.00-1@spamfilter.osbf.lua [... header ...]

Example of sfid in the Message-ID :

[... header ...] Message-ID: <013e01c5c9f7$d3f60cf0$1216040a@SUPGR11> (sfid-H20051005-155749-000.00-1@spamfilter.osbf.lua) [... header ...]

Examples of valid commands using the sfid above:

Subject: recover <pwd> sfid-H20051005-155749-+001.00-1@spamfilter.osbf.lua Subject: learn <pwd> spam sfid-H20051005-155749-+001.00-1@spamfilter.osbf.lua Subject: learn <pwd> spam body

As of version 1.5.7b, the sfid is added to the References field, as a normal reference, because this form is accepted by practically all MUA. Contrarily to what is recommended in RFC-2822, some MUAs, like Sylpheed and Mutt, discard Message-ID comments in the reply, what breaks Spamfilter’s training mechanism.

Some email clients that support sfid as a Message-ID comment:

* On Unix (tested on Linux):
Evolution
KMail
Mozilla Mail
Mozilla Thunderbird
Mutt (with patch)

* On Windows:
Eudora
Mozilla Mail
Mozilla Thunderbird
Microsoft Outlook 200X
Microsoft Outlook Express
Pegasus Mail
The Bat!

* Webmail:
Openwebmail




Command line options and commands

Besides the send-to-yourself subject line commands, spamfilter.lua also accepts commands and options in the command line. The available options and commands are described below.

Options

udir=<user_dir>
Set the user directory, where its osbf-lua configuration, databases, lists and log files are located. The location of these files can also be set individually, see the options below.

gdir=<global_dir>
Set the global directory where spamfilter.lua is installed and where it looks for its companion files, like spamfilter_commands.lua, spamfilter.help, etc.

cfdir=<config_dir>
Specify a location for the configuration file different than that specified with –udir.

dbdir=<database_dir>
Specify a location for the database files different than that specified with –udir.

listdir=<list_dir>
Specify a location for the list files, whitelist.lua and blacklist.lua, different than that specified with –udir.

source=stdin|sfid|body
Set the source of the message to be used in a trainining, when one of the commands –learn or –unlearn is used.

stdin:
The message is exactly what is read from stdin.
sfid:
The message is recovered from the cache using the sfid in the headers of the message read from stdin.
body:
The message to be trained with is the body of the message read from stdin.

The default value is “stdin”, that is, when this option is not specified.

output=report|message
Determine what is written to stdout after training a message, the default report or the original message classified as spam or ham, according to the training command.



Commands

classify
Classify a message read from stdin and print just the X-OSBF-Lua-Score header line that would be added to the message header.

learn=spam|nonspam
Learn a message from stdin as spam or not spam, respectively. The source of the message can be changed with the option –source.

score
Classify a message read from stdin and print just the score.

unlearn=spam|nonspam
Undo (approx.) a previous learn done by mistake. The message is read from stdin. The source of the message can be changed with the option –source.

If no command-line command is specified, spamfilter.lua looks for one of the send-to-yourself commands in the subject line and executes it if found. If no subject line command is found, it searches the first 100 chars of the message body for a command. If no command is found, it then performs a normal classification, adds a X-OSBF-Lua-Score to the message header, does other actions specified in the config file, like tagging the subject line, and prints the message to the standard output.

Resources

Exim website
OSBF-LUA website
spamfilter.help

Credits

The OSBF-LUA lib and spamfilter were designed and implemented by Fidelis Assis, who holds the copyright.