Instalando Snort e Guardian no Slackware

Segurança hoje em dia é uma coisa séria e muito difícil de se fazer, nenhum sistema é totalmente seguro, mas podemos dificultar as coisas não é? Estudando segurança pela grande rede, achei o Snort, que é um sistema reconhecido pelos administradores de sistemas e já ganhou alguns prêmios. Utilizarei arquivos tgz para mantermos a organização do nosso Slackware.

[ Hits: 86.028 ]

Por: João Paulo de Oliveira Faria em 18/03/2005 | Blog: http://www.jpfaria.com


Criando o Guardian



1 - Crie o arquivo /usr/sbin/guardian.pl com o seguinte conteúdo:

#!/usr/bin/perl
# This program was written by Anthony Stevens (astevens@chaotic.org), and is
# free for distrubtion. The author will not be liable for any damages caused by
# this software. Anyone is free to make modifications / enhancements to this
# script, as long as changes are sent back to me so that they may be included
# in
# the official distrubtion.
# Modificado por João Paulo de Oliveira Faria ( joaopaulo@deoliveira.com.br )


require 'getopts.pl';

#&Getopts('a:dt:iI:');
&Getopts ('hc:d');
if (defined($opt_h)) {
print "Guardian v1.0.. \n";
print "guardian.pl [-hd] <-c config>\n";
print " -h  shows help\n";
print " -d  run in debug mode (doesn't fork, output goes to STDOUT)\n";
print " -c  specifiy a configuration file other than the default (/etc/guardian.conf)\n";
exit;
}
&load_conf;

# get the default time limit, or set no time limit...
#if (defined ($opt_t)) { $timelimit = $opt_t} else {$timelimit = 0}

print "My ip address and interface are: $hostipaddr $interface\n";

if ($hostipaddr !~ /\d+\.\d+\.\d+\.\d+/) {
   print "This ip address is bad : $hostipaddr\n";
   die "I need a good host ipaddress\n";
}

$networdaddr = $hostipaddr;
$networkaddr =~ s/\d$/0/;
$gatewayaddr = $hostipaddr;
$gatewayaddr =~ s/\d$/$hostgatewaybyte/;
$broadcastaddr = $hostipaddr;
$broadcastaddr =~ s/\d$/255/;
&build_ignore_hash;

# This is the target hash. If a packet was destened to any of these, then the
# sender of that packet will get denied, unless it is on the ignore list..

%targethash = ( "$networkaddr" => 1,
              "$broadcastaddr" => 1,
              "$hostipaddr" => 1);
  
if (!defined($opt_d)) {
  print "Becoming a daemon..\n";
  &daemonize;
} else { print "Running in debug mode..\n"; }

open (ALERT, $alert_file) or die "open $alert_file: $!\n";
@junk=;
# this is the same as a tail -f :)
for (;;) {
  sleep 1;
  if (seek(ALERT,0,1)){
    while (<ALERT>) {
      chop;
      if (defined($opt_d)) {print "$_\n";}
      if (/\[\*\*\]\s+(.*)\s+\[\*\*\]/){
        $type=$1;
      }
      if (/(\d+\.\d+\.\d+\.\d+):\d+ -\> (\d+\.\d+\.\d+\.\d+):\d+/) {
        &checkem ($1, $2, $type);
      }
    }
  }
}

sub checkem {
  my ($source, $dest,$type) = @_;
  my $flag=0;
  my $date = localtime();
  return 1 if ($source eq $hostipaddr); # this should prevent is from nuking
                                       # ourselves
  return 1 if ($source eq $gatewayaddr); # or our gateway
  if ($ignore{$source} == 1) { # check our ignore list..
     &write_log("$date: ");
     &write_log("$source\t$type\n");
     &write_log("Ignoring attack because $source is in my ignore list\n");
     return 1;
  }
  # if the offending packet was sent to us, the network, or the broadcast, then
  # deny the punk ass..
  if ($targethash{$dest} == 1) {
    &write_log("$date: ");
    &ipchain ($source, $dest, $type);
  }
  # you will see this if the destination was not in the $targethash, and the
  # packet was not ignored before the target check..
  else {
    &write_log ("Odd.. source = $source, dest = $dest. No action done.\n");
    if (defined ($opt_d)) {
      foreach $key (keys %targethash) {
        &write_log ("targethash{$key} = $targethash{$key}\n");
      }
    }
  }
}
  
sub ipchain {
  my ($source, $dest, $type) = @_;
  &write_log ("$source\t$type\n");
  if ($hash{$source} != 1) {
    &write_log ("adding '/usr/sbin/iptables -I INPUT -s $source -i $interface -j DROP'\n");
    system ("/usr/sbin/iptables -I INPUT -s $source -i $interface -j DROP");
    $hash{$source} = 1;
  }
  # print "$source already Denied.\n";
}
    
sub build_ignore_hash {
#  This would cause is to ignore all broadcasts if it
#  got set.. However if unset, then the attacker could spoof the packet to make
#  it look like it came from the network, and a reply to the spoofed packet
#  could be seen if the attacker were on the local network.
#  $ignore{$networkaddr}=1;
  
# same thing as above, just with the broadcast instead of the network.
#  $ignore{$broadcastaddr}=1;
  my $count =0;
  $ignore{$gatewayaddr=1};  
  $ignore{$hostipaddr}=1;
  if ($ignorefile ne "") {
    open (IGNORE, $ignorefile);
    while (<IGNORE>) {
      chop;
      next if (/\#/);  #skip comments
      next if (/^\s*$/); # and blank lines
      $ignore{$_}=1;  
      $count++;
    }
    close (IGNORE);
    print "Loaded $count addresses from $ignorefile\n";
  } else {
    print "No ignore file was loaded!\n";
  }
}
  
sub load_conf {
  if ($opt_c eq "") {
    $opt_c = "/etc/guardian.conf";
  }
  if (! -e $opt_c) {  
    die "Need a configuration file.. please use to the -c option to name a
configuration file\n";
  }
  open (CONF, $opt_c) or die "Cannot read the config file $opt_c, $!\n";
  while (<CONF>) {
    chop;
    next if (/^\s*$/); #skip blank lines
    next if (/^#/); # skip comment lines
    if (/LogFile\s+(.*)/) {
       $logfile = $1;
    }
    if (/Interface\s+(.*)/) {
       $interface = $1;
    }
    if (/AlertFile\s+(.*)/) {
       $alert_file = $1;
    }
    if (/IgnoreFile\s+(.*)/) {
       $ignorefile = $1;
    }
    if (/HostIpAddr\s+(.*)/) {
       $hostipaddr = $1;
    }
    if (/HostGatewayByte\s+(.*)/) {
       $hostgatewaybyte = $1;
    }
    if (/iptablesPath\s+(.*)/) {
       $iptables_path = $1;
    }
  }
  if ($interface eq "") {
    die "Fatal! Interface is undefined.. Please define it in $opt_o with keyword Interface\n";
  }
  if ($alert_file eq "") {
    print "Warning! AlertFile is undefined.. Assuming /var/log/snort/alert\n";
    $alert_file="/var/log/snort/alert";
  }
  if ($hostipaddr eq "") {
    print "Warning! HostIpAddr is undefined! Attempting to guess..\n";
    $hostipaddr = &get_ip($interface);
    print "Got it.. your HostIpAddr is $hostipaddr\n";
  }
  if ($ignorefile eq "") {  
    print "Warning! IgnoreFile is undefined.. going with default ignore list (hostname and gateway)!\n";
  }
  if ($hostgatewaybyte eq "") {
    print "Warning! HostGatewayByte is undefined.. gateway will not be in ignore list!\n";
  }
  if ($iptables_path eq "") {
    print "Warning! iptablesPath is undefined.. Using default of /usr/sbin/iptables\n";
  }
  if ($logfile eq "") {  
    print "Warning! LogFile is undefined.. Assuming debug mode, output to STDOUT\n";
    $opt_d = 1;
  }
  if (! -w $logfile) {
    print "Warning! Logfile is not writeable! Engaging debug mode, output to STDOUT\n";
    $opt_d = 1;
  }
}  
  
    
sub write_log {
  my $message = $_[0];
  if (defined($opt_d)) {  # we are in debug mode, and not daemonized
    print STDOUT $message;
  } else {
    open (LOG, ">>$logfile");
    print LOG $message;
    close (LOG);
  }
}
  
  
    
sub daemonize {
  my ($home);
  
  if (fork()) {
  # parent
    exit(0);  
  } else {
    # child
    &write_log ("Guardian process id $$\n");
    $home = (getpwuid($>))[7] || die "No home directory!\n";
    chdir($home);                   # go to my homedir
    setpgrp(0,0);                   # become process leader
    close(STDOUT);
    close(STDIN);
    close(STDERR);
    print "Testing...\n";
  }
}
  
sub get_ip {
  my ($interface) = $_[0];
  my $ip;
  open (IFCONFIG, "/sbin/ifconfig $interface |");
  while (<IFCONFIG>) {
    if (/inet addr:(\d+\.\d+\.\d+\.\d+)/) {
      $ip = $1;
    }
  }
  close (IFCONFIG);
  if ($ip eq "") { die "Couldn't figure out the ip address\n"; }
  $ip;
}

2 - Dê permissão no arquivo:

# chmod +x /usr/sbin/guardian.pl

3 - Crie o arquivo /etc/guardian.conf com o seguinte conteúdo:

# The machines IP address that is visable to the internet
# If this is left undefined, then guardian will attempt to get the information
# from ifconfig, as long as it has an interface to use. This would be usefull
# for people on ppp links, or dhcp machines, or if you are lazy :)
# HostIpAddr

# Here we define the interface which we will use to guess the IP address, and
# block incoming offending packets. This is the only option that is required
# for guardian to run. If the rest are undefined, guardian will use the default.

Interface       eth0

# The last octet of the ip address, which gives us the gateway address.
HostGatewayByte  254

# Guardian's log file
LogFile         /var/log/guardian.log

# Snort's alert file
AlertFile       /var/log/snort/alert

# The list of ip addresses to ignore
IgnoreFile      /etc/guardian.ignore

# The path to ipchains
iptablesPath     /usr/sbin/iptables

4 - Crie o arquivo /etc/guardian.ignore:

# touch /etc/guardian.ignore

5 - Crie o arquivo /var/log/guardian.log:

# touch /var/log/guardian.log

Página anterior     Próxima página

Páginas do artigo
   1. Introdução
   2. Instalando o Snort 2.2
   3. Criando o Guardian
   4. Modificando os arquivos de inicialização
   5. Iniciando o Snort + Guardian
   6. Configurações adicionais
   7. Verificando se tudo está funcionando
   8. Verificando os arquivos de log
   9. Finalizando
Outros artigos deste autor

Instalando e configurando um servidor DNS (Bind)

Utilizando o Smarty template no PHP

Instalando e configurando um servidor DNS (Bind+CHROOT) no Slackware

Solução completa com o sendmail (segunda edição)

Instalando o AWSTATS no Slackware

Leitura recomendada

YASG (Yet Another Security Guide)

Segurança Física (Parte 1)

Terceirização de segurança gera dúvidas em profissionais de TI

HoneyPots em Linux

Adicionando baterias automotivas extras em nobreaks

  
Comentários
[1] Comentário enviado por y2h4ck em 19/03/2005 - 01:35h

Cara bacana a iniciativa ... POREMMMM ahuah ta na hora de colocar a mão na ferida ...
Seguinte cara... vc falou do Guardian e do Snort e tudo mais blz ... so que vc nao tocou numa coisa ultra-importante para o funcionamento do seu esquema ... que é o pre-processor do snort "portscan" que vai fazer a detecção de Scans ...

afinal vc nao vai querer cometer o pecado de deixar o seu guardian analisando o snort.alert completo ou vai ????? imagine ... um falso positivo e booom ... o host esta dropped sem razão ...
portante se faz necessária a configuração do pre-processo para gerar um log a parte ... e assim o guardian ler aquele log e realizar as determinadas ações predefinidas ??


OK ? Espero ter sido util ...
abraços

ESTAVA SUMIDO MAIS VOLTEI UHUHUU

[2] Comentário enviado por fabio em 19/03/2005 - 07:03h

Fala João, o artigo está ótimo, mas também queria fazer umas observações. Você tá ficando acostumado a escrever artigos muito técnicos e acaba não se tocando nos pequenos detalhes que dificultam a vida dos "normais". Vamos lá:

1. Faltou uma introdução ao Snort. O que ele é e para que serve?
2. Faltou uma introdução ao Guardian. O que ele é e para que serve?
3. Você disse que mudou o Guardian, mas o que você mudou nele? Qual a vantagem da sua versão?

De resto, tudo bem completo. O lance de pré-processo o Anderson (y2h4ck) escreveu num de seus artigos falando sobre Snort também. Acho bacana darem uma lida como complemento, o Snort é bem extenso, quanto mais literatura, melhor:

http://www.vivaolinux.com.br/~y2h4ck/artigos

Meus parabéns!

[]'s

[3] Comentário enviado por D3v1L em 21/03/2005 - 16:37h

No meu guardian.pl deu erro, precisamente linha 56
comentei o parâmetro "@junk=;" e ele funcionou, dei uma olhada no script e não achei mais nenhuma utilização deste junk, gostaria que o jpfaria verificasse.

Muito obrigado

Bruno Sant'Anna

[4] Comentário enviado por segment em 20/10/2005 - 18:06h

Ai D3v1L tbm obtive o mesmo pro. q o teu ai, deu exatamente erro de sintaxe desse =; do junk na linha 55, mas foi so retirar que fico legal. Bom o artigo fico muito bom kra, consegui fazer os lances aqui de prima, apesar que não tem mistérios, o artigo de facil de compreender, entao tudo rolo bem, :]
Vlw brow.

[5] Comentário enviado por gabrielgrace em 31/07/2006 - 11:14h

EM primeiro lugar parabens pelo tutorial .

E para o pessoal que encontrou um erro assim =; na linha 55 é só olhar o arquivo do guardian original lá ta assim "@junk=<ALERT>;"

Pronto funcionol

Valeu joão

T+

[6] Comentário enviado por demattos em 05/09/2006 - 20:53h

Gostaria de Saber se com o guardiam daria para fazer uma analize on line por uma pagina ou seja home page, em tempo real e analizar este logs tambem por este site

Obrigado pela atencao de todos

[7] Comentário enviado por leandrojpg em 18/01/2010 - 14:29h

Show de bola o tutorial, mas só tem um problema fiz tudo passa a passop e me reportou a msg na hora de iniciar

"OS shows Linux
Warning! Logfile is not writeable! Engaging debug mode, output to STDOUT
Warning! Could not find guardian_unblock.sh. Guardian will not be
able to remove blocked ip addresses. Please consult the README file
My ip address and interface are: 150.164.192.210 eth0
Loaded 0 addresses from /etc/guardian.ignore
Running in debug mode.."
E outro eu tento dar um tail -f para ver o log e nao processa nada trava e nao me reporta nada.
será que alguem pode me ajudar, nos mais valeu pelo psot.!!!

[8] Comentário enviado por janjaw em 11/11/2010 - 03:44h

/etc/rc.d/rc.snort: permission denied cara deu isso quando fui starta o serviço e olhe q praticamente copiei e colei


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts