├── .gitignore ├── web ├── images │ ├── index.jpg │ ├── spacer.gif │ ├── index_r1_c1.jpg │ ├── index_r2_c1.jpg │ ├── index_r2_c2.jpg │ ├── index_r2_c3.jpg │ ├── index_r2_c4.jpg │ ├── index_r3_c1.jpg │ ├── index_r3_c2.jpg │ ├── index_r3_c3.jpg │ ├── index_r3_c4.jpg │ ├── index_r3_c5.jpg │ ├── index_r4_c1.jpg │ ├── index_r4_c2.jpg │ ├── index_r4_c3.jpg │ ├── index_r4_c4.jpg │ ├── index_r4_c5.jpg │ └── _notes │ │ ├── index.jpg.mno │ │ ├── index_r1_c1.jpg.mno │ │ ├── index_r2_c4.jpg.mno │ │ ├── index_r3_c2.jpg.mno │ │ ├── index_r2_c1.jpg.mno │ │ ├── index_r2_c2.jpg.mno │ │ ├── index_r2_c3.jpg.mno │ │ ├── index_r3_c1.jpg.mno │ │ ├── index_r4_c1.jpg.mno │ │ ├── index_r4_c2.jpg.mno │ │ ├── index_r4_c3.jpg.mno │ │ ├── index_r3_c3.jpg.mno │ │ ├── index_r3_c4.jpg.mno │ │ ├── index_r3_c5.jpg.mno │ │ ├── index_r4_c4.jpg.mno │ │ └── index_r4_c5.jpg.mno ├── include │ ├── refresh.php │ ├── connect.php │ ├── hora.php │ ├── estilo.css │ ├── SAL.inc │ ├── functionLayout.php │ └── functions.php ├── index.php ├── cab.html ├── graphics.php ├── main.php ├── menu.php └── graficos.php ├── misc ├── screenshots │ ├── netactuator1.png │ ├── netactuator2.png │ ├── netactuator3.png │ ├── netactuator4.png │ └── netactuator5.png ├── 3rd-software │ ├── pmacct │ │ └── pmacct-0.12.5.tar.gz │ └── README └── academic-work │ ├── articles │ ├── SIRC-Artigo16.pdf │ └── Revista-Unicruz-Artigo26.pdf │ ├── graduation-conclusion-work │ ├── NETACT-TC2.pdf │ └── NETACT-TC2_Defesa.ppt │ ├── README │ └── LINKS ├── sql ├── repair.sh └── netactuator-mysql.sql ├── netactuator-apache.conf-dist ├── netactuator.conf-dist ├── proto.h ├── CREDITS ├── COPYING ├── timing.c ├── wrapper.c ├── eventos.c ├── README ├── scripts └── netactuator.sh ├── TODO ├── mysql_driver.c ├── pattern.c ├── Makefile ├── file.c ├── blacklist.c ├── netmask.c ├── defs.h ├── action.c ├── datastruct.c ├── INSTALL ├── limit.c ├── config.c ├── netactuator.c ├── topusers.c ├── graph.c └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /web/images/index.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index.jpg -------------------------------------------------------------------------------- /web/images/spacer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/spacer.gif -------------------------------------------------------------------------------- /web/images/index_r1_c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r1_c1.jpg -------------------------------------------------------------------------------- /web/images/index_r2_c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r2_c1.jpg -------------------------------------------------------------------------------- /web/images/index_r2_c2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r2_c2.jpg -------------------------------------------------------------------------------- /web/images/index_r2_c3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r2_c3.jpg -------------------------------------------------------------------------------- /web/images/index_r2_c4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r2_c4.jpg -------------------------------------------------------------------------------- /web/images/index_r3_c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r3_c1.jpg -------------------------------------------------------------------------------- /web/images/index_r3_c2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r3_c2.jpg -------------------------------------------------------------------------------- /web/images/index_r3_c3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r3_c3.jpg -------------------------------------------------------------------------------- /web/images/index_r3_c4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r3_c4.jpg -------------------------------------------------------------------------------- /web/images/index_r3_c5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r3_c5.jpg -------------------------------------------------------------------------------- /web/images/index_r4_c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r4_c1.jpg -------------------------------------------------------------------------------- /web/images/index_r4_c2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r4_c2.jpg -------------------------------------------------------------------------------- /web/images/index_r4_c3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r4_c3.jpg -------------------------------------------------------------------------------- /web/images/index_r4_c4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r4_c4.jpg -------------------------------------------------------------------------------- /web/images/index_r4_c5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/web/images/index_r4_c5.jpg -------------------------------------------------------------------------------- /misc/screenshots/netactuator1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/screenshots/netactuator1.png -------------------------------------------------------------------------------- /misc/screenshots/netactuator2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/screenshots/netactuator2.png -------------------------------------------------------------------------------- /misc/screenshots/netactuator3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/screenshots/netactuator3.png -------------------------------------------------------------------------------- /misc/screenshots/netactuator4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/screenshots/netactuator4.png -------------------------------------------------------------------------------- /misc/screenshots/netactuator5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/screenshots/netactuator5.png -------------------------------------------------------------------------------- /misc/3rd-software/pmacct/pmacct-0.12.5.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/3rd-software/pmacct/pmacct-0.12.5.tar.gz -------------------------------------------------------------------------------- /misc/academic-work/articles/SIRC-Artigo16.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/academic-work/articles/SIRC-Artigo16.pdf -------------------------------------------------------------------------------- /misc/academic-work/articles/Revista-Unicruz-Artigo26.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/academic-work/articles/Revista-Unicruz-Artigo26.pdf -------------------------------------------------------------------------------- /misc/academic-work/graduation-conclusion-work/NETACT-TC2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/academic-work/graduation-conclusion-work/NETACT-TC2.pdf -------------------------------------------------------------------------------- /misc/academic-work/graduation-conclusion-work/NETACT-TC2_Defesa.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stockrt/netactuator/HEAD/misc/academic-work/graduation-conclusion-work/NETACT-TC2_Defesa.ppt -------------------------------------------------------------------------------- /misc/3rd-software/README: -------------------------------------------------------------------------------- 1 | The work below this directory is not part of netactuator 2 | and is not under same licensing. Please refer to the copyright 3 | and author's notes inside each document. 4 | -------------------------------------------------------------------------------- /misc/academic-work/README: -------------------------------------------------------------------------------- 1 | The work below this directory is not part of netactuator 2 | and is not under same licensing. Please refer to the copyright 3 | and author's notes inside each document. 4 | -------------------------------------------------------------------------------- /sql/repair.sh: -------------------------------------------------------------------------------- 1 | # Para reparar tabelas "crashed" do mysql 2 | 3 | myisamchk -r /var/db/mysql/netactuator/storage_mass.MYI 4 | myisamchk -r /var/db/mysql/netactuator/*.MYI 5 | 6 | # Ou em /var/lib/db/mysql, /var/lib/mysql 7 | -------------------------------------------------------------------------------- /web/include/refresh.php: -------------------------------------------------------------------------------- 1 | "; 8 | ?> 9 | -------------------------------------------------------------------------------- /web/images/_notes/index.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r1_c1.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r2_c4.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r3_c2.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r2_c1.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r2_c2.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r2_c3.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r3_c1.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r4_c1.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r4_c2.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r4_c3.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r3_c3.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r3_c4.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r3_c5.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r4_c4.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/images/_notes/index_r4_c5.jpg.mno: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /web/include/connect.php: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /netactuator-apache.conf-dist: -------------------------------------------------------------------------------- 1 | # 2 | # Esta é a configuração do netactuator para ser acessado pelo Apache. 3 | # 4 | 5 | Alias /netactuator /usr/local/netactuator/web 6 | 7 | #AddDefaultCharset ISO-8859-1 8 | Options FollowSymLinks 9 | AllowOverride None 10 | Order deny,allow 11 | Allow from all 12 | 13 | -------------------------------------------------------------------------------- /netactuator.conf-dist: -------------------------------------------------------------------------------- 1 | # 2 | # Arquivo de configuração do netactuator. 3 | # 4 | 5 | ## Utilize o script de inicialização do banco para poder usar o netactuator ## 6 | 7 | ## Database ## 8 | 9 | # Database Host 10 | db_host=localhost 11 | 12 | # Database User 13 | db_user=netactuator 14 | 15 | # Database Password 16 | db_password=netdbpass 17 | 18 | # Database Name 19 | db_name=netactuator 20 | -------------------------------------------------------------------------------- /misc/academic-work/LINKS: -------------------------------------------------------------------------------- 1 | http://ctec.unicruz.edu.br/revista/artigos/26.pdf 2 | http://www.sirc.unifra.br/artigos2006/SIRC-Artigo16.pdf 3 | 4 | 5 | netactuator on Google Code: 6 | http://netactuator.googlecode.com 7 | 8 | netactuator on Github: 9 | https://github.com/stockrt/netactuator 10 | 11 | Author: Rogério Carvalho Schneider (stockrt@gmail.com) 12 | http://stockrt.github.com 13 | 14 | Web Interface: Lucas Schneider (scorfell@gmail.com) 15 | -------------------------------------------------------------------------------- /web/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | [ netactuator ] 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | <body> 16 | </body> 17 | 18 | -------------------------------------------------------------------------------- /proto.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | void inserir_blacklist (tipostring host, int expire); 21 | void remover_blacklist (tipostring host); 22 | int bloquear_host (tipostring info, int expire); 23 | void desbloquear_host (tipostring info); 24 | -------------------------------------------------------------------------------- /web/cab.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Untitled Document 6 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /CREDITS: -------------------------------------------------------------------------------- 1 | O netactuator foi idealizado e programado por mim como parte do meu TCC (trabalho de conclusão) para o curso de graduação 2 | em Ciência da Computação (UNICRUZ - Universidade de Cruz Alta / RS / Brasil). 3 | 4 | And the thanks goes to... 5 | 6 | - prof. Antônio Rodrigo Delepiane de Vit (UNICRUZ), por orientar meu trabalho. 7 | - profa. Liane Margarida Rockenbach Tarouco (UFRGS), por co-orientar meu trabalho. 8 | - Lucas Schneider, por programar a interface web toda do netactuator. Cada linha PHP/HTML neste sistema eu devo a ele. 9 | - Jeferson Franke, por assumir a continuidade deste projeto em seu TCC, efetuando alterações no código-fonte e na interface web. 10 | 11 | 12 | netactuator on Google Code: 13 | http://netactuator.googlecode.com 14 | 15 | netactuator on Github: 16 | https://github.com/stockrt/netactuator 17 | 18 | Author: Rogério Carvalho Schneider (stockrt@gmail.com) 19 | http://stockrt.github.com 20 | 21 | Web Interface: Lucas Schneider (scorfell@gmail.com) 22 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | netactuator is an active network management tool, for graphing individual 2 | host activities and make individual host behavior patterns, acting 3 | directly with the firewall rules to block machines whose behavior 4 | steped out of the historic pattern of communication flow. 5 | 6 | Copyright (C) 2006, 2007, 2008 Rogério Carvalho Schneider (stockrt@gmail.com) 7 | 8 | netactuator is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | netactuator is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see 20 | -------------------------------------------------------------------------------- /timing.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Pega a hora inicial 21 | void inicial (void) 22 | { 23 | time(&ini); 24 | } 25 | 26 | 27 | // Pega a hora final 28 | void final (tipostring mensagem) 29 | { 30 | time_t total; 31 | 32 | 33 | time(&end); 34 | total = end - ini; 35 | 36 | printf("Processing Time %s: %ld\n", mensagem, total); 37 | } 38 | -------------------------------------------------------------------------------- /web/include/hora.php: -------------------------------------------------------------------------------- 1 | $datacerta"; 38 | ?> 39 | -------------------------------------------------------------------------------- /wrapper.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | void pmacctd_wrapper (tipostring iface) 21 | { 22 | tipostring comando; 23 | 24 | 25 | // Monta o comando a ser executado. 26 | sprintf(comando, "%s \ 27 | -c src_host,dst_host \ 28 | -p /tmp/collect.pipe.%s \ 29 | -P memory \ 30 | -i %s \ 31 | -F /var/run/pmacctd.pid.%s \ 32 | -D", pmacctd_bin, iface, iface, iface); 33 | system(comando); 34 | } 35 | -------------------------------------------------------------------------------- /eventos.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Cadastra um evento 21 | void registrar_evento (tipostring host, long convs_as_source, long baseline, tipostring description) 22 | { 23 | MYSQL *conn=NULL; 24 | MYSQL_RES *res=NULL; 25 | MYSQL_ROW row; 26 | 27 | tipostring query; 28 | 29 | 30 | if ((conn = conectar())) 31 | { 32 | printf("Registrando novo evento %s %ld %ld %s\n", host, convs_as_source, baseline, description); 33 | sprintf(query, "INSERT INTO %s VALUES('%s', '%ld', '%ld', '%s', '%s', '%s', '%s');", 34 | EVENTOS_T, host, convs_as_source, baseline, data, hora, week_day, description); 35 | res = sql(query, conn); 36 | 37 | desconectar(conn); 38 | } // if conn 39 | } 40 | -------------------------------------------------------------------------------- /web/graphics.php: -------------------------------------------------------------------------------- 1 | ".$dados."
"; 26 | if(!file_exists("graph/".$dados."_".$time."_".$type."_day.png")) 27 | print $dados." - Gráfico não disponível
"; 28 | } 29 | 30 | } elseif (isset($host)){ 31 | print "
$host - $type

"; 32 | //print "Diário
"; 33 | print "

"; 34 | //print "Semanal
"; 35 | print "

"; 36 | //print "Mensal
"; 37 | print "

"; 38 | //print "Anual
"; 39 | print "

"; 40 | } 41 | ?> 42 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | netactuator is an active network management tool, for graphing individual 2 | host activities and make individual host behavior patterns, acting 3 | directly with the firewall rules to block machines whose behavior 4 | steped out of the historic pattern of communication flow. 5 | 6 | netactuator é uma ferramenta de gerência ativa de redes, que gera gráficos 7 | individuais de atividade por host e avalia individualmente o comportamento 8 | dos hosts de uma rede, atuando diretamente no firewall para bloquear as 9 | máquinas que venham a sair do seu padrão histórico de fluxo comunicação. 10 | 11 | - O netactuator pode gerar gráficos web de utilização de recursos, tais como conexões originadas e tráfego de dados in/out por host na rede. 12 | - É possível visualizar os Top Users da rede nos últimos N minutos de coleta, ordenandos por bytes, pacotes e conexões in/out. 13 | - O sistema envia alertas por e-mail quando um evento novo ocorre (máquina bloqueada na rede) e registra em log outros eventos. 14 | - As regras do firewall são "flutuadas" pelo netactuator, mantendo as máquinas bloqueadas por pequenos periodos e depois as liberando. 15 | - Hosts podem ser bloqueados/liberados no firewall a qualquer momento, via interface web do netactuator. 16 | - Toda a configuração e gerência da ferramenta é feita pela web. 17 | 18 | 19 | netactuator on Google Code: 20 | http://netactuator.googlecode.com 21 | 22 | netactuator on Github: 23 | https://github.com/stockrt/netactuator 24 | 25 | Author: Rogério Carvalho Schneider (stockrt@gmail.com) 26 | http://stockrt.github.com 27 | 28 | Web Interface: Lucas Schneider (scorfell@gmail.com) 29 | -------------------------------------------------------------------------------- /web/main.php: -------------------------------------------------------------------------------- 1 | "; 41 | } else { 42 | echo "


WELCOME TO netactuator.
"; 43 | } 44 | 45 | if($action=='list') 46 | print $erro; 47 | ?> 48 | -------------------------------------------------------------------------------- /scripts/netactuator.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # start/stop/restart/status do netactuator 4 | # 5 | # chkconfig: 2345 85 15 6 | # description: netactuator 7 | # 8 | # Author: Rogério Carvalho Schneider (stockrt@gmail.com) 9 | # http://stockrt.github.com 10 | 11 | PID="" 12 | export LANG="en_US" 13 | export LANGUAGE="en_US" 14 | export LC_ALL="C" 15 | 16 | getpid() 17 | { 18 | PID=$(pgrep -f /usr/local/bin/netactuator) 19 | } 20 | 21 | start() 22 | { 23 | getpid 24 | 25 | if [ "$PID" == "" ] 26 | then 27 | if [ -x /usr/local/bin/netactuator ] 28 | then 29 | /usr/local/bin/netactuator >> /var/log/netactuator.log 2>&1 30 | getpid 31 | echo "O netactuator foi iniciado sob o pid $PID" 32 | fi 33 | else 34 | echo "O netactuator já está rodando sob o pid $PID" 35 | fi 36 | } 37 | 38 | stop() 39 | { 40 | getpid 41 | 42 | if [ "$PID" == "" ] 43 | then 44 | echo "O netactuator estava rodando?" 45 | pkill pmacctd > /dev/null 2>&1 46 | pkill pmacct > /dev/null 2>&1 47 | pkill netactuator > /dev/null 2>&1 48 | else 49 | echo "Encerrando o netactuator sob o pid $PID" 50 | pkill pmacctd > /dev/null 2>&1 51 | pkill pmacct > /dev/null 2>&1 52 | pkill netactuator > /dev/null 2>&1 53 | kill -9 $PID > /dev/null 2>&1 54 | echo "O netactuator foi finalizado" 55 | fi 56 | } 57 | 58 | restart() 59 | { 60 | stop 61 | start 62 | } 63 | 64 | status() 65 | { 66 | getpid 67 | 68 | if [ "$PID" == "" ] 69 | then 70 | echo "O netactuator não está rodando" 71 | else 72 | echo "O netactuator está rodando sob o pid $PID" 73 | fi 74 | } 75 | 76 | case "$1" in 77 | start) 78 | start 79 | ;; 80 | 81 | stop) 82 | stop 83 | ;; 84 | 85 | restart) 86 | stop 87 | start 88 | ;; 89 | 90 | status) 91 | status 92 | ;; 93 | 94 | *) 95 | echo "Modo de uso: `basename $0` {start stop restart status}" >&2 96 | exit 64 97 | ;; 98 | esac 99 | 100 | exit 0 101 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Algumas coisas a fazer ainda... 2 | 3 | ** 4 | ** Daemon 5 | ** 6 | - Sanity check no uso de mask /0.0.0.0 pois trava o netmask.c do paul_davis. 7 | - Coleta por SNMP. 8 | - Baseline maths (melhorar o cálculo de baseline com um método 9 | matemático mais aprimorado, não apenas uma média como ainda é o caso). 10 | - Bloquear definitivo após 3 incidências? 11 | - Montar tabela com ajuste automático de espaçamento para 12 | os gráficos. Não raramente o cabeçalho fica desalinhado. 13 | - Syslog e remover os redirects do scripts de inicialização. 14 | - Tratamento de sinais para gracefull exit. 15 | - Intervalo de geração de gráficos deve ser removido 16 | de defs.h e colocado em configuração no banco de dados, junto 17 | com as demais entradas de configuração. 18 | - Logo que se inicia o aprendizado (7 dias por default) os gráficos 19 | de base ficam marcando todo o tráfego como comprometido. Somente 20 | depois deste período é que se terá gráficos com áreas verdes. Isso 21 | poderia ser ajustado para ser considerado tráfego normal até que 22 | o período de aprendizado seja encerrado. Acho que isso se deve ao 23 | fato da baseline ser zero neste período, por isso tudo fica marcado 24 | como comprometido. Quem sabe um pouco mais de lógica com condicionais 25 | no graph.c? Ver rrdgraph_rpn (1). 26 | - Revisar e eliminar memory-leaks. 27 | - timing.c: inicial() e final() usam variáveis globais, e isso não 28 | está certo! 29 | - No netmask.c existem chamadas para exit() ao não aceitar a máscara 30 | usada. O range permitido é de 1 até 30. Realizar sanity-check nas masks 31 | utilizadas e remover o exit() para que o daemon não morra por erro 32 | de configuração do usuário. 33 | 34 | ** 35 | ** Web Interface 36 | ** 37 | - Existem alguns warnings para o PHP que podem ser revisados, 38 | como acesso à variáveis não declaradas (em casos onde os condicionais 39 | evitam a inicialização de uma variável, que acaba sendo 40 | mesmo assim referenciada em outro ponto do código). 41 | - connect.php deve trazer os dados do netactuator.conf. 42 | 43 | ** 44 | ** Extra 45 | ** 46 | - Perhaps translate all the comments and texts to English to make 47 | it more world wide? 48 | 49 | 50 | netactuator on Google Code: 51 | http://netactuator.googlecode.com 52 | 53 | netactuator on Github: 54 | https://github.com/stockrt/netactuator 55 | 56 | Author: Rogério Carvalho Schneider (stockrt@gmail.com) 57 | http://stockrt.github.com 58 | 59 | Web Interface: Lucas Schneider (scorfell@gmail.com) 60 | -------------------------------------------------------------------------------- /mysql_driver.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | #include 21 | 22 | 23 | MYSQL *mysql_conn_global; 24 | 25 | 26 | //int conectar (void) 27 | MYSQL * conectar (void) 28 | { 29 | MYSQL *mysql_conn; 30 | int i, flag_conectou=0; 31 | 32 | 33 | mysql_conn = mysql_init(NULL); 34 | if (mysql_conn == NULL) 35 | { 36 | printf("mysql_init() failed (probably out of memory)\n"); 37 | return NULL; 38 | } 39 | 40 | // mysql_conn, host, user, passwd, db 41 | for(i=0; i 2 | 3 | 4 | 5 | Untitled Document 6 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 |
31 | 32 | "; 60 | 61 | poweredby(); 62 | 63 | mysql_free_result($result); 64 | ?>  
73 | 74 | 75 | -------------------------------------------------------------------------------- /web/include/estilo.css: -------------------------------------------------------------------------------- 1 | 122 | -------------------------------------------------------------------------------- /pattern.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Atualiza a tabela de padrão de comportamento 21 | void update_pattern_def (void) 22 | { 23 | MYSQL *conn=NULL; 24 | MYSQL_RES *res=NULL; 25 | MYSQL_ROW row; 26 | 27 | tipostring query; 28 | time_t data_hora; 29 | struct tm *sdata; 30 | int last_value_hour=-1; // em cada laço do while principal ele é avaliado 31 | 32 | 33 | while (1) 34 | { 35 | // Captura a data atual 36 | time(&data_hora); 37 | sdata = localtime(&data_hora); 38 | 39 | // 6 - ATUALIZAÇÃO DE PADRÃO COMPORTAMENTAL 40 | // Se o valor da hora for diferente do valor anterior 41 | // então é uma nova hora, e o update da tabela pattern_def 42 | // deverá ser realizado 43 | if (sdata->tm_hour != last_value_hour) 44 | // if (sdata->tm_min != last_value_hour) 45 | { 46 | //printf("pattern... pattern... pattern... pattern... pattern... pattern... \n"); 47 | inicial(); 48 | if ((conn = conectar())) 49 | { 50 | // Limpa os mais antigos de MASS_T 51 | sprintf(query, "DELETE FROM %s WHERE data < DATE_SUB(CURDATE(), INTERVAL %d DAY);", MASS_T, days_to_keep); 52 | res = sql(query, conn); 53 | 54 | // Zera PATTERN_T 55 | sprintf(query, "DELETE FROM %s;", PATTERN_T); 56 | res = sql(query, conn); 57 | 58 | // Atualiza 59 | sprintf(query, "INSERT INTO %s () \ 60 | SELECT host, AVG(convs_as_source), MAX(convs_as_source) \ 61 | FROM %s WHERE \ 62 | convs_as_source > 0 AND \ 63 | flow_capture_time_min = %d AND \ 64 | flag_clean = %d \ 65 | GROUP BY host HAVING MIN(data) < DATE_SUB(CURDATE(), INTERVAL %d DAY);", 66 | PATTERN_T, MASS_T, flow_capture_time_min, FLAG_CLEAN, days_to_learn); 67 | res = sql(query, conn); 68 | 69 | desconectar(conn); 70 | } // if conn 71 | final("PATTERN"); 72 | last_value_hour = sdata->tm_hour; 73 | // last_value_hour = sdata->tm_min; 74 | } 75 | 76 | sleep(DELAY_UPDATE); 77 | } // while not the end of the world 78 | } 79 | -------------------------------------------------------------------------------- /web/graficos.php: -------------------------------------------------------------------------------- 1 |
2 | Buscar host: 3 | 4 | 5 |
6 | 7 |
"; 49 | //echo "Mostram-se páginas de " . $TAMANHO_PAGINA . " registros cada uma
"; 50 | //echo "A mostrar a página " . $pagina . " de " . $total_paginas . "

"; 51 | 52 | //construo a sentença SQL 53 | //$ssql = "SELECT host FROM storage_pattern_def " . $criterio . " LIMIT " . $inicio . "," . $TAMANHO_PAGINA; 54 | $ssql = "SELECT DISTINCT host FROM storage_mass " . $criterio . " LIMIT " . $inicio . "," . $TAMANHO_PAGINA; 55 | $rs = mysql_query($ssql); 56 | $max = mysql_num_rows($rs); 57 | 58 | for($i=0;$i < $max; $i++) { 59 | list($dados) = mysql_fetch_row($rs); 60 | //echo "$dados
"; 61 | // coloquei (rogerio) para imprimir o valor do path e descobri que time era o problema dos graficos nao aparecerem mais (devido ao refresh.php ter mudado) 62 | // echo "graph/".$dados."_".$time."_traf_day.png"; 63 | if(file_exists("graph/".$dados."_".$time."_traf_day.png")){ 64 | print "".$dados."    traf 65 |   base
"; 66 | } 67 | if(!file_exists("graph/".$dados."_".$time."_traf_day.png")) 68 | print $dados." - Gráfico não disponível
"; 69 | 70 | } 71 | echo("

"); 72 | //fechamos o conjunto de resultado e a conexão com a base de dados 73 | mysql_free_result($rs); 74 | mysql_close($connect); 75 | 76 | //mostro os diferentes índices das páginas, se é que há várias páginas 77 | if ($total_paginas> 1){ 78 | for ($i=1;$i<=$total_paginas;$i++){ 79 | if ($pagina == $i) 80 | //se mostro o índice da página atual, não coloco link 81 | echo "| $pagina "; 82 | else 83 | //se o índice não corresponde com a página mostrada atualmente, coloco o link para ir a essa página 84 | echo "| " . $i . " "; 85 | } 86 | echo " |"; 87 | } 88 | ?> 89 | 90 |
91 |
92 |

<- Retornar ao menu
93 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GCC=/usr/bin/gcc 2 | 3 | MAIN_INPUT=netactuator.c 4 | MAIN_OUTPUT=netactuator 5 | CONFIG_FILE=netactuator.conf-dist 6 | MYSQL_LIBS=`mysql_config --libs` 7 | MYSQL_INCLUDE=`mysql_config --include` 8 | COMP=$(GCC) -o $(MAIN_OUTPUT) -g $(MAIN_INPUT) $(MYSQL_LIBS) -lpthread -lrrd -L/usr/local/lib -L/usr/lib -L/opt/local/lib -L/opt/lib $(MYSQL_INCLUDE) -I/usr/local/include -I/usr/include -I/opt/local/include -I/opt/include 9 | INST_DEST=/usr/local/bin 10 | INST_DEST_CONF=/usr/local/etc/netactuator 11 | INST_DEST_WEB=/usr/local/netactuator 12 | 13 | default: 14 | @echo 15 | 16 | @echo "As opções para make são:" 17 | @echo 18 | @echo "build/all -> Compila o netactuator." 19 | @echo "instalar -> Instala o netactuator (depois de compilado). Binário e interface Web." 20 | @echo "desinstalar -> Desinstala o netactuator." 21 | @echo "clean -> Limpa o workdir e remove o binário gerado do diretório atual." 22 | @echo 23 | 24 | build: all 25 | all: 26 | @echo 27 | 28 | @echo "Compilando com a linha $(COMP) ..." 29 | @$(COMP) 30 | @sleep 1 31 | @echo "Pronto" 32 | @echo 33 | 34 | instalar: 35 | @echo 36 | 37 | @echo "Instalando \"$(MAIN_OUTPUT)\" em \"$(INST_DEST)\"" 38 | @mkdir -p $(INST_DEST) 39 | @cp -v $(MAIN_OUTPUT) $(INST_DEST) 40 | @sleep 1 41 | @echo "Pronto" 42 | @echo 43 | 44 | @echo "Instalando \"$(CONFIG_FILE)\" em \"$(INST_DEST_CONF)\"" 45 | @mkdir -p $(INST_DEST_CONF) 46 | @cp -v $(CONFIG_FILE) $(INST_DEST_CONF) 47 | @sleep 1 48 | @echo "Pronto" 49 | @echo 50 | 51 | @echo "Instalando o sistema web do netactuator em \"$(INST_DEST_WEB)/web\"" 52 | @mkdir -p $(INST_DEST_WEB) 53 | @cp -Rv web $(INST_DEST_WEB) 54 | @sleep 1 55 | @echo "Pronto" 56 | @echo 57 | 58 | @echo "Fixando permissões de $(INST_DEST)/$(MAIN_OUTPUT)" 59 | @chmod 555 $(INST_DEST)/$(MAIN_OUTPUT) 60 | @sleep 1 61 | @echo "Pronto" 62 | @echo 63 | 64 | @echo 65 | @echo "****************************************************************" 66 | @echo 67 | @echo "- Ajuste as configurações de netactuator.conf:" 68 | @echo " # cp $(INST_DEST_CONF)/$(CONFIG_FILE) $(INST_DEST_CONF)/netactuator.conf" 69 | @echo 70 | @echo "- Utilize o script de inicialização do banco de dados para começar a usar o netactuator:" 71 | @echo " # mysql < sql/netactuator-mysql.sql" 72 | @echo 73 | @echo "- Ajuste o seu httpd.conf:" 74 | @echo " Alias /netactuator /usr/local/netactuator/web" 75 | @echo " " 76 | @echo " #AddDefaultCharset ISO-8859-1" 77 | @echo " Options FollowSymLinks" 78 | @echo " AllowOverride None" 79 | @echo " Order deny,allow" 80 | @echo " Allow from all" 81 | @echo " " 82 | @echo "- Ou utilize o arquivo fornecido:" 83 | @echo " # cp netactuator-apache.conf-dist /etc/httpd/conf.d/netactuator-apache.conf" 84 | @echo 85 | @echo "- Altere os seguintes parâmetros no php.ini:" 86 | @echo " output_buffering = On" 87 | @echo " variables_order = \"EGPCS\"" 88 | @echo " register_globals = On" 89 | @echo " session.auto_start = 1" 90 | @echo 91 | @echo "- Utilize o script de start/stop/status do netactuator:" 92 | @echo " # ./scripts/netactuator.sh" 93 | @echo 94 | @echo "****************************************************************" 95 | @echo 96 | 97 | desinstalar: 98 | @echo 99 | 100 | @echo "Removendo \"$(MAIN_OUTPUT)\" de \"$(INST_DEST)\"" 101 | @rm -f $(INST_DEST)/$(MAIN_OUTPUT) 102 | @sleep 1 103 | @echo "Pronto" 104 | @echo 105 | @echo "****************************************************************" 106 | @echo 107 | @echo "Os arquivos de configuração serão mantidos em \"$(INST_DEST_CONF)\"." 108 | @echo "O diretório \"$(INST_DEST_WEB)\" foi mantido com suas bases históricas, remova-o manualmente, se desejar." 109 | @echo 110 | @echo "****************************************************************" 111 | @echo 112 | 113 | clean: 114 | @echo 115 | 116 | @echo "Removendo binários e objetos locais de $(MAIN_OUTPUT) ..." 117 | @rm -f $(MAIN_OUTPUT) 118 | @rm -f $(MAIN_OUTPUT).o 119 | @rm -f $(MAIN_OUTPUT).core 120 | @sleep 1 121 | @echo "Pronto" 122 | @echo 123 | -------------------------------------------------------------------------------- /file.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Função que padroniza procedimento de abertura de arquivos 21 | FILE *rfopen (tipostring file_temp, tipostring modo) 22 | { 23 | FILE *temp_handler; 24 | 25 | 26 | temp_handler = fopen(file_temp, modo); 27 | 28 | if (temp_handler == NULL) 29 | { 30 | printf("\n\n"); 31 | printf("Problema ao abrir o arquivo: %s", file_temp); 32 | printf("\n\n"); 33 | return NULL; 34 | } 35 | else 36 | return temp_handler; 37 | } 38 | 39 | 40 | // Função que padroniza procedimento de abertura de pipes de comandos 41 | FILE *rpopen (tipostring cmd_temp, tipostring modo) 42 | { 43 | FILE *temp_handler; 44 | 45 | 46 | temp_handler = popen(cmd_temp, modo); 47 | 48 | if (temp_handler == NULL) 49 | { 50 | printf("\n\n"); 51 | printf("Problema ao executar o comando: %s", cmd_temp); 52 | printf("\n\n"); 53 | return NULL; 54 | } 55 | else 56 | return temp_handler; 57 | } 58 | 59 | 60 | // Verifica se um IP pertence a uma das redes definidas pelo usuário 61 | int is_network_defined (tipostring info) 62 | { 63 | struct in_addr addr; 64 | unsigned long ip_avaliar=0; 65 | int i=0; 66 | 67 | 68 | /* Convert the string ip address to network order address */ 69 | if (inet_aton(info, &addr)) 70 | { 71 | ip_avaliar = ntohl(addr.s_addr); 72 | for(i=0; i= networks_ranges[i][0] && ip_avaliar <= networks_ranges[i][1]) 74 | { 75 | // Pertence a uma das redes definidas 76 | // printf("IP %s pertence a uma das redes definidas.\n", info); 77 | return 1; 78 | } 79 | } 80 | 81 | // Não pertence a nenhuma das redes definidas 82 | // printf("IP %s NAO pertence a uma das redes definidas.\n", info); 83 | return 0; 84 | } 85 | 86 | 87 | // Varre a coleta gerada pelo pmacctd para separar/contabilizar as conversações e dados de tráfego 88 | void processar_coleta_gerada (tipostring iface) 89 | { 90 | tipostring linha; 91 | tipostring comando; 92 | tipostring ip_src, ip_dst; 93 | long ip_recv_f, ip_recv_b, ip_sent_f, ip_sent_b, packets, bytes; 94 | FILE *in_handler; 95 | 96 | 97 | // Captura os dados já coletados e zera para a nova coleta iniciar imediatamente, nenhum byte é perdido neste modelo 98 | sprintf(comando, "%s -s -p /tmp/collect.pipe.%s -e | grep -v SRC | grep -v total | \ 99 | grep -v INFO | grep -v OK", pmacct_bin, iface); 100 | //printf("Lançando pmacct - %s\n", comando); 101 | in_handler = rpopen(comando, "r"); 102 | if (in_handler) 103 | { 104 | while (fgets(linha, MAX_TAM_LINHA, in_handler)) // Captura as estatísticas 105 | { 106 | // Não processa a linha final do pmacct, uma linha em branco... 107 | if (linha[0] != '\n') 108 | { 109 | // Incrementa o contador dos registros nos logs (com repeticao) 110 | ++count_log; 111 | //printf("linha : %s", linha); 112 | //printf("leitura linha..\n"); 113 | // Captura os dados vindos do rpopen 114 | sscanf(linha, "%s %s %ld %ld", ip_src, ip_dst, &packets, &bytes); 115 | 116 | // Antes de adicionar o registro na árvore deve-se verificar se o IP pertence a uma das redes definidas em netactuator.conf 117 | if (is_network_defined(ip_src)) 118 | { 119 | // Quando o IP é source ele fez UPLOAD 120 | ip_sent_f = packets; 121 | ip_sent_b = bytes; 122 | adicionar_registro_arvore(ip_src, 0, 0, ip_sent_f, ip_sent_b, iface); 123 | } 124 | if (is_network_defined(ip_dst)) 125 | { 126 | // Quando o IP é destin ele fez DOWNLOAD 127 | ip_recv_f = packets; 128 | ip_recv_b = bytes; 129 | adicionar_registro_arvore(ip_dst, ip_recv_f, ip_recv_b, 0, 0, iface); 130 | } 131 | } // if linha 132 | } // while fgets linha 133 | 134 | pclose(in_handler); 135 | } // in_handler rpopen pmacct 136 | } 137 | -------------------------------------------------------------------------------- /blacklist.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Cadastra um IP bloqueado na lista de bloqueados 21 | void inserir_blacklist (tipostring host, int expire) 22 | { 23 | MYSQL *conn=NULL; 24 | MYSQL_RES *res=NULL; 25 | MYSQL_ROW row; 26 | 27 | time_t data_hora; 28 | 29 | tipostring query; 30 | long time_bloqueio, expire_time; 31 | 32 | 33 | if ((conn = conectar())) 34 | { 35 | // Captura a data atual 36 | time(&data_hora); 37 | 38 | time_bloqueio = data_hora; 39 | expire_time = time_bloqueio + (block_time_min * 60); 40 | 41 | // Só insere se vir com 1, casos automáticos, não via web 42 | if (expire) 43 | { 44 | sprintf(query, "INSERT INTO %s (host,time_bloqueio,expire_time,description) VALUES('%s', '%ld', '%ld', 'Bloqueado pelo netactuator');", BLACKLIST_T, host, time_bloqueio, expire_time); 45 | res = sql(query, conn); 46 | } 47 | 48 | desconectar(conn); 49 | } // if conn 50 | } 51 | 52 | 53 | // Descadastra um host da lista de bloqueados 54 | void remover_blacklist (tipostring host) 55 | { 56 | MYSQL *conn=NULL; 57 | MYSQL_RES *res=NULL; 58 | MYSQL_ROW row; 59 | 60 | tipostring query; 61 | 62 | 63 | if ((conn = conectar())) 64 | { 65 | sprintf(query, "DELETE FROM %s WHERE host = '%s';", BLACKLIST_T, host); 66 | res = sql(query, conn); 67 | 68 | desconectar(conn); 69 | } // if conn 70 | } 71 | 72 | 73 | // Monitora os expire times dos bloqueios (flutuação) e faz bloqueios da web 74 | void on_the_fly (void) 75 | { 76 | MYSQL *conn=NULL; 77 | MYSQL_RES *res=NULL; 78 | MYSQL_ROW row; 79 | 80 | time_t data_hora; 81 | 82 | tipostring query; 83 | tipostring host; 84 | tipostring comando; 85 | long expire_time; 86 | FILE *in_handler; 87 | tipostring linha; 88 | int flag_consta=0; 89 | 90 | 91 | while (1) 92 | { 93 | // Captura a data atual 94 | time(&data_hora); 95 | 96 | if ((conn = conectar())) 97 | { 98 | sprintf(query, "SELECT host,expire_time FROM %s;", BLACKLIST_T); 99 | res = sql(query, conn); 100 | 101 | while ((row = mysql_fetch_row(res))) 102 | { 103 | strcpy(host, row[0]); 104 | expire_time = atol(row[1]); 105 | 106 | if (expire_time <= data_hora && expire_time != 0) 107 | { 108 | desbloquear_host(host); 109 | registrar_evento(host, -1, -1, "Desbloqueado"); 110 | } 111 | else 112 | bloquear_host(host, 0); // Será testado se já está ou não bloqueado 113 | } 114 | 115 | // Gera a lista dos atuais bloqueados no firewall e verifica quais deve liberar 116 | if (is_ipfw) 117 | sprintf(comando, "%s list | grep \"deny ip from\" | grep \"to any\" | awk '{print $5}'", fire_bin); 118 | else if (is_iptables) 119 | sprintf(comando, "%s -L -n -t filter | grep DROP | awk '{print $4}'", fire_bin); 120 | 121 | in_handler = rpopen(comando, "r"); 122 | if (in_handler) 123 | { 124 | while (fgets(linha, MAX_TAM_LINHA, in_handler)) 125 | { 126 | flag_consta = 0; // para cada host, zerar a marcação e verificar na tabela 127 | linha[strlen(linha)-1] = '\0'; // remove o \n do fim da string 128 | sprintf(query, "SELECT * FROM %s WHERE host = '%s';", BLACKLIST_T, linha); 129 | //printf("q: %s\n", query); 130 | res = sql(query, conn); 131 | 132 | // Verifica se o host consta como bloqueado, caso contrário o libera (foi liberado pela web) 133 | if ((row = mysql_fetch_row(res))) 134 | flag_consta = 1; 135 | mysql_free_result(res); 136 | 137 | if (!flag_consta) 138 | desbloquear_host(linha); 139 | //printf("while filter drops\n"); 140 | //fflush(stdout); 141 | } 142 | 143 | pclose(in_handler); 144 | } 145 | 146 | desconectar(conn); 147 | } // if conn 148 | 149 | fflush(stdout); 150 | sleep(DELAY_EXPIRE); 151 | } // while not the end of the world 152 | } 153 | -------------------------------------------------------------------------------- /web/include/SAL.inc: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * - 28/07: MySQL Support - mSQL support 8 | * - 29/07: PostgreSQL Support 9 | * - 03/08: ODBC Support 10 | */ 11 | 12 | /* 13 | * 14 | * Set the variable $dbtype to any of the following 15 | * values: MySQL, mSQL, Postgres, ODBC before including 16 | * this library 17 | * 18 | */ 19 | 20 | /* $dbtype = "MySQL"; */ /* $dbtype = "mSQL"; */ /* $dbtype = "PostgreSQL"; */ /* $dbtype = "ODBC"; */ 21 | function SQL_connect($host, $user, $password, $db) { $password = base64_decode($password); 22 | global $dbtype; switch ($dbtype) { 23 | case "MySQL": 24 | $conn=mysql_pconnect($host, $user, $password); 25 | mysql_select_db($db); 26 | return $conn; 27 | break;; 28 | 29 | case "mSQL": 30 | $conn=msql_pconnect($host); 31 | msql_select_db($db); 32 | return $conn; 33 | break;; 34 | 35 | case "PostgreSQL": 36 | $conn=pg_connect("host=$host port='5432' dbname=$db user=$user password=$password"); 37 | return $conn; 38 | break;; 39 | 40 | case "ODBC": 41 | $conn=odbc_pconnect($db,$user,$password); 42 | return $conn; 43 | break;; 44 | 45 | default: 46 | $conn=mysql_pconnect($host, $user, $password); 47 | mysql_select_db($db); 48 | return $conn; 49 | break;; 50 | } 51 | } 52 | 53 | /* 54 | * SQL_query($host, $user, $password, $db) 55 | * executes an SQL statement, returns a result identifier 56 | */ 57 | function SQL_query($query, $id) { global $dbtype; switch ($dbtype) { 58 | case "MySQL": 59 | $res=mysql_query($query, $id); 60 | return $res; 61 | break;; 62 | 63 | case "mSQL": 64 | $res=msql_query($query, $id); 65 | return $res; 66 | break;; 67 | 68 | case "PostgreSQL": 69 | $res=pg_query($id,$query); 70 | return $res; 71 | break;; 72 | 73 | case "ODBC": 74 | $rid=odbc_prepare($id,$query); 75 | $res=odbc_execute($rid); 76 | return $res; 77 | break;; 78 | 79 | default: 80 | $res=mysql_query($query, $id); 81 | return $res; 82 | break;; 83 | } 84 | } 85 | 86 | /* 87 | * SQL_num_rows($host, $user, $password, $db) 88 | * given a result identifier, returns the number of affected rows 89 | */ 90 | function SQL_num_rows($res) { global $dbtype; switch ($dbtype) { 91 | case "MySQL": 92 | $rows=mysql_num_rows($res); 93 | return $rows; 94 | break;; 95 | 96 | case "mSQL": 97 | $rows=msql_num_rows($res); 98 | return $rows; 99 | break;; 100 | 101 | case "PostgreSQL": 102 | $rows=pg_num_rows($res); 103 | return $rows; 104 | break;; 105 | 106 | case "ODBC": 107 | $rows=odbc_num_rows($res); 108 | return $rows; 109 | break;; 110 | 111 | default: 112 | $rows=mysql_num_rows($res); 113 | return $rows; 114 | break;; 115 | } 116 | } 117 | 118 | /* 119 | * SQL_fetchrow($res,$row) 120 | * given a result identifier, returns an array with the resulting row 121 | * Needs also a row number for compatibility with PostgreSQL 122 | */ 123 | function SQL_fetch_row($res, $nr) { global $dbtype; switch ($dbtype) { 124 | case "MySQL": 125 | $row = array(); 126 | $row = mysql_fetch_row($res); 127 | return $row; 128 | break;; 129 | 130 | case "mSQL": 131 | $row = array(); 132 | $row = msql_fetch_row($res); 133 | return $row; 134 | break;; 135 | 136 | case "PostgreSQL": 137 | $row = array(); 138 | $row = pg_fetch_row($res,$nr); 139 | return $row; 140 | break;; 141 | 142 | case "ODBC": 143 | $row = array(); 144 | $cols = odbc_fetch_into($res, $nr, &$row); 145 | return $row; 146 | break;; 147 | 148 | default: 149 | $row = array(); 150 | $row = mysql_fetch_row($res); 151 | return $row; 152 | break;; 153 | } 154 | } 155 | 156 | /* 157 | * SQL_fetch_array($res,$row) 158 | * given a result identifier, returns an associative array 159 | * with the resulting row using field names as keys. 160 | * Needs also a row number for compatibility with PostgreSQL. 161 | */ 162 | function SQL_fetch_array($res, $nr) { global $dbtype; switch ($dbtype) { 163 | case "MySQL": 164 | $row = array(); 165 | $row = mysql_fetch_array($res); 166 | return $row; 167 | break;; 168 | 169 | case "mSQL": 170 | $row = array(); 171 | $row = msql_fetch_array($res); 172 | return $row; 173 | break;; 174 | 175 | case "PostgreSQL": 176 | $row = array(); 177 | $row = pg_fetch_array($res,$nr); 178 | return $row; 179 | break;; 180 | 181 | /* 182 | * ODBC doesn't have a native _fetch_array(), so we have to 183 | * use a trick. Beware: this might cause HUGE loads! 184 | */ 185 | case "ODBC": 186 | $row = array(); 187 | $result = array(); 188 | $result = odbc_fetch_row($res, $nr); 189 | $nf = count($result)+2; /* Field numbering starts at 1 */ 190 | for($count=1; $count < $nf; $count++) { 191 | $field_name = odbc_field_name($res, $count); 192 | $field_value = odbc_result($res, $field_name); 193 | $row[$field_name] = $field_value; 194 | } 195 | return $row; 196 | break;; 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /netmask.c: -------------------------------------------------------------------------------- 1 | /* 2 | * netmask.c 3 | * Copyright (C) 2000 Paul Davis, pdavis@lpccomp.bc.ca 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 2 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software 17 | * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 18 | * 19 | * 20 | * This program takes an IP address and netmask from the command line 21 | * and shows the netmask, netmask bits, network address, broadcast address, 22 | * host IP range within the subnet and the number of such hosts. 23 | * 24 | * 25 | * I have made some modifications on this program, so I use it as a include 26 | * on netactuator, to filter IPs, matching against to the defined netmask to see if I 27 | * should or should not consider this IP for processing (filtering, graphing, you name it). 28 | * The accepted range is saved on the global vector networks_ranges[] 29 | * defs.h:unsigned long networks_ranges[MAX_ARGS][3]; // campo 0 = ip_inicial, campo 1 = ip_final, campo 2 = maskbits (inseridos somente na função netmask_paul_davis()) 30 | * 31 | * Modification by: Rogério Carvalho Schneider (stockrt@gmail.com) 32 | * http://stockrt.github.com 33 | * 34 | */ 35 | 36 | 37 | /* Convert the given ip address in native byte order to a printable string */ 38 | char * my_ntoa(unsigned long ip) 39 | { 40 | struct in_addr addr; 41 | 42 | 43 | addr.s_addr = htonl(ip); 44 | return inet_ntoa(addr); 45 | } 46 | 47 | 48 | // Converte a entrada ip/mask em valores para avaliação no sistema (long). 49 | // Coloca esses dados em uma tabela. 50 | void netmask_paul_davis (void) 51 | { 52 | struct in_addr addr, netmask; 53 | unsigned long mask, network, hostmask, broadcast; 54 | int maskbits; 55 | int i, i_net; 56 | tipostring ip_rog, mask_rog; 57 | 58 | 59 | for (i_net=0; i_net 30 ) 100 | { 101 | fprintf(stderr, "Invalid net mask bits (1-30): %d\n", maskbits); 102 | exit(1); 103 | } 104 | /* Create the netmask from the number of bits */ 105 | mask = 0; 106 | for(i=0; i 5 | 6 |
[ $tb ]
7 | 8 | "; 9 | } 10 | 11 | function topTabelas() { 12 | print " 13 | 14 | 15 | 16 | 17 | 18 | "; 19 | } 20 | 21 | function formTables($row, $description) { 22 | print" 23 | 24 | 27 | 28 | 29 | "; 30 | } 31 | 32 | function formFields($tb, $field, $i, $action, $view_insert, $view_alter, $view_id) { 33 | if($view_insert=='1') { 34 | print ""; 35 | } 36 | print ""; 37 | for($j=0; $j < count($field); $j++) 38 | if($field[$j] == 'id') { 39 | if($view_id == '1') 40 | print ""; 41 | } else { 42 | if($j==(count($field)-1)) 43 | print ""; 44 | else 45 | print ""; 46 | } 47 | print ""; 48 | } 49 | 50 | function formTopUsersFields($tb, $field, $i, $action) { 51 | print ""; 52 | for($j=0; $j < count($field); $j++) 53 | print ""; 54 | print ""; 55 | } 56 | 57 | function selectTopUsers($toptype) { 58 | $sql = "SELECT * FROM net_topusers WHERE toptype='$toptype'"; 59 | $res = mysql_query($sql); 60 | 61 | while ($dados = mysql_fetch_array($res)) { 62 | print""; 63 | for($j=0; $j < count($dados); $j++) { 64 | if($field[$j] == 'id') 65 | print ""; 66 | else { 67 | // print ""; 68 | if($j == 0) // host com link 69 | print ""; 70 | else 71 | print ""; 72 | } 73 | } 74 | print""; 75 | } 76 | } 77 | 78 | function formGraphics() { 79 | print" 80 | 81 | 84 | 85 | "; 86 | } 87 | 88 | function formDados($tb, $dados, $i) { 89 | print ""; 90 | for($j=0; $j < count($dados); $j++) 91 | print ""; 92 | print ""; 93 | } 94 | 95 | function formUpdateItem($tb, $campo, $dado, $i, $id, $data, $erro, $action) { 96 | $form1 = formTop($tb, $field); 97 | $form2 = formFields($tb, $field, $i, $action, $view_insert, $view_alter, $view_id); 98 | 99 | print " 100 | 110 | "; 111 | } 112 | 113 | function formInsertDados($tb, $field) { 114 | $form1 = formTop($tb, $field); 115 | $form2 = formFields($tb, $field, $i, $action, $view_insert, $view_alter, $view_id); 116 | 117 | print " "; 118 | 119 | for($i=0; $i < count($field); $i++) { 120 | // if($field[$i] == 'id') 121 | // print""; 122 | //else 123 | if($field[$i] != 'id') 124 | print " 125 | 131 | "; 132 | } 133 | 134 | print " 135 | 136 | 137 | 140 | 141 | 142 | "; 143 | } 144 | 145 | function poweredby() { 146 | print"
147 |

148 | netactuator by Rogério Carvalho Schneider
149 | Interface Web by Lucas Schneider 150 |

151 | "; 152 | } 153 | ?> 154 | -------------------------------------------------------------------------------- /defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // *** DEFINES *** 21 | 22 | #define MAX_TAM_LINHA 5000 23 | #define MAX_ARGS 128 24 | 25 | // Intervalo entre cada leitura das configs do banco 26 | #define DELAY_LEITURA_CONFIGS 20 27 | // Intervalo entre cada verificação de hora para update do pattern 28 | #define DELAY_UPDATE 60 29 | // Pausa entre uma verificação de expire time de host bloqueado e outra 30 | #define DELAY_EXPIRE 40 31 | // Intervalo entre iterações do laço principal 32 | // 2 s = 20 = ds = 200 cs = 2000 ms = 20000 = ?s = 200000 ?s = 2000000 us -> Usando 20 ms = 20000 us 33 | #define DELAY_MAIN 20000 34 | 35 | // Flags dos registros limpos e sujos do DB (ok e comprometidos) 36 | #define FLAG_CLEAN 1 37 | #define FLAG_DIRTY 0 38 | 39 | // Número de tentativas de conexão com o MySQL antes de desistir 40 | #define NUM_DB_TRY 5 41 | 42 | // Tabelas 43 | #define ADMIN_T "config_admincontacts" 44 | #define INTERFACES_T "config_interfaces" 45 | #define netactuator_T "config_netactuator" 46 | #define NETWORKS_T "config_networks" 47 | 48 | #define BLACKLIST_T "net_blacklist" 49 | #define TOPUSERS_T "net_topusers" 50 | #define WHITELIST_T "net_whitelist" 51 | 52 | #define MASS_T "storage_mass" 53 | #define PATTERN_T "storage_pattern_def" 54 | 55 | #define EVENTOS_T "storage_eventos" 56 | 57 | // *** FIM DEFINES *** 58 | 59 | 60 | // *** GLOBAIS *** 61 | 62 | typedef char tipostring[MAX_TAM_LINHA]; 63 | time_t ini, end; // marcadores de tempo de execucao 64 | long count_log=0; // contador de registros nos logs, com repeticao 65 | 66 | 67 | // Árvore 68 | struct TreeNode; 69 | typedef struct TreeNode *SearchTree; 70 | 71 | struct TreeNode 72 | { 73 | tipostring info; 74 | long recv_f; 75 | long sent_f; 76 | long recv_b; 77 | long sent_b; 78 | long convs_as_source; 79 | long convs_as_destin; 80 | tipostring iface; 81 | SearchTree esq; 82 | SearchTree dir; 83 | }; 84 | 85 | SearchTree raiz=NULL; 86 | 87 | 88 | // Lista 89 | struct ListNode; 90 | typedef struct ListNode *SeqList; 91 | 92 | struct ListNode 93 | { 94 | tipostring info; 95 | long recv_f; 96 | long sent_f; 97 | long recv_b; 98 | long sent_b; 99 | long convs_as_source; 100 | long convs_as_destin; 101 | tipostring iface; 102 | SeqList p; 103 | }; 104 | 105 | SeqList top_users_frames_recv=NULL; 106 | SeqList top_users_frames_sent=NULL; 107 | SeqList top_users_bytes_recv=NULL; 108 | SeqList top_users_bytes_sent=NULL; 109 | SeqList top_users_convs_as_source=NULL; 110 | SeqList top_users_convs_as_destin=NULL; 111 | 112 | 113 | // Gaph Thread 114 | struct graph_data; 115 | typedef struct graph_data graph_t; 116 | struct graph_data 117 | { 118 | tipostring info; 119 | long recv_f; 120 | long sent_f; 121 | long recv_b; 122 | long sent_b; 123 | long convs_as_source; 124 | long convs_as_destin; 125 | tipostring iface; 126 | long baseline; 127 | }; 128 | 129 | 130 | // Configurações 131 | int flag_loading_config=1; // inicia carregando configurações 132 | int flag_limit_update=0; // bloqueia geração de gráficos durante o limit (update rrd, evita acessos múltiplos aos rrds) 133 | 134 | tipostring interfaces[MAX_ARGS]; 135 | int num_interfaces=0; 136 | 137 | tipostring networks[MAX_ARGS][2]; // campo 0 = rede, campo 1 = máscara 138 | int num_networks=0; 139 | unsigned long networks_ranges[MAX_ARGS][3]; // campo 0 = ip_inicial, campo 1 = ip_final, campo 2 = maskbits (inseridos somente na função netmask_paul_davis()) 140 | 141 | int flow_capture_time_min=0; 142 | int flow_capture_time_sec=0; 143 | 144 | //int graph_update_time_min=45; // minutos, colocar no banco 145 | int graph_update_time_min=5; // minutos, colocar no banco 146 | 147 | tipostring blacklist[MAX_ARGS]; 148 | int num_blacklist=0; 149 | 150 | tipostring whitelist[MAX_ARGS]; 151 | int num_whitelist=0; 152 | 153 | tipostring admin_contacts[MAX_ARGS]; 154 | int num_admin_contacts=0; 155 | 156 | tipostring pmacctd_bin; 157 | tipostring pmacct_bin; 158 | 159 | tipostring fire_bin; 160 | 161 | int top_users=0; 162 | 163 | tipostring base_www; 164 | 165 | int block_time_min=0; 166 | 167 | int days_to_keep=0; 168 | 169 | int days_to_learn=0; 170 | 171 | float threshold=0; 172 | 173 | int flag_block_hosts=0; 174 | 175 | int flag_send_email=0; 176 | 177 | 178 | // Firewall 179 | int is_ipfw=0; 180 | int is_iptables=0; 181 | 182 | 183 | // Database 184 | tipostring db_host; 185 | tipostring db_user; 186 | tipostring db_password; 187 | tipostring db_name; 188 | 189 | 190 | // Datetime 191 | time_t data_hora_global; // Usado para fazer update com valor global nos RRDs 192 | tipostring data; 193 | tipostring hora; 194 | tipostring week_day; // se usar int vai dar erro ao atribuir o dia da semana a partir da struct sdata em netactuator.c 195 | 196 | // *** FIM GLOBAIS *** 197 | -------------------------------------------------------------------------------- /action.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Verifica se um IP está na lista de whitelisteds ou não 21 | int is_whitelisted (tipostring info) 22 | { 23 | int i; 24 | 25 | 26 | for(i=0; iinfo)) 52 | { 53 | strcpy(mail_temp_file, "/tmp/netactuator_mail_temp_file.txt"); 54 | 55 | for(i=0; iinfo, comeca->convs_as_source); 60 | fprintf(mail_handler, "Baseline: %ld\n", baseline); 61 | fprintf(mail_handler, "Limite: %.0f\n\n", baseline * threshold); 62 | fclose(mail_handler); 63 | printf("Mandando mail para %s\n", admin_contacts[i]); 64 | sprintf(comando, "mail -s 'netactuator - Alerta Host \"%s\"' %s < %s", comeca->info, admin_contacts[i], mail_temp_file); 65 | if (flag_send_email) 66 | system(comando); 67 | } 68 | } 69 | } 70 | // else 71 | // { 72 | // printf("Nada a ser feito, IP %s pertence à WhiteList\n", comeca->info); 73 | // } 74 | 75 | printf("\n"); 76 | fflush(stdout); 77 | } 78 | 79 | 80 | // Aplica a regra de firewall ao host detectado como intruso 81 | int bloquear_host (tipostring info, int expire) 82 | { 83 | FILE *in_handler; 84 | tipostring comando; 85 | tipostring linha; 86 | int flag_bloqueado=0; 87 | 88 | 89 | // printf("Aplicando regra de firewall...\n"); 90 | 91 | // Se não for whitelisted 92 | if (!is_whitelisted(info)) 93 | { 94 | if (is_ipfw) 95 | sprintf(comando, "%s list | grep \"deny ip from %s to any\"", fire_bin, info); 96 | else if (is_iptables) 97 | sprintf(comando, "%s -L -n -t filter | grep %s | grep DROP", fire_bin, info); 98 | 99 | in_handler = rpopen(comando, "r"); 100 | if (in_handler) 101 | { 102 | while (fgets(linha, MAX_TAM_LINHA, in_handler)) // Se tiver entradas para este IP em deny, não bloqueia novamente 103 | flag_bloqueado = 1; 104 | pclose(in_handler); 105 | } 106 | 107 | if (!flag_bloqueado) 108 | { 109 | if (is_ipfw) 110 | sprintf(comando, "%s add deny ip from %s to any", fire_bin, info); 111 | else if (is_iptables) 112 | sprintf(comando, "%s -I INPUT -t filter -s %s -j DROP", fire_bin, info); 113 | 114 | printf("Bloqueando host: %s\n", info); 115 | if (flag_block_hosts) 116 | system(comando); 117 | inserir_blacklist(info, expire); 118 | 119 | fflush(stdout); 120 | return 1; 121 | } 122 | } 123 | // else 124 | // { 125 | // printf("Nada a ser feito, IP %s pertence à WhiteList\n", info); 126 | // } 127 | 128 | return 0; 129 | } 130 | 131 | 132 | // Aplica a regra de liberação no firewall 133 | void desbloquear_host (tipostring info) 134 | { 135 | FILE *in_handler; 136 | tipostring comando; 137 | tipostring linha; 138 | int flag_bloqueado=0; 139 | 140 | 141 | // printf("Aplicando regra de liberação de firewall...\n"); 142 | 143 | if (is_ipfw) 144 | sprintf(comando, "%s list | grep \"deny ip from %s to any\"", fire_bin, info); 145 | else if (is_iptables) 146 | sprintf(comando, "%s -L -n -t filter | grep %s | grep DROP", fire_bin, info); 147 | 148 | in_handler = rpopen(comando, "r"); 149 | if (in_handler) 150 | { 151 | while (fgets(linha, MAX_TAM_LINHA, in_handler)) // Se tiver entradas para este IP em deny, não bloqueia novamente 152 | flag_bloqueado = 1; 153 | pclose(in_handler); 154 | } 155 | 156 | if (flag_bloqueado) 157 | { 158 | if (is_ipfw) 159 | sprintf(comando, "%s delete $(%s list | grep \"deny ip from %s to any\" | awk '{print $1}')", fire_bin, fire_bin, info); 160 | else if (is_iptables) 161 | sprintf(comando, "%s -D INPUT -t filter -s %s -j DROP", fire_bin, info); 162 | 163 | printf("Liberando host: %s\n", info); 164 | if (flag_block_hosts) 165 | system(comando); 166 | fflush(stdout); 167 | } 168 | 169 | remover_blacklist(info); 170 | fflush(stdout); 171 | } 172 | -------------------------------------------------------------------------------- /datastruct.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // *** BIN PESQ *** 21 | 22 | // Insere um novo nodo na arvore 23 | SearchTree inserir_nodo_arvore (SearchTree comeca, SearchTree novo_nodo, SearchTree volta) // ok -> recursiva 24 | { 25 | if (comeca) // se nao chegou ao final (ainda !NULL) 26 | { 27 | // jah existe - retorna nodo encontrado 28 | if (!strcmp(comeca->info, novo_nodo->info)) 29 | return comeca; 30 | 31 | // se for maior, insere na direita 32 | else if (strcmp(comeca->info, novo_nodo->info) < 0) // se anterior menor, vai para a direita 33 | { 34 | if (!comeca->dir) // se vago, insere 35 | { 36 | comeca->dir = novo_nodo; 37 | return NULL; 38 | } 39 | else // senao, procura outro 40 | volta = inserir_nodo_arvore(comeca->dir, novo_nodo, volta); 41 | } 42 | 43 | // se for menor, insere na esquerda 44 | else if (strcmp(comeca->info, novo_nodo->info) > 0) // se anterior maior, vai para a esquerda 45 | { 46 | if (!comeca->esq) // se vago, insere 47 | { 48 | comeca->esq = novo_nodo; 49 | return NULL; 50 | } 51 | else // senao, procura proximo 52 | volta = inserir_nodo_arvore(comeca->esq, novo_nodo, volta); 53 | } 54 | } 55 | 56 | return volta; 57 | } 58 | 59 | 60 | // Mostra todos os registros cadastrados 61 | void mostrar_registros_arvore (SearchTree comeca) 62 | { 63 | if (comeca) 64 | { 65 | mostrar_registros_arvore(comeca->dir); 66 | mostrar_registros_arvore(comeca->esq); 67 | 68 | printf("IP: %s ->", comeca->info); 69 | printf(" Recv Frames: %ld", comeca->recv_f); 70 | printf(" Recv Bytes: %ld", comeca->recv_b); 71 | printf(" Sent Frames: %ld", comeca->sent_f); 72 | printf(" Sent Bytes: %ld", comeca->sent_b); 73 | printf(" Source: %ld", comeca->convs_as_source); 74 | printf(" Destino: %ld", comeca->convs_as_destin); 75 | printf(" Iface: %s", comeca->iface); 76 | printf("\n"); 77 | } 78 | } 79 | 80 | 81 | // Destroi a arvore para liberar memoria 82 | void destruir_arvore (SearchTree comeca) 83 | { 84 | if (comeca) 85 | { 86 | destruir_arvore(comeca->dir); 87 | destruir_arvore(comeca->esq); 88 | free(comeca); 89 | } 90 | } 91 | 92 | 93 | // Contador de registros inseridos, sem repeticao 94 | long contar_registros_arvore (SearchTree comeca, long count) 95 | { 96 | if (comeca) 97 | { 98 | count = contar_registros_arvore(comeca->dir, count); 99 | count = contar_registros_arvore(comeca->esq, count); 100 | ++count; 101 | } 102 | 103 | return count; 104 | } 105 | 106 | // *** FIM BIN PESQ *** 107 | 108 | 109 | 110 | // *** LISTA *** 111 | 112 | // Cria as listas de top users com top_users nodos alocados 113 | SeqList criar_lista (int nodos) 114 | { 115 | SeqList list=NULL; 116 | SeqList atual=NULL; 117 | int i; 118 | 119 | 120 | // Cria o primeiro nodo da lista 121 | if (!(list = (SeqList) malloc(sizeof(struct ListNode)))) 122 | { 123 | printf("Sem memoria para continuar.\n"); 124 | exit(1); 125 | } 126 | strcpy(list->info, "vago"); 127 | list->recv_f = 0; 128 | list->recv_b = 0; 129 | list->sent_f = 0; 130 | list->sent_b = 0; 131 | list->convs_as_source = 0; 132 | list->convs_as_destin = 0; 133 | strcpy(list->iface, ""); 134 | list->p = NULL; 135 | 136 | // Cria os nodos seguintes da lista 137 | for(i=0; ip) 142 | atual = atual->p; 143 | 144 | if (!(atual->p = (SeqList) malloc(sizeof(struct ListNode)))) 145 | { 146 | printf("Sem memoria para continuar.\n"); 147 | exit(1); 148 | } 149 | strcpy(atual->p->info, "vago"); 150 | atual->p->recv_f = 0; 151 | atual->p->recv_b = 0; 152 | atual->p->sent_f = 0; 153 | atual->p->sent_b = 0; 154 | atual->p->convs_as_source = 0; 155 | atual->p->convs_as_destin = 0; 156 | strcpy(atual->iface, ""); 157 | atual->p->p = NULL; 158 | } 159 | 160 | return list; 161 | } 162 | 163 | 164 | // Mostra todos os registros cadastrados 165 | void mostrar_registros_lista (SeqList comeca) 166 | { 167 | if (comeca) 168 | { 169 | mostrar_registros_lista(comeca->p); 170 | 171 | printf("IP: %s ->", comeca->info); 172 | printf(" Recv Frames: %ld", comeca->recv_f); 173 | printf(" Recv Bytes: %ld", comeca->recv_b); 174 | printf(" Sent Frames: %ld", comeca->sent_f); 175 | printf(" Sent Bytes: %ld", comeca->sent_b); 176 | printf(" Source: %ld", comeca->convs_as_source); 177 | printf(" Destino: %ld", comeca->convs_as_destin); 178 | printf(" Iface: %s", comeca->iface); 179 | printf("\n"); 180 | } 181 | } 182 | 183 | 184 | // Destroi a lista para liberar memoria 185 | void destruir_lista (SeqList comeca) 186 | { 187 | if (comeca) 188 | { 189 | destruir_lista(comeca->p); 190 | free(comeca); 191 | } 192 | } 193 | 194 | // *** FIM LISTA *** 195 | -------------------------------------------------------------------------------- /web/include/functions.php: -------------------------------------------------------------------------------- 1 | '0') 14 | return true; 15 | //print "1"; 16 | else { 17 | $sql = "SELECT * FROM config_tables WHERE table_name='".$row[0]."'"; 18 | $res = mysql_query($sql); 19 | 20 | if (mysql_num_rows($res)=='0') 21 | return true; 22 | else 23 | return false; 24 | } 25 | } 26 | 27 | function getDados($tb, $field, $j, $view_delete, $view_alter, $view_id, $dados) { 28 | global $tb, $field, $j, $view_delete, $view_alter, $view_id, $dados; 29 | $sql = "SELECT * FROM ".$tb.""; 30 | $res = mysql_query($sql); 31 | 32 | if($tb != 'config_tables'){ 33 | 34 | while ($dados = mysql_fetch_array($res)) { 35 | print""; 36 | for($j=0; $j < count($dados); $j++) { 37 | if($field[$j] == 'id') { 38 | if($view_id == '1') { 39 | print ""; 40 | } 41 | } else { 42 | if($view_alter == '1') { 43 | print ""; 44 | } else { 45 | if($tb == 'net_topusers' && $field[$j] == 'host') // host com link 46 | print ""; 47 | else 48 | print ""; 49 | } 50 | } 51 | } 52 | if($view_delete=='1') 53 | print ""; 54 | print""; 55 | } 56 | 57 | } else { 58 | print ""; 59 | while ($dados = mysql_fetch_array($res)) { 60 | print""; 61 | for($j=0; $j < count($dados); $j++) { 62 | if($field[$j] != 'id') 63 | print ""; 64 | } 65 | print ""; 66 | print""; 67 | } 68 | } 69 | } 70 | 71 | function updateDados($tb, $campo, $dado, $j, $id, $data, $connect, $erro) { 72 | if(isset($_POST['data']) && ($_POST['data'] != '')) { 73 | $sql = "UPDATE $tb SET $campo='".$_POST['data']."' WHERE id='$id'"; 74 | $update = mysql_query($sql); 75 | echo "table $tb
campo $campo
dado $dado
data: $data
id $id
$sql"; 76 | $action=''; 77 | $erro = " $campo alterado com sucesso!"; 78 | header('location:main.php?tb='.$tb.'&action=list'); 79 | } 80 | } 81 | 82 | function insertDados($tb, $field) { 83 | //$exec='1'; 84 | for($i=0; $i < count($field); $i++) { 85 | if (!empty($_POST[$field[$i]])) { 86 | $exec='1'; 87 | if($field[$i] != 'id'){ 88 | if($i > 0) { 89 | if($i==1) { 90 | $SQL_fields = $field[$i]; 91 | $SQL_dados = "'".$_POST[$field[$i]]."'"; 92 | } else { 93 | $SQL_fields = "$SQL_fields, ".$field[$i].""; 94 | $SQL_dados = "$SQL_dados, '".$_POST[$field[$i]]."'"; 95 | } 96 | } else 97 | $sql2 = $field[$i]; 98 | } 99 | } elseif (empty($_POST[$field[$i]])) { 100 | $exec = '0'; 101 | } 102 | } 103 | if($exec=='1'){ 104 | $sql = "INSERT INTO $tb ($SQL_fields) VALUES($SQL_dados);"; 105 | $update = mysql_query($sql); 106 | header('location:main.php?tb='.$tb.''); 107 | } elseif($exec=='0') { 108 | print "Todos os campos devem ser preenchidos."; 109 | } 110 | } 111 | 112 | function deleteDados($tb, $dado) { 113 | if($_GET['id']) { 114 | $sql = "DELETE FROM $tb WHERE id='".$_GET['id']."';"; 115 | $query = mysql_query($sql); 116 | } else 117 | echo("Erro. Valor não setado!"); 118 | } 119 | 120 | function mysql_fetch_all($result) { 121 | while($row=mysql_fetch_array($result)) { 122 | $return[] = $row; 123 | } 124 | return $return; 125 | } 126 | 127 | function getHostGraphics($dados) { 128 | $sql = "SELECT host FROM storage_pattern_def"; 129 | $res = mysql_query($sql); 130 | $max = mysql_num_rows($res); 131 | 132 | for($i=0;$i < $max; $i++) { 133 | list($dados) = mysql_fetch_row($res); 134 | if(file_exists("graph/".$dados."_".$time."_day.png")) 135 | print "
".$dados."
"; 136 | if(!file_exists("graph/".$dados."_".$time."_day.png")) 137 | print "".$dados." (Arquivo não encontrado)
"; 138 | } 139 | } 140 | 141 | function checkConfigTables($row) { 142 | global $description; 143 | $sql = "SELECT table_name, delete_view, id_view, insert_view, description FROM config_tables WHERE table_name = '".$row[0]."';"; 144 | $res=mysql_query($sql); 145 | $max=mysql_num_rows($res); 146 | 147 | if($max=='0') 148 | $description = $row[0]; 149 | elseif($res){ 150 | for($j=0; $j<$max; $j++) { 151 | list($tb_name, $delelte_view, $id_view, $insert_view, $description) = mysql_fetch_row($res); 152 | } 153 | } 154 | } 155 | 156 | function views($tb, $view_insert, $view_delete, $view_id, $view_alter) { 157 | global $view_insert, $view_delete, $view_id, $view_alter, $view_table; 158 | $sql = "SELECT id_view, insert_view, delete_view, table_view, alter_view FROM config_tables WHERE table_name='".$tb."' AND table_name != 'config_tables'"; 159 | $res = mysql_query($sql); 160 | 161 | while ($views = mysql_fetch_array($res)) { 162 | for($j=0; $j < 5; $j++) { 163 | $id_insert = $views[0]; 164 | $view_insert = $views[1]; 165 | $view_delete = $views[2]; 166 | $view_table = $views[3]; 167 | $view_alter = $views[4]; 168 | } 169 | } 170 | } 171 | ?> 172 | -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | Passos a serem executados para a compilação e instalação do netactuator. 2 | 3 | ############################################################################ 4 | # FreeBSD # 5 | ############################################################################ 6 | 7 | # MySQL 5 (binários e headers) 8 | cd /usr/ports/databases/mysql50-client 9 | make install 10 | cd /usr/ports/databases/mysql50-server 11 | make install 12 | cd /usr/ports/databases/mysql50-scripts 13 | make install 14 | 15 | # Apache 1 ou 2 16 | cd /usr/ports/www/apache{13,20,21,22} 17 | make install 18 | 19 | # PHP 4 ou PHP 5 20 | cd /usr/ports/lang/php{4,5} 21 | make install 22 | 23 | # PHP com suporte a MySQL 24 | cd /usr/ports/databases/php{4,5}-mysql 25 | make install 26 | 27 | # pmacct 28 | cd /usr/ports/net-mgmt/pmacct 29 | make install 30 | 31 | # RRDTool (binários e headers) 32 | cd /usr/ports/net/rrdtool 33 | make install 34 | 35 | Depois destes passos o netactuator pode ser compilado e instalado no sistema. 36 | 37 | ############################################################################ 38 | # FreeBSD # 39 | ############################################################################ 40 | 41 | 42 | ############################################################################ 43 | # Fedora # 44 | ############################################################################ 45 | 46 | # Apache 47 | yum -y install httpd 48 | 49 | # PHP 5 50 | yum -y install php 51 | 52 | # MySQL 5 53 | yum -y install mysql-server 54 | yum -y install mysql mysql-devel mysql-libs 55 | 56 | # RRD 57 | yum -y install rrdtool rrdtool-devel 58 | 59 | # LIBPCAP Headers 60 | yum -y install libpcap-devel 61 | 62 | # pmacct 63 | http://www.pmacct.net/ 64 | pmacct-0.11.5.tar.gz ou mais novo 65 | 66 | wget http://www.pmacct.net/pmacct-0.11.5.tar.gz 67 | tar xzvf pmacct-0.11.5.tar.gz 68 | cd pmacct-0.11.5 69 | ./configure 70 | make 71 | make install 72 | 73 | A versão mencionada já se encontra em 'misc'. 74 | 75 | Depois destes passos o netactuator pode ser compilado e instalado no sistema. 76 | 77 | ############################################################################ 78 | # Fedora # 79 | ############################################################################ 80 | 81 | 82 | ############################################################################ 83 | # Ubuntu / Debian # 84 | ############################################################################ 85 | 86 | # MySQL 5 (binários) 87 | apt-get install mysql-client 88 | apt-get install mysql-server 89 | apt-get install mysql-common 90 | 91 | # MySQL 5 (headers) 92 | apt-get install libmysqlclient16-dev (mysql.h e mysql_config) 93 | 94 | # Apache 2 95 | apt-get install apache 96 | 97 | # PHP 4 ou PHP 5 98 | apt-get install php{4,5} 99 | 100 | # PHP com suporte a MySQL 101 | apt-get install php{4,5}-mysql 102 | 103 | # pmacct 104 | apt-get install pmacct 105 | 106 | # RRDTool (binários) 107 | apt-get install rrdtool 108 | 109 | # RRDTool (headers) 110 | apt-get install librrd2 111 | apt-get install librrd2-dev 112 | 113 | Depois destes passos o netactuator pode ser compilado e instalado no sistema. 114 | 115 | ############################################################################ 116 | # Ubuntu / Debian # 117 | ############################################################################ 118 | 119 | 120 | ############################################################################ 121 | # SuSE # 122 | ############################################################################ 123 | 124 | Fazer o download de: 125 | 126 | # Mysql 5.0 Client: 127 | wget http://dev.mysql.com/get/Downloads/MySQL-5.0/MySQL-client-standard-5.0.26-0.sles9.i586.rpm/from/http://www.linorg.usp.br/mysql/ 128 | # MySql 5.0 Server: 129 | wget http://dev.mysql.com/get/Downloads/MySQL-5.0/MySQL-server-standard-5.0.26-0.sles9.i586.rpm/from/http://www.linorg.usp.br/mysql/ 130 | # MySql 5.0 - Headers and libraries: 131 | wget http://dev.mysql.com/get/Downloads/MySQL-5.0/MySQL-devel-standard-5.0.26-0.sles9.i586.rpm/from/http://www.linorg.usp.br/mysql/ 132 | 133 | # Instalar os programas baixados: 134 | rpm -ivh MySQL-server-standard-5.0.26-0.sles9.i586.rpm MySQL-client-standard-5.0.26-0.sles9.i586.rpm MySQL-devel-standard-5.0.26-0.sles9.i586.rpm 135 | 136 | Instalar pelo YAST: 137 | - Apache 2 138 | - Php 5 139 | - Php 5 MySQL 140 | - RRDTool 1.2.11 141 | 142 | # Instalar o pmacct: 143 | wget ftp://ftp.suntel.com.tr/pub/repo/monitoring/SUSE_Factory/i586/pmacct-0.11.0-15.1.i586.rpm 144 | rpm -ivh pmacct-0.11.0-15.1.i586.rpm 145 | 146 | Depois destes passos o netactuator pode ser compilado e instalado no sistema. 147 | 148 | ############################################################################ 149 | # SuSE # 150 | ############################################################################ 151 | 152 | 153 | ############################################################################ 154 | # Para todos os sistemas # 155 | ############################################################################ 156 | 157 | # tar xzvf netactuator.tar.gz 158 | # cd netactuator 159 | # make all 160 | # make instalar 161 | 162 | **************************************************************************** 163 | 164 | - Ajuste as configurações de netactuator.conf: 165 | # cp /usr/local/etc/netactuator/netactuator.conf-dist /usr/local/etc/netactuator/netactuator.conf 166 | 167 | - Utilize o script de inicialização do banco de dados para começar a usar o netactuator: 168 | # mysql < sql/netactuator-mysql.sql 169 | 170 | - Ajuste o seu httpd.conf: 171 | Alias /netactuator /usr/local/netactuator/web 172 | 173 | AddDefaultCharset ISO-8859-1 174 | Options None 175 | AllowOverride None 176 | Order deny,allow 177 | Allow from all 178 | 179 | - Ou utilize o arquivo fornecido: 180 | # cp netactuator-apache.conf-dist /etc/httpd/conf.d/netactuator-apache.conf 181 | 182 | - Altere os seguintes parâmetros no php.ini: 183 | output_buffering = On 184 | variables_order = "EGPCS" 185 | register_globals = On 186 | session.auto_start = 1 187 | 188 | - Utilize o script de start/stop/status do netactuator: 189 | # ./scripts/netactuator.sh 190 | 191 | **************************************************************************** 192 | 193 | ############################################################################ 194 | # Para todos os sistemas # 195 | ############################################################################ 196 | 197 | 198 | netactuator on Google Code: 199 | http://netactuator.googlecode.com 200 | 201 | netactuator on Github: 202 | https://github.com/stockrt/netactuator 203 | 204 | Author: Rogério Carvalho Schneider (stockrt@gmail.com) 205 | http://stockrt.github.com 206 | 207 | Web Interface: Lucas Schneider (scorfell@gmail.com) 208 | -------------------------------------------------------------------------------- /limit.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Checa se algum host ultrapassou os limites estabelecidos e atua 21 | void checar_limites (SearchTree comeca) 22 | { 23 | MYSQL_RES *res=NULL; 24 | MYSQL_ROW row; 25 | 26 | long avg_conv_host=0; 27 | long max_conv_host=0; 28 | int flag_prosseguir=0; 29 | 30 | tipostring query; 31 | graph_t graph; 32 | pthread_t thread; 33 | 34 | 35 | if (comeca) 36 | { 37 | checar_limites(comeca->dir); 38 | checar_limites(comeca->esq); 39 | 40 | // Verificar se já consta entrada em pattern_def, para poder prosseguir com a avaliação 41 | // Só terá entrada registrada em pattern_def caso já tenha atingido um valor mínimo de registros 42 | sprintf(query, "SELECT host FROM %s WHERE host = '%s';", PATTERN_T, comeca->info); 43 | res = sql(query, mysql_conn_global); 44 | 45 | if ((row = mysql_fetch_row(res))) 46 | flag_prosseguir = 1; 47 | mysql_free_result(res); 48 | 49 | // Se tiver cadastro de pattern, continua, senão insere como clean em mass 50 | if (flag_prosseguir) 51 | { 52 | // Pega valor definido no banco 53 | sprintf(query, "SELECT convs_as_source_avg,convs_as_source_max FROM %s WHERE host = '%s';", PATTERN_T, comeca->info); 54 | res = sql(query, mysql_conn_global); 55 | 56 | if ((row = mysql_fetch_row(res))) 57 | { 58 | if (row[0] != NULL) 59 | avg_conv_host = atol(row[0]); 60 | if (row[1] != NULL) 61 | max_conv_host = atol(row[1]); 62 | } 63 | mysql_free_result(res); 64 | 65 | //printf("Host %s avg: %ld\n", comeca->info, avg_conv_host); 66 | //printf("Host %s max: %ld\n", comeca->info, max_conv_host); 67 | 68 | // Somente executa se tiver algum valor registrado para o host como origem 69 | // Evita avaliar hosts que tenham entradas suficientes mas que sejam apenas como destino, sem valores de convs como origem, gerando valor nulo ou zero 70 | // Esta situação não vai ocorrer por conta do insert into com select convs_as_source > 0 71 | if (avg_conv_host > 0) 72 | { 73 | // Se for maior do que o limite especificado 74 | // DIRTY 75 | if (comeca->convs_as_source > (avg_conv_host * threshold)) 76 | { 77 | sprintf(query, "INSERT INTO %s VALUES ('%s', '%ld', '%ld', '%ld', '%ld', '%ld', '%ld', '%s', '%s', '%s', '%d', '%d', '%s');", 78 | MASS_T, comeca->info, comeca->convs_as_source, comeca->convs_as_destin, comeca->recv_f, comeca->sent_f, comeca->recv_b, comeca->sent_b, data, hora, week_day, flow_capture_time_min, FLAG_DIRTY, comeca->iface); 79 | sql(query, mysql_conn_global); 80 | 81 | /* 82 | printf("IP: %s ->", comeca->info); 83 | printf(" Recv Frames: %ld", comeca->recv_f); 84 | printf(" Recv Bytes: %ld", comeca->recv_b); 85 | printf(" Sent Frames: %ld", comeca-> sent_f); 86 | printf(" Sent Bytes: %ld", comeca->sent_b); 87 | printf(" Source: %ld", comeca->convs_as_source); 88 | printf(" Destino: %ld", comeca->convs_as_destin); 89 | printf("\n"); 90 | */ 91 | 92 | // Atuação 93 | if (bloquear_host(comeca->info, 1)) 94 | { 95 | // Somente registra evento e avisa por mail, caso ainda não esteja bloqueado 96 | registrar_evento(comeca->info, comeca->convs_as_source, avg_conv_host, "Bloqueado"); 97 | avisar_contatos_adm(comeca, avg_conv_host); 98 | } 99 | } 100 | // CLEAN 101 | else 102 | { 103 | sprintf(query, "INSERT INTO %s VALUES ('%s', '%ld', '%ld', '%ld', '%ld', '%ld', '%ld', '%s', '%s', '%s', '%d', '%d', '%s');", 104 | MASS_T, comeca->info, comeca->convs_as_source, comeca->convs_as_destin, comeca->recv_f, comeca->sent_f, comeca->recv_b, comeca->sent_b, data, hora, week_day, flow_capture_time_min, FLAG_CLEAN, comeca->iface); 105 | sql(query, mysql_conn_global); 106 | } 107 | 108 | /* 109 | // Desativado temporariamente 110 | if (comeca->convs_as_destin > max_convs_as_destin) 111 | { 112 | printf("IP: %s ->", comeca->info); 113 | printf(" Recv Frames: %ld", comeca->recv_f); 114 | printf(" Recv Bytes: %ld", comeca->recv_b); 115 | printf(" Sent Frames: %ld", comeca-> sent_f); 116 | printf(" Sent Bytes: %ld", comeca->sent_b); 117 | printf(" Source: %ld", comeca->convs_as_source); 118 | printf(" Destino: %ld", comeca->convs_as_destin); 119 | printf("\n"); 120 | } 121 | */ 122 | } // if avg_conv_host > 0 123 | } // if flag_prosseguir (cadastrado em pattern) 124 | else 125 | { 126 | // Este seria o caso das primeiras inserções do host no banco, insere clean. 127 | sprintf(query, "INSERT INTO %s VALUES ('%s', '%ld', '%ld', '%ld', '%ld', '%ld', '%ld', '%s', '%s', '%s', '%d', '%d', '%s');", 128 | MASS_T, comeca->info, comeca->convs_as_source, comeca->convs_as_destin, comeca->recv_f, comeca->sent_f, comeca->recv_b, comeca->sent_b, data, hora, week_day, flow_capture_time_min, FLAG_CLEAN, comeca->iface); 129 | sql(query, mysql_conn_global); 130 | } // else flag_prosseguir (cadastrado em pattern) 131 | 132 | 133 | // Cria gráficos com RRDTools para qualquer IP capturado que esteja cadastrado em NETWORKS_T 134 | strcpy(graph.info, comeca->info); 135 | graph.recv_f = comeca->recv_f; 136 | graph.sent_f = comeca->sent_f; 137 | graph.recv_b = comeca->recv_b; 138 | graph.sent_b = comeca->sent_b; 139 | graph.convs_as_source = comeca->convs_as_source; 140 | graph.convs_as_destin = comeca->convs_as_destin; 141 | strcpy(graph.iface, comeca->iface); 142 | graph.baseline = avg_conv_host; 143 | 144 | // flag_copia_local_ok = 0; 145 | // pthread_create(&thread, NULL, (void *) &rrd_rog, (graph_t *) &graph); 146 | // // Aguarda a cópia local ser concluída pela thread para prosseguir. Aqui existe a perda de contexto da struct, no 147 | // // retorno da função, por isso a flag (wait_lock). 148 | rrd_rog(&graph); 149 | // while (!flag_copia_local_ok) 150 | // ; 151 | } // if (comeca) 152 | } 153 | -------------------------------------------------------------------------------- /sql/netactuator-mysql.sql: -------------------------------------------------------------------------------- 1 | USE mysql; 2 | 3 | -- Criação do usuário 4 | --REPLACE INTO user (host, user, password) VALUES ('%', 'netactuator', OLD_PASSWORD('netdbpass')); 5 | REPLACE INTO user (host, user, password) VALUES ('localhost', 'netactuator', OLD_PASSWORD('netdbpass')); 6 | 7 | -- Permissões de acesso do usuário 8 | --REPLACE INTO db (host, db, user, select_priv, insert_priv, update_priv, delete_priv, create_priv, drop_priv, index_priv) 9 | -- VALUES ( 10 | -- '%', 11 | -- 'netactuator', 12 | -- 'netactuator', 13 | -- 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y' 14 | --); 15 | REPLACE INTO db (host, db, user, select_priv, insert_priv, update_priv, delete_priv, create_priv, drop_priv, index_priv) 16 | VALUES ( 17 | 'localhost', 18 | 'netactuator', 19 | 'netactuator', 20 | 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y' 21 | ); 22 | 23 | -- Atualiza os privilégios dados 24 | FLUSH PRIVILEGES; 25 | 26 | -- Criação do banco de dados e conexão com o banco 27 | CREATE DATABASE IF NOT EXISTS netactuator; 28 | USE netactuator; 29 | 30 | -- Configurações da ferramenta 31 | DROP TABLE IF EXISTS config_netactuator; 32 | CREATE TABLE config_netactuator ( 33 | id INT UNSIGNED NOT NULL auto_increment, 34 | flow_capture_time_min INT UNSIGNED NOT NULL, 35 | pmacctd_bin TEXT NOT NULL, 36 | pmacct_bin TEXT NOT NULL, 37 | fire_bin TEXT NOT NULL, 38 | top_users INT UNSIGNED NOT NULL, 39 | base_www TEXT NOT NULL, 40 | block_time_min INT UNSIGNED NOT NULL, 41 | days_to_keep INT UNSIGNED NOT NULL, 42 | days_to_learn INT UNSIGNED NOT NULL, 43 | threshold INT UNSIGNED NOT NULL, 44 | flag_block_hosts INT UNSIGNED NOT NULL, 45 | flag_send_email INT UNSIGNED NOT NULL, 46 | PRIMARY KEY (id) 47 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 48 | --INSERT INTO config_netactuator VALUES ('', 5, '/usr/local/sbin/pmacctd', '/usr/local/bin/pmacct', '/sbin/ipfw', 15, '/usr/local/netactuator/web', 30, 90, 7, 300, 0, 0); 49 | INSERT INTO config_netactuator VALUES ('', 5, '/usr/local/sbin/pmacctd', '/usr/local/bin/pmacct', '/sbin/iptables', 15, '/usr/local/netactuator/web', 30, 90, 7, 300, 0, 0); 50 | 51 | -- Configuração das interfaces de rede a serem monitoradas 52 | DROP TABLE IF EXISTS config_interfaces; 53 | CREATE TABLE config_interfaces ( 54 | id INT UNSIGNED NOT NULL auto_increment, 55 | interface VARCHAR(7) NOT NULL, 56 | PRIMARY KEY (id) 57 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 58 | INSERT INTO config_interfaces VALUES ('', 'eth0'); 59 | INSERT INTO config_interfaces VALUES ('', 'eth1'); 60 | INSERT INTO config_interfaces VALUES ('', 'xl0'); 61 | INSERT INTO config_interfaces VALUES ('', 'xl1'); 62 | INSERT INTO config_interfaces VALUES ('', 'fxp0'); 63 | INSERT INTO config_interfaces VALUES ('', 'fxp1'); 64 | INSERT INTO config_interfaces VALUES ('', 'vmnet1'); 65 | INSERT INTO config_interfaces VALUES ('', 'vmnet8'); 66 | INSERT INTO config_interfaces VALUES ('', 'lnc0'); 67 | INSERT INTO config_interfaces VALUES ('', 'lo'); 68 | 69 | -- Configuração das redes a serem avaliadas 70 | DROP TABLE IF EXISTS config_networks; 71 | CREATE TABLE config_networks ( 72 | id INT UNSIGNED NOT NULL auto_increment, 73 | network TEXT NOT NULL, 74 | PRIMARY KEY (id) 75 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 76 | INSERT INTO config_networks VALUES ('', '10.0.0.0/255.255.255.0'); 77 | INSERT INTO config_networks VALUES ('', '10.0.1.0/255.255.255.0'); 78 | INSERT INTO config_networks VALUES ('', '200.180.200.96/27'); 79 | INSERT INTO config_networks VALUES ('', '172.16.0.0/16'); 80 | INSERT INTO config_networks VALUES ('', '192.168.0.0/16'); 81 | INSERT INTO config_networks VALUES ('', '189.0.0.0/8'); 82 | INSERT INTO config_networks VALUES ('', '127.0.0.1/30'); 83 | 84 | -- Configuração dos contatos administrativos 85 | DROP TABLE IF EXISTS config_admincontacts; 86 | CREATE TABLE config_admincontacts ( 87 | id INT UNSIGNED NOT NULL auto_increment, 88 | contact TEXT NOT NULL, 89 | email TEXT NOT NULL, 90 | PRIMARY KEY (id) 91 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 92 | INSERT INTO config_admincontacts VALUES ('', 'Rogério Carvalho Schneider', 'stockrt@gmail.com'); 93 | 94 | -- IPs sempre liberados 95 | DROP TABLE IF EXISTS net_whitelist; 96 | CREATE TABLE net_whitelist ( 97 | id INT UNSIGNED NOT NULL auto_increment, 98 | host VARCHAR(15) NOT NULL, 99 | description TEXT NOT NULL, 100 | PRIMARY KEY (id) 101 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 102 | INSERT INTO net_whitelist VALUES ('', '200.180.200.125', 'stockrt'); 103 | INSERT INTO net_whitelist VALUES ('', '200.180.200.126', 'island'); 104 | 105 | -- IPs bloqueados 106 | DROP TABLE IF EXISTS net_blacklist; 107 | CREATE TABLE net_blacklist ( 108 | id INT UNSIGNED NOT NULL auto_increment, 109 | host VARCHAR(15) NOT NULL, 110 | time_bloqueio INT UNSIGNED NOT NULL, 111 | expire_time INT UNSIGNED NOT NULL, 112 | description TEXT NOT NULL, 113 | PRIMARY KEY (id) 114 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 115 | 116 | -- IPs com maior utilização de recurso 117 | DROP TABLE IF EXISTS net_topusers; 118 | CREATE TABLE net_topusers ( 119 | host VARCHAR(15) NOT NULL, 120 | convs_as_source INT UNSIGNED NOT NULL, 121 | convs_as_destin INT UNSIGNED NOT NULL, 122 | frames_in INT UNSIGNED NOT NULL, 123 | frames_out INT UNSIGNED NOT NULL, 124 | bytes_in INT UNSIGNED NOT NULL, 125 | bytes_out INT UNSIGNED NOT NULL, 126 | toptype ENUM('1', '2', '3', '4', '5', '6') NOT NULL 127 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 128 | # 1 - conversations_as_source 129 | # 2 - conversations_as_destin 130 | # 3 - frames_recv 131 | # 4 - frames_sent 132 | # 5 - bytes_recv 133 | # 6 - bytes_sent 134 | 135 | -- Armazenamento geral dos dados coletados 136 | DROP TABLE IF EXISTS storage_mass; 137 | CREATE TABLE storage_mass ( 138 | host VARCHAR(15) NOT NULL, 139 | convs_as_source INT UNSIGNED NOT NULL, 140 | convs_as_destin INT UNSIGNED NOT NULL, 141 | frames_in INT UNSIGNED NOT NULL, 142 | frames_out INT UNSIGNED NOT NULL, 143 | bytes_in INT UNSIGNED NOT NULL, 144 | bytes_out INT UNSIGNED NOT NULL, 145 | data DATE NOT NULL, 146 | hora TIME NOT NULL, 147 | week_day ENUM('0', '1', '2', '3', '4', '5', '6') NOT NULL, 148 | flow_capture_time_min TINYINT UNSIGNED NOT NULL, 149 | flag_clean TINYINT UNSIGNED NOT NULL, 150 | interface VARCHAR(5) NOT NULL 151 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 152 | 153 | -- Armazenamento dos padrões definidos 154 | DROP TABLE IF EXISTS storage_pattern_def; 155 | CREATE TABLE storage_pattern_def ( 156 | host VARCHAR(15) NOT NULL, 157 | convs_as_source_avg INT UNSIGNED NOT NULL, 158 | convs_as_source_max INT UNSIGNED NOT NULL, 159 | PRIMARY KEY (host) 160 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 161 | 162 | -- Armazenamento dos eventos ocorridos 163 | DROP TABLE IF EXISTS storage_eventos; 164 | CREATE TABLE storage_eventos ( 165 | host VARCHAR(15) NOT NULL, 166 | convs_as_source INT NOT NULL, 167 | baseline INT NOT NULL, 168 | data DATE NOT NULL, 169 | hora TIME NOT NULL, 170 | week_day ENUM('0', '1', '2', '3', '4', '5', '6') NOT NULL, 171 | description TEXT NOT NULL 172 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 173 | 174 | -- Configuração de visualizacão/alteração das tabelas pela interface gráfica 175 | DROP TABLE IF EXISTS config_tables; 176 | CREATE TABLE config_tables ( 177 | id INT UNSIGNED NOT NULL auto_increment, 178 | table_name VARCHAR(80) DEFAULT NULL, 179 | table_view INT NOT NULL, 180 | id_view INT NOT NULL, 181 | insert_view INT NOT NULL, 182 | delete_view INT NOT NULL, 183 | alter_view INT NOT NULL, 184 | description TEXT NOT NULL, 185 | PRIMARY KEY (id), 186 | UNIQUE KEY `table` (table_name) 187 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 188 | INSERT INTO config_tables VALUES ('', 'config_netactuator', 1, 0, 0, 0, 1, 'CONFIGURACOES'); 189 | INSERT INTO config_tables VALUES ('', 'config_interfaces', 1, 0, 1, 1, 1, 'INTERFACES'); 190 | INSERT INTO config_tables VALUES ('', 'config_networks', 1, 0, 1, 1, 1, 'NETWORKS'); 191 | INSERT INTO config_tables VALUES ('', 'config_admincontacts', 1, 0, 1, 1, 1, 'CONTATOS'); 192 | INSERT INTO config_tables VALUES ('', 'net_whitelist', 1, 0, 1, 1, 1, 'WHITELIST'); 193 | INSERT INTO config_tables VALUES ('', 'net_blacklist', 1, 0, 1, 1, 0, 'BLACKLIST'); 194 | INSERT INTO config_tables VALUES ('', 'net_topusers', 1, 0, 0, 0, 0, 'TOP USERS'); 195 | INSERT INTO config_tables VALUES ('', 'storage_mass', 0, 0, 0, 0, 0, 'STOR_MASS'); 196 | INSERT INTO config_tables VALUES ('', 'storage_pattern_def', 1, 0, 0, 0, 0, 'PADROES'); 197 | INSERT INTO config_tables VALUES ('', 'storage_eventos', 1, 0, 0, 0, 0, 'EVENTOS'); 198 | INSERT INTO config_tables VALUES ('', 'config_tables', 0, 0, 1, 1, 1, 'TABELAS'); 199 | 200 | -- Ajusta privilégios de acesso 201 | --GRANT ALL PRIVILEGES ON netactuator.* TO 'netactuator'@'%'; 202 | GRANT ALL PRIVILEGES ON netactuator.* TO 'netactuator'@'localhost'; 203 | 204 | -- Atualiza os privilégios concedidos 205 | FLUSH PRIVILEGES; 206 | -------------------------------------------------------------------------------- /config.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Remove os espacos em branco do comeco e do fim da string 21 | // e os \n do fim da string 22 | void trim (char *inputstring) 23 | { 24 | int space_inicial=0; 25 | int space_final=0; 26 | tipostring str_aux; 27 | 28 | 29 | // Remove os spaces do inicio 30 | while (inputstring[space_inicial] == ' ') 31 | space_inicial++; 32 | strcpy(str_aux, &inputstring[space_inicial]); 33 | strcpy(inputstring, str_aux); 34 | 35 | 36 | // Remove os spaces do final 37 | space_final = strlen(inputstring) - 1; 38 | while (inputstring[space_final] == ' ' || inputstring[space_final] == '\n') 39 | { 40 | inputstring[space_final] = '\0'; 41 | space_final--; 42 | } 43 | } 44 | 45 | 46 | // Remove o comentario de uma linha antes de avalia-la 47 | void remover_comentarios (char *inputstring) 48 | { 49 | char *ponto; 50 | 51 | 52 | ponto = strstr(inputstring, "#"); 53 | 54 | if (ponto) 55 | { 56 | *ponto = '\0'; 57 | inputstring = ponto; 58 | } 59 | } 60 | 61 | 62 | // Separa uma string em argumentos com o separador regexp "," 63 | int sep_arg_vet (char *arg[MAX_ARGS], char *inputstring, tipostring regexp) 64 | { 65 | int num_arg=0, i=0; 66 | char **ap; 67 | 68 | 69 | // Separa argumentos em um vetor 70 | for (ap = arg; (*ap = strsep(&inputstring, regexp)) != NULL;) 71 | if (**ap != '\0') 72 | { 73 | if (++ap >= &arg[MAX_ARGS]) 74 | break; 75 | num_arg += 1; 76 | } 77 | 78 | for(i=0; i 1 ? "s" : ""); 123 | 124 | printf("\n"); 125 | printf("Admin Contacts: %d\n", num_admin_contacts); 126 | for(i=0; i 1 ? "s" : ""); 154 | 155 | printf("\n"); 156 | printf("Days to Keep: %d dia%s\n", days_to_keep, days_to_keep > 1 ? "s" : ""); 157 | 158 | printf("\n"); 159 | printf("Days to Learn: %d dia%s\n", days_to_learn, days_to_learn > 1 ? "s" : ""); 160 | 161 | printf("\n"); 162 | printf("Threshold: %.2f(fator) | %.0f%%\n", threshold, (threshold - 1) * 100); 163 | 164 | printf("\n"); 165 | printf("Flag Block Hosts: %d\n", flag_block_hosts); 166 | 167 | printf("\n"); 168 | printf("Flag Send Email: %d\n", flag_send_email); 169 | 170 | printf("\n\n"); 171 | 172 | fflush(stdout); 173 | } 174 | 175 | 176 | // Carrega as configurações do arquivo para as variáveis globais 177 | //void carregar_configuracoes (FILE *in_handler) 178 | void carregar_configuracoes (tipostring arquivo) 179 | { 180 | MYSQL *conn=NULL; 181 | MYSQL_RES *res=NULL; 182 | MYSQL_ROW row; 183 | 184 | tipostring query; 185 | 186 | int i=0, num_arg=0; 187 | tipostring linha, tag; 188 | char *argum[MAX_ARGS]; 189 | char *net_argum_temp[MAX_ARGS]; 190 | 191 | 192 | FILE *in_handler; 193 | if (in_handler = rfopen(arquivo, "rt")) 194 | { 195 | // Ler linha a linha em um buffer inicial 196 | while (fgets(linha, MAX_TAM_LINHA, in_handler)) 197 | { 198 | remover_comentarios(linha); 199 | // Separa as entradas em tag e valores 200 | num_arg = sep_arg_vet(argum, linha, "="); 201 | 202 | // Se achou uma tag com um valor 203 | if (num_arg == 2) 204 | { 205 | // Database 206 | if (!strcmp(argum[0], "db_host")) 207 | strcpy(db_host, argum[1]); 208 | else if (!strcmp(argum[0], "db_user")) 209 | strcpy(db_user, argum[1]); 210 | else if (!strcmp(argum[0], "db_password")) 211 | strcpy(db_password, argum[1]); 212 | else if (!strcmp(argum[0], "db_name")) 213 | strcpy(db_name, argum[1]); 214 | } 215 | } 216 | 217 | //fclose(in_handler); // aberto em main 218 | fclose(in_handler); 219 | } // if in_handler 220 | 221 | 222 | // while (1) 223 | // { 224 | flag_loading_config = 1; // carregando configurações, bloqueia outros acessos 225 | 226 | if ((conn = conectar())) 227 | { 228 | num_interfaces = 0; 229 | sprintf(query, "SELECT interface FROM %s;", INTERFACES_T); 230 | res = sql(query, conn); 231 | while ((row = mysql_fetch_row(res))) 232 | { 233 | strcpy(interfaces[num_interfaces], row[0]); 234 | num_interfaces++; 235 | } 236 | 237 | 238 | num_networks = 0; 239 | sprintf(query, "SELECT network FROM %s;", NETWORKS_T); 240 | res = sql(query, conn); 241 | while ((row = mysql_fetch_row(res))) 242 | { 243 | // Rede/Máscara 244 | sep_arg_vet(net_argum_temp, row[0], "/"); 245 | strcpy(networks[num_networks][0], net_argum_temp[0]); 246 | strcpy(networks[num_networks][1], net_argum_temp[1]); 247 | num_networks++; 248 | } 249 | // Carrega os valores de ip_range para networks_ranges usando a função netmask() de Paul Davis, modificada por mim. 250 | if (num_networks) 251 | netmask_paul_davis(); 252 | 253 | 254 | sprintf(query, "SELECT flow_capture_time_min,pmacctd_bin,pmacct_bin,fire_bin,top_users,base_www,block_time_min,days_to_keep,days_to_learn,threshold,flag_block_hosts,flag_send_email FROM %s;", netactuator_T); 255 | res = sql(query, conn); 256 | while ((row = mysql_fetch_row(res))) 257 | { 258 | flow_capture_time_min = atoi(row[0]); 259 | if (flow_capture_time_min < 1 || flow_capture_time_min > 10) 260 | { 261 | printf("Valor de flow_capture_time=%d está fora do intervalo permitido\n", flow_capture_time_min); 262 | } 263 | flow_capture_time_sec = flow_capture_time_min * 60; // transforma os minutos em segundos 264 | 265 | strcpy(pmacctd_bin, row[1]); 266 | strcpy(pmacct_bin, row[2]); 267 | strcpy(fire_bin, row[3]); 268 | top_users = atoi(row[4]); 269 | strcpy(base_www, row[5]); 270 | block_time_min = atoi(row[6]); 271 | days_to_keep = atoi(row[7]); 272 | days_to_learn = atoi(row[8]); 273 | threshold = 1 + (atof(row[9]) / 100); 274 | flag_block_hosts = atoi(row[10]); 275 | flag_send_email = atoi(row[11]); 276 | } 277 | 278 | 279 | num_admin_contacts = 0; 280 | sprintf(query, "SELECT email FROM %s;", ADMIN_T); 281 | res = sql(query, conn); 282 | while ((row = mysql_fetch_row(res))) 283 | { 284 | strcpy(admin_contacts[num_admin_contacts], row[0]); 285 | num_admin_contacts++; 286 | } 287 | 288 | 289 | num_whitelist = 0; 290 | sprintf(query, "SELECT host FROM %s;", WHITELIST_T); 291 | res = sql(query, conn); 292 | while ((row = mysql_fetch_row(res))) 293 | { 294 | strcpy(whitelist[num_whitelist], row[0]); 295 | num_whitelist++; 296 | } 297 | 298 | 299 | // Determina o firewall a usar 300 | if (strstr(fire_bin, "ipfw")) 301 | { 302 | is_ipfw = 1; 303 | is_iptables = 0; 304 | } 305 | if (strstr(fire_bin, "iptables")) 306 | { 307 | is_iptables = 1; 308 | is_ipfw = 0; 309 | } 310 | 311 | desconectar(conn); 312 | } // if conn 313 | 314 | // Sinaliza ao main que já pode prosseguir (banco ok, configs ok) 315 | flag_loading_config = 0; // configurações carregadas, libera outros acessos 316 | //mostrar_configuracoes(); 317 | // sleep(DELAY_LEITURA_CONFIGS); 318 | // } // while not the end of the world 319 | } 320 | -------------------------------------------------------------------------------- /netactuator.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include 30 | #include 31 | #include 32 | 33 | #include 34 | #include 35 | 36 | #include "defs.h" 37 | #include "proto.h" 38 | #include "mysql_driver.c" 39 | #include "eventos.c" 40 | #include "timing.c" 41 | #include "datastruct.c" 42 | #include "netmask.c" 43 | #include "wrapper.c" 44 | #include "topusers.c" 45 | #include "file.c" 46 | #include "blacklist.c" 47 | #include "action.c" 48 | #include "pattern.c" 49 | #include "graph.c" 50 | #include "limit.c" 51 | #include "config.c" 52 | 53 | 54 | // Mostra o modo de uso do aplicativo 55 | int usage (tipostring programa) 56 | { 57 | printf("\n"); 58 | printf("Modo de uso: %s -c [-v]", programa); 59 | printf("\n\n"); 60 | printf("\n\n"); 61 | 62 | return 1; 63 | } 64 | 65 | 66 | // Para o daemonize 67 | int fork2 (void) 68 | { 69 | pid_t pid; 70 | if (!(pid = fork())) 71 | { 72 | if (!fork()) 73 | return(0); 74 | exit(0); 75 | } 76 | 77 | waitpid(pid, NULL, 0); 78 | 79 | return(1); 80 | } 81 | 82 | 83 | int main (int argc, char *argv[]) 84 | { 85 | int i=0; // contador padrão 86 | int erro=0; // flag que indica se foi executado da forma correta na linha de comando 87 | char *in_opt=NULL; // input file name 88 | FILE *in_handler; // pointer to input file 89 | char ch; // usado pelo getpot in the switch/case pair 90 | time_t data_hora_inicial; 91 | time_t data_hora_atual; 92 | struct tm *sdata; // a ser usado no banco de dados 93 | tipostring comando; // string usada para efetuar comandos no sistema 94 | pthread_t thread; 95 | 96 | 97 | // Captura a data atual - a ser usado no DB - iteracao inicial (threads) 98 | time(&data_hora_inicial); 99 | sdata = localtime(&data_hora_inicial); 100 | sprintf(data, "%d-%d-%d", sdata->tm_year+1900, sdata->tm_mon+1, sdata->tm_mday); 101 | sprintf(hora, "%d:%d:%d", sdata->tm_hour, sdata->tm_min, sdata->tm_sec); 102 | sprintf(week_day, "%d", sdata->tm_wday); 103 | 104 | // Aponta para o local padrão do arquivo de configuração 105 | in_opt = "/usr/local/etc/netactuator/netactuator.conf"; 106 | 107 | // Arquivo de input e output 108 | while ((ch = getopt(argc, argv, "c:v?h")) != -1) 109 | switch (ch) 110 | { 111 | case 'c': 112 | // Define o input_file 113 | free(in_opt); 114 | in_opt = optarg; 115 | break; 116 | 117 | case 'v': 118 | // Mostra a versão 119 | printf("\n"); 120 | printf("netactuator version is: 1.0\n"); 121 | // Não tem break pois leva ao usage 122 | 123 | case '?': 124 | case 'h': 125 | default: 126 | erro = usage(argv[0]); 127 | exit(0); 128 | } // switch 129 | 130 | if (in_opt == NULL) 131 | erro = usage(argv[0]); 132 | 133 | // Se não houve erro, continua com a execução 134 | if (!erro) 135 | { 136 | // Coloca o processo em modo background / detach from console 137 | if (fork2()) 138 | exit(0); 139 | 140 | // Abre arquivo de origem 141 | // if (in_handler = rfopen(in_opt, "rt")) // fechado dentro da thread, em config.c - carregar_configuracoes() 142 | // { 143 | // pthread_create(&thread, NULL, (void *) &carregar_configuracoes, (FILE *) in_handler); 144 | 145 | carregar_configuracoes(in_opt); 146 | 147 | // Aguarda até a thread carregar todas as configs 148 | printf("Inicializando o netactuator...\n"); 149 | while (flag_loading_config) // enquanto carregando configurações, aguarda 150 | { 151 | printf("Aguardando as configs..\n"); 152 | usleep(DELAY_MAIN); 153 | } 154 | 155 | // Inicia as outras threads 156 | pthread_create(&thread, NULL, (void *) &update_pattern_def, NULL); 157 | pthread_create(&thread, NULL, (void *) &on_the_fly, NULL); 158 | pthread_create(&thread, NULL, (void *) &graphing, NULL); 159 | 160 | mostrar_configuracoes(); 161 | 162 | 163 | 164 | /* 165 | Passos: 166 | 167 | 1 - Coleta dados 168 | 169 | 2 - Agrupa dados 170 | 171 | 3 - Checa limites e armazena no banco (usando flags de clean e dirty) e gera gráficos 172 | 3.1 - Gera Gráficos 173 | 174 | 4 - Toma acao (block, mail) 175 | 176 | 5 - Fazer flutuacao de bloqueios 177 | 178 | 6 - Fazer atualizacao de padroes comportamentais 179 | 180 | 9 - Top Users 181 | 182 | 10 - Liberar memoria 183 | 184 | // Verificar o numero da ocorrencia 185 | // Caso maior que o max definido, adicionar em blacklist 186 | */ 187 | 188 | 189 | 190 | // 1 - COLETA 191 | // 1 - SENSOR 192 | 193 | // Certifica-se de que nenhuma instância anterior do pmacctd esteja sendo executada 194 | system("kill -9 $(cat /var/run/pmacctd.pid*) > /dev/null 2>&1"); 195 | system("killall pmacctd > /dev/null 2>&1"); 196 | sleep(3); 197 | 198 | // Captura a data inicial - primeira 199 | time(&data_hora_inicial); 200 | 201 | // Executa o pmacctd para coleta de dados 202 | for(i=0; i= (data_hora_inicial + flow_capture_time_sec) && (flag_loading_config == 0)) 219 | { 220 | // Captura a data inicial - atualiza no momento da coleta real e counter zeroing 221 | time(&data_hora_inicial); 222 | // Data a ser utilizada no RRD update, para não haver problema na demora entre os updates 223 | time(&data_hora_global); 224 | //printf("Nova coleta de stats...\n"); 225 | // Reset na raiz 226 | raiz = NULL; 227 | // Reset no contador de linhas dos arquivos gerados pelo pmacctd 228 | count_log = 0; 229 | // Reset nas listas 230 | top_users_frames_recv = NULL; 231 | top_users_frames_sent = NULL; 232 | top_users_bytes_recv = NULL; 233 | top_users_bytes_sent = NULL; 234 | top_users_convs_as_source = NULL; 235 | top_users_convs_as_destin = NULL; 236 | 237 | 238 | inicial(); 239 | // 2 - COLLECTOR - AGRUPAMENTO 240 | // Processa a coleta e gera estatísticas 241 | for(i=0; itm_year+1900, sdata->tm_mon+1, sdata->tm_mday); 249 | sprintf(hora, "%d:%d:%d", sdata->tm_hour, sdata->tm_min, sdata->tm_sec); 250 | sprintf(week_day, "%d", sdata->tm_wday); 251 | 252 | 253 | inicial(); 254 | // 3 - CHECAGEM DE LIMITES e ARMAZENAMENTO NO BANCO com flags CLEAN e DIRTY 255 | // 3.1 - GERA GRÁFICOS 256 | // 4 - TOMA AÇÃO 257 | // Checa se algum host ultrapassou os limites estabelecidos no arquivo de configuração 258 | // Armazena os dados no banco usando flags de limpo e sujo 259 | // Toma as ações necessárias 260 | 261 | // Cria o diretório dos graphs - criar logo antes de tentar usar, caso tenho sido deletado durante a 262 | // execução reduz as chances de não se encontrar o diretório 263 | sprintf(comando, "mkdir -p %s/graph", base_www); 264 | system(comando); 265 | 266 | // Conectar ao DB 267 | if ((mysql_conn_global = conectar())) 268 | { 269 | // Dentro de checar_limites fica a geração dos gráficos pq o checar_limites jah varre a árvore 270 | // toda, e captura, para cada host, a sua baseline. 271 | flag_limit_update = 1; // bloqueia geração de gráficos para evitar conflitos de acesso aos rrd 272 | checar_limites(raiz); 273 | desconectar(mysql_conn_global); 274 | flag_limit_update = 0; // libera geração de gráficos 275 | } // if conectar 276 | final("LIMIT CHECK"); 277 | 278 | 279 | inicial(); 280 | // 9 - CRIAÇÃO DE LISTAS DE TOP USERS 281 | // Criação das listas de Top Users (vazias por enquanto, apenas espaco alocado) 282 | top_users_frames_recv = criar_lista(top_users); 283 | top_users_frames_sent = criar_lista(top_users); 284 | top_users_bytes_recv = criar_lista(top_users); 285 | top_users_bytes_sent = criar_lista(top_users); 286 | top_users_convs_as_source = criar_lista(top_users); 287 | top_users_convs_as_destin = criar_lista(top_users); 288 | 289 | gerar_top_users(raiz); 290 | final("GERAR TOP USERS"); 291 | 292 | 293 | // mostrar_top_users("convs_as_source"); 294 | // mostrar_top_users("convs_as_destin"); 295 | // mostrar_top_users("frames_recv"); 296 | // mostrar_top_users("frames_sent"); 297 | // mostrar_top_users("bytes_recv"); 298 | // mostrar_top_users("bytes_sent"); 299 | 300 | //inicial(); 301 | // printf("Registros logs (linhas com dois IPs): %ld\n", count_log); 302 | // printf("Registros arvore (um IP): %ld\n", contar_registros_arvore(raiz, 0)); 303 | //final("CONTAR REGISTROS"); 304 | 305 | 306 | inicial(); 307 | gerar_top_users_db(); 308 | final("GERAR TOP USERS DB"); 309 | 310 | // 10 - LIBERAÇÃO DA MEMÓRIA 311 | destruir_arvore(raiz); 312 | destruir_lista(top_users_frames_recv); 313 | destruir_lista(top_users_frames_sent); 314 | destruir_lista(top_users_bytes_recv); 315 | destruir_lista(top_users_bytes_sent); 316 | destruir_lista(top_users_convs_as_source); 317 | destruir_lista(top_users_convs_as_destin); 318 | } // if data_hora do collector (flow_cap_time) 319 | 320 | // Para imprimir as saídas na tela quando há redir no Shell 321 | fflush(stdout); 322 | 323 | usleep(DELAY_MAIN); // delay em cada iteração do laço principal 324 | } // while (1) 325 | // } // if in_handler 326 | } // if !erro 327 | 328 | return 0; 329 | } 330 | -------------------------------------------------------------------------------- /topusers.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Adiciona um novo registro na arvore (um novo IP foi encontrado e precisa ser cadastrado) 21 | void adicionar_registro_arvore (tipostring ip, long recv_f, long recv_b, long sent_f, long sent_b, tipostring iface) 22 | { 23 | SearchTree novo_nodo=NULL; 24 | SearchTree retorno=NULL; 25 | 26 | 27 | // Se ainda nao tiver raiz 28 | if (!raiz) 29 | { 30 | if (!(raiz = (SearchTree) malloc(sizeof(struct TreeNode)))) 31 | { 32 | printf("Sem memoria para continuar.\n"); 33 | exit(1); 34 | } 35 | 36 | strcpy(raiz->info, ip); 37 | raiz->recv_f = recv_f; 38 | raiz->recv_b = recv_b; 39 | raiz->sent_f = sent_f; 40 | raiz->sent_b = sent_b; 41 | strcpy(raiz->iface, iface); 42 | 43 | // Se enviou e nao recebeu frames 44 | if (sent_f && !recv_f) 45 | { 46 | raiz->convs_as_source = 1; 47 | raiz->convs_as_destin = 0; 48 | } 49 | // Se recebeu e nao enviou frames 50 | else if (recv_f && !sent_f) 51 | { 52 | raiz->convs_as_source = 0; 53 | raiz->convs_as_destin = 1; 54 | } 55 | // Se enviou e recebeu frames 56 | else if (sent_f && recv_f) 57 | { 58 | raiz->convs_as_source = 1; 59 | raiz->convs_as_destin = 1; 60 | } 61 | 62 | raiz->dir = NULL; 63 | raiz->esq = NULL; 64 | } 65 | else // Novo nodo 66 | { 67 | if (!(novo_nodo = (SearchTree) malloc(sizeof(struct TreeNode)))) 68 | { 69 | printf("Sem memoria para continuar.\n"); 70 | exit(1); 71 | } 72 | 73 | strcpy(novo_nodo->info, ip); 74 | novo_nodo->recv_f = recv_f; 75 | novo_nodo->recv_b = recv_b; 76 | novo_nodo->sent_f = sent_f; 77 | novo_nodo->sent_b = sent_b; 78 | strcpy(novo_nodo->iface, iface); 79 | 80 | // Se enviou e nao recebeu frames 81 | if (sent_f && !recv_f) 82 | { 83 | novo_nodo->convs_as_source = 1; 84 | novo_nodo->convs_as_destin = 0; 85 | } 86 | // Se recebeu e nao enviou frames 87 | else if (recv_f && !sent_f) 88 | { 89 | novo_nodo->convs_as_source = 0; 90 | novo_nodo->convs_as_destin = 1; 91 | } 92 | // Se enviou e recebeu frames 93 | else if (sent_f && recv_f) 94 | { 95 | novo_nodo->convs_as_source = 1; 96 | novo_nodo->convs_as_destin = 1; 97 | } 98 | 99 | novo_nodo->dir = NULL; 100 | novo_nodo->esq = NULL; 101 | 102 | 103 | retorno = inserir_nodo_arvore(raiz, novo_nodo, NULL); // chama a recursao para situar o novo nodo na arvore 104 | 105 | if (retorno != NULL) // Jah existe, soma os valores 106 | { 107 | retorno->recv_f += novo_nodo->recv_f; 108 | retorno->recv_b += novo_nodo->recv_b; 109 | retorno->sent_f += novo_nodo->sent_f; 110 | retorno->sent_b += novo_nodo->sent_b; 111 | 112 | // Se enviou e nao recebeu frames 113 | if (novo_nodo->sent_f && !novo_nodo->recv_f) 114 | { 115 | retorno->convs_as_source += 1; 116 | retorno->convs_as_destin += 0; 117 | } 118 | // Se recebeu e nao enviou frames 119 | else if (novo_nodo->recv_f && !novo_nodo->sent_f) 120 | { 121 | retorno->convs_as_source += 0; 122 | retorno->convs_as_destin += 1; 123 | } 124 | // Se enviou e recebeu frames 125 | else if (novo_nodo->sent_f && novo_nodo->recv_f) 126 | { 127 | retorno->convs_as_source += 1; 128 | retorno->convs_as_destin += 1; 129 | } 130 | 131 | /* 132 | // Outra forma de somar as conversacoes 133 | // Se enviou frames foi uma conversação onde atuou como source 134 | if (novo_nodo->sent_f) 135 | retorno->convs_as_source += 1; 136 | // Se recebeu frames foi uma conversação onde atuou como destino 137 | if (novo_nodo->recv_f) 138 | retorno->convs_as_destin += 1; 139 | */ 140 | 141 | // nao inseriu pos jah existia, mas jah somou os valores ao nodo previamente existente 142 | free(novo_nodo); 143 | } 144 | } 145 | } 146 | 147 | 148 | // Insere um Top User na lista caso ele seja maior em seu quesito do que um dos atuais integrantes da lista 149 | void inserir_top_user (SearchTree to_insert, tipostring tipo) 150 | { 151 | SeqList comeca=NULL; 152 | 153 | 154 | if (!strcmp(tipo, "frames_recv")) 155 | { 156 | comeca = top_users_frames_recv; 157 | while (comeca) 158 | { 159 | // Se o valor proposto eh maior do que o atual neste nodo, insere 160 | if (to_insert->recv_f > comeca->recv_f) 161 | { 162 | // Inserção 163 | strcpy(comeca->info, to_insert->info); 164 | strcpy(comeca->iface, to_insert->iface); 165 | comeca->recv_f = to_insert->recv_f; 166 | break; 167 | // comeca = NULL; // sai do laço 168 | } 169 | // Vai ao próximo nodo 170 | else 171 | comeca = comeca->p; 172 | } 173 | } 174 | else if (!strcmp(tipo, "frames_sent")) 175 | { 176 | comeca = top_users_frames_sent; 177 | while (comeca) 178 | { 179 | // Se o valor proposto eh maior do que o atual neste nodo, insere 180 | if (to_insert->sent_f > comeca->sent_f) 181 | { 182 | // Inserção 183 | strcpy(comeca->info, to_insert->info); 184 | strcpy(comeca->iface, to_insert->iface); 185 | comeca->sent_f = to_insert->sent_f; 186 | break; 187 | // comeca = NULL; // sai do laço 188 | } 189 | // Vai ao próximo nodo 190 | else 191 | comeca = comeca->p; 192 | } 193 | } 194 | else if (!strcmp(tipo, "bytes_recv")) 195 | { 196 | comeca = top_users_bytes_recv; 197 | while (comeca) 198 | { 199 | // Se o valor proposto eh maior do que o atual neste nodo, insere 200 | if (to_insert->recv_b > comeca->recv_b) 201 | { 202 | // Inserção 203 | strcpy(comeca->info, to_insert->info); 204 | strcpy(comeca->iface, to_insert->iface); 205 | comeca->recv_b = to_insert->recv_b; 206 | break; 207 | // comeca = NULL; // sai do laço 208 | } 209 | // Vai ao próximo nodo 210 | else 211 | comeca = comeca->p; 212 | } 213 | } 214 | else if (!strcmp(tipo, "bytes_sent")) 215 | { 216 | comeca = top_users_bytes_sent; 217 | while (comeca) 218 | { 219 | // Se o valor proposto eh maior do que o atual neste nodo, insere 220 | if (to_insert->sent_b > comeca->sent_b) 221 | { 222 | // Inserção 223 | strcpy(comeca->info, to_insert->info); 224 | strcpy(comeca->iface, to_insert->iface); 225 | comeca->sent_b = to_insert->sent_b; 226 | break; 227 | // comeca = NULL; // sai do laço 228 | } 229 | // Vai ao próximo nodo 230 | else 231 | comeca = comeca->p; 232 | } 233 | } 234 | else if (!strcmp(tipo, "convs_as_source")) 235 | { 236 | comeca = top_users_convs_as_source; 237 | while (comeca) 238 | { 239 | // Se o valor proposto eh maior do que o atual neste nodo, insere 240 | if (to_insert->convs_as_source > comeca->convs_as_source) 241 | { 242 | // Inserção 243 | strcpy(comeca->info, to_insert->info); 244 | strcpy(comeca->iface, to_insert->iface); 245 | comeca->convs_as_source = to_insert->convs_as_source; 246 | break; 247 | // comeca = NULL; // sai do laço 248 | } 249 | // Vai ao próximo nodo 250 | else 251 | comeca = comeca->p; 252 | } 253 | } 254 | else if (!strcmp(tipo, "convs_as_destin")) 255 | { 256 | comeca = top_users_convs_as_destin; 257 | while (comeca) 258 | { 259 | // Se o valor proposto eh maior do que o atual neste nodo, insere 260 | if (to_insert->convs_as_destin > comeca->convs_as_destin) 261 | { 262 | // Inserção 263 | strcpy(comeca->info, to_insert->info); 264 | strcpy(comeca->iface, to_insert->iface); 265 | comeca->convs_as_destin = to_insert->convs_as_destin; 266 | break; 267 | // comeca = NULL; // sai do laço 268 | } 269 | // Vai ao próximo nodo 270 | else 271 | comeca = comeca->p; 272 | } 273 | } 274 | } 275 | 276 | 277 | // Cadastra os Top Users nas listas varrendo toda a arvore a partir da raiz 278 | void gerar_top_users (SearchTree comeca) 279 | { 280 | if (comeca) 281 | { 282 | gerar_top_users(comeca->dir); 283 | gerar_top_users(comeca->esq); 284 | 285 | inserir_top_user(comeca, "frames_recv"); 286 | inserir_top_user(comeca, "frames_sent"); 287 | inserir_top_user(comeca, "bytes_recv"); 288 | inserir_top_user(comeca, "bytes_sent"); 289 | inserir_top_user(comeca, "convs_as_source"); 290 | inserir_top_user(comeca, "convs_as_destin"); 291 | } 292 | } 293 | 294 | 295 | // Mostra a lista de Top Users de acordo com o relatório pedido 296 | void mostrar_top_users (tipostring tipo) 297 | { 298 | SeqList comeca=NULL; 299 | 300 | 301 | if (!strcmp(tipo, "frames_recv")) 302 | { 303 | printf("Top Users Frames Recebidos:\n"); 304 | comeca = top_users_frames_recv; 305 | while (comeca) 306 | { 307 | if (strcmp(comeca->info, "vago")) 308 | { 309 | printf("IP: %s ->", comeca->info); 310 | printf(" Recv Frames: %ld", comeca->recv_f); 311 | printf(" Iface: %s", comeca->iface); 312 | printf("\n"); 313 | } 314 | comeca = comeca->p; 315 | } 316 | } 317 | else if (!strcmp(tipo, "frames_sent")) 318 | { 319 | printf("Top Users Frames Enviados:\n"); 320 | comeca = top_users_frames_sent; 321 | while (comeca) 322 | { 323 | if (strcmp(comeca->info, "vago")) 324 | { 325 | printf("IP: %s ->", comeca->info); 326 | printf(" Sent Frames: %ld", comeca->sent_f); 327 | printf(" Iface: %s", comeca->iface); 328 | printf("\n"); 329 | } 330 | comeca = comeca->p; 331 | } 332 | } 333 | else if (!strcmp(tipo, "bytes_recv")) 334 | { 335 | printf("Top Users Bytes Recebidos:\n"); 336 | comeca = top_users_bytes_recv; 337 | while (comeca) 338 | { 339 | if (strcmp(comeca->info, "vago")) 340 | { 341 | printf("IP: %s ->", comeca->info); 342 | printf(" Recv Bytes: %ld", comeca->recv_b); 343 | printf(" Iface: %s", comeca->iface); 344 | printf("\n"); 345 | } 346 | comeca = comeca->p; 347 | } 348 | } 349 | else if (!strcmp(tipo, "bytes_sent")) 350 | { 351 | printf("Top Users Bytes Enviados:\n"); 352 | comeca = top_users_bytes_sent; 353 | while (comeca) 354 | { 355 | if (strcmp(comeca->info, "vago")) 356 | { 357 | printf("IP: %s ->", comeca->info); 358 | printf(" Sent Bytes: %ld", comeca->sent_b); 359 | printf(" Iface: %s", comeca->iface); 360 | printf("\n"); 361 | } 362 | comeca = comeca->p; 363 | } 364 | } 365 | else if (!strcmp(tipo, "convs_as_source")) 366 | { 367 | printf("Top Users Conversations as Source:\n"); 368 | comeca = top_users_convs_as_source; 369 | while (comeca) 370 | { 371 | if (strcmp(comeca->info, "vago")) 372 | { 373 | printf("IP: %s ->", comeca->info); 374 | printf(" Convs as Source: %ld", comeca->convs_as_source); 375 | printf(" Iface: %s", comeca->iface); 376 | printf("\n"); 377 | } 378 | comeca = comeca->p; 379 | } 380 | } 381 | else if (!strcmp(tipo, "convs_as_destin")) 382 | { 383 | printf("Top Users Conversations as Destin:\n"); 384 | comeca = top_users_convs_as_destin; 385 | while (comeca) 386 | { 387 | if (strcmp(comeca->info, "vago")) 388 | { 389 | printf("IP: %s ->", comeca->info); 390 | printf(" Convs as Destin: %ld", comeca->convs_as_destin); 391 | printf(" Iface: %s", comeca->iface); 392 | printf("\n"); 393 | } 394 | comeca = comeca->p; 395 | } 396 | } 397 | 398 | printf("\n"); 399 | } 400 | 401 | 402 | // Gera os top users para dentro do DB 403 | gerar_top_users_db (void) 404 | { 405 | MYSQL *conn=NULL; 406 | MYSQL_RES *res=NULL; 407 | MYSQL_ROW row; 408 | 409 | tipostring query; 410 | 411 | 412 | if ((conn = conectar())) 413 | { 414 | // Limpa 415 | sprintf(query, "DELETE FROM %s;", TOPUSERS_T); 416 | res = sql(query, conn); 417 | 418 | 419 | // Gera os top 420 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"1\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY convs_as_source DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 421 | res = sql(query, conn); 422 | 423 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"2\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY convs_as_destin DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 424 | res = sql(query, conn); 425 | 426 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"3\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY frames_in DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 427 | res = sql(query, conn); 428 | 429 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"4\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY frames_out DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 430 | res = sql(query, conn); 431 | 432 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"5\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY bytes_in DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 433 | res = sql(query, conn); 434 | 435 | sprintf(query, "INSERT INTO %s () SELECT host, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, \"6\" FROM %s WHERE data = '%s' AND hora = '%s' ORDER BY bytes_out DESC limit %d;", TOPUSERS_T, MASS_T, data, hora, top_users); 436 | res = sql(query, conn); 437 | 438 | 439 | desconectar(conn); 440 | } // if conn 441 | } 442 | -------------------------------------------------------------------------------- /graph.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of netactuator. 3 | * 4 | * netactuator is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * netactuator is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with netactuator. If not, see 16 | * 17 | */ 18 | 19 | 20 | // Cria a base RRD 21 | void rrd_create_rog (tipostring arquivo) 22 | { 23 | tipostring step; 24 | tipostring ds_convs_as_source; 25 | tipostring ds_convs_as_destin; 26 | tipostring ds_frames_in; 27 | tipostring ds_frames_out; 28 | tipostring ds_bytes_in; 29 | tipostring ds_bytes_out; 30 | tipostring ds_baseline; 31 | tipostring ds_threshold; 32 | tipostring rra_day_avg; 33 | tipostring rra_week_avg; 34 | tipostring rra_month_avg; 35 | tipostring rra_year_avg; 36 | tipostring rra_week_max; 37 | tipostring rra_month_max; 38 | tipostring rra_year_max; 39 | int heartbeat; 40 | int day_steps; 41 | int week_steps; 42 | int month_steps; 43 | int year_steps; 44 | int day_rows; 45 | int week_rows; 46 | int month_rows; 47 | int year_rows; 48 | float fator=2.0; // Número de dias, semanas, meses e anos completos a manter 49 | 50 | 51 | sprintf(step, "-s %d", flow_capture_time_sec); 52 | heartbeat = flow_capture_time_sec * 2; // HB é maior do que step 53 | 54 | day_steps = 1; // Resolução máxima diária (valor exato a cada step segundos) 55 | week_steps = (30.0 / flow_capture_time_sec * 60); // Resolução de 30 minutos (média de 30 em 30 minutos, na consolidação) 56 | month_steps = (120.0 / flow_capture_time_sec * 60); // Resolução de 2 horas (média de 2 em 2 horas, na consolidação) 57 | year_steps = (360.0 / flow_capture_time_sec * 60); // Resolução de 6 horas (média de 6 em 6 horas, na consolidação) 58 | 59 | day_rows = (fator * 86400 / flow_capture_time_sec); // num rows para step segundos 60 | week_rows = (fator * 100800 / flow_capture_time_sec); // num rows para 30 minutos 61 | month_rows = (fator * 111600 / flow_capture_time_sec); // num rows para 2 horas 62 | year_rows = (fator * 439200 / flow_capture_time_sec); // num rows para 6 horas 63 | 64 | if (day_steps <= 0) 65 | day_steps = 1; 66 | if (week_steps <= 0) 67 | week_steps = 1; 68 | if (month_steps <= 0) 69 | month_steps = 1; 70 | if (year_steps <= 0) 71 | year_steps = 1; 72 | 73 | if (day_rows <= 0) 74 | day_rows = 1; 75 | if (week_rows <= 0) 76 | week_rows = 1; 77 | if (month_rows <= 0) 78 | month_rows = 1; 79 | if (year_rows <= 0) 80 | year_rows = 1; 81 | 82 | sprintf(ds_convs_as_source, "DS:convs_as_source:GAUGE:%d:0:U", heartbeat); 83 | sprintf(ds_convs_as_destin, "DS:convs_as_destin:GAUGE:%d:0:U", heartbeat); 84 | 85 | sprintf(ds_frames_in, "DS:frames_in:ABSOLUTE:%d:0:U", heartbeat); 86 | sprintf(ds_frames_out, "DS:frames_out:ABSOLUTE:%d:0:U", heartbeat); 87 | 88 | sprintf(ds_bytes_in, "DS:bytes_in:ABSOLUTE:%d:0:U", heartbeat); 89 | sprintf(ds_bytes_out, "DS:bytes_out:ABSOLUTE:%d:0:U", heartbeat); 90 | 91 | sprintf(ds_baseline, "DS:baseline:GAUGE:%d:0:U", heartbeat); 92 | sprintf(ds_threshold, "DS:threshold:GAUGE:%d:0:U", heartbeat); 93 | 94 | sprintf(rra_day_avg, "RRA:AVERAGE:0.5:%d:%d", day_steps, day_rows); 95 | sprintf(rra_week_avg, "RRA:AVERAGE:0.5:%d:%d", week_steps, week_rows); 96 | sprintf(rra_month_avg, "RRA:AVERAGE:0.5:%d:%d", month_steps, month_rows); 97 | sprintf(rra_year_avg, "RRA:AVERAGE:0.5:%d:%d", year_steps, year_rows); 98 | 99 | sprintf(rra_week_max, "RRA:MAX:0.5:%d:%d", week_steps, week_rows); 100 | sprintf(rra_month_max, "RRA:MAX:0.5:%d:%d", month_steps, month_rows); 101 | sprintf(rra_year_max, "RRA:MAX:0.5:%d:%d", year_steps, year_rows); 102 | 103 | /* 104 | printf("%s\n", ds_convs_as_source); 105 | printf("%s\n", ds_convs_as_destin); 106 | printf("%s\n", ds_frames_in); 107 | printf("%s\n", ds_frames_out); 108 | printf("%s\n", ds_bytes_in); 109 | printf("%s\n", ds_bytes_out); 110 | printf("%s\n", ds_baseline); 111 | printf("%s\n", ds_threshold); 112 | printf("%s\n", rra_day_avg); 113 | printf("%s\n", rra_week_avg); 114 | printf("%s\n", rra_month_avg); 115 | printf("%s\n", rra_year_avg); 116 | */ 117 | 118 | char *params[] = { 119 | "create", 120 | arquivo, 121 | step, 122 | ds_convs_as_source, 123 | ds_convs_as_destin, 124 | ds_frames_in, 125 | ds_frames_out, 126 | ds_bytes_in, 127 | ds_bytes_out, 128 | ds_baseline, 129 | ds_threshold, 130 | rra_day_avg, 131 | rra_week_avg, 132 | rra_month_avg, 133 | rra_year_avg, 134 | rra_week_max, 135 | rra_month_max, 136 | rra_year_max, 137 | NULL 138 | }; 139 | 140 | optind = opterr = 0; /* Because rrdtool uses getopt() */ 141 | rrd_clear_error(); 142 | rrd_create(18, params); 143 | 144 | /* 145 | Com step de 300 (5 minutos) temos: 146 | 72 = a cada seis horas, o mrtg usa a cada 24 para year (288) 147 | 24 = a cada duas horas, para mes, mesmo do mrtg 148 | 6 = a cada meia hora, para semana, mesmo do mrtg 149 | 1 = a cada cinco minutos, resolucao maxima, usado no diario 150 | 151 | Com step de 60 (1 minuto) temos: 152 | 72 = a cada 1.2 horas, para year 153 | 24 = a cada 24 minutos, para mes 154 | 6 = a cada 6 minutos, para semana 155 | 1 = a cada minuto, resolucao maxima, usado no diario 156 | */ 157 | } 158 | 159 | 160 | // Alimenta a base RRD 161 | void rrd_update_rog (tipostring arquivo, long convs_as_source, long convs_as_destin, long frames_in, long frames_out, long bytes_in, long bytes_out, long baseline) 162 | { 163 | tipostring dados; 164 | 165 | 166 | // sprintf(dados, "N:%ld:%ld:%ld:%ld:%ld:%ld:%ld:%0.f", convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, baseline, baseline * threshold); 167 | sprintf(dados, "%ld:%ld:%ld:%ld:%ld:%ld:%ld:%ld:%0.f", 168 | data_hora_global, convs_as_source, convs_as_destin, frames_in, frames_out, bytes_in, bytes_out, baseline, baseline * threshold); 169 | 170 | char *params[] = { 171 | "update", 172 | arquivo, 173 | dados, 174 | NULL 175 | }; 176 | 177 | printf("update: %s %s\n", arquivo, dados); 178 | optind = opterr = 0; /* Because rrdtool uses getopt() */ 179 | rrd_clear_error(); 180 | rrd_update(3, params); 181 | } 182 | 183 | 184 | // Gera os gráficos para o ip passado 185 | //void rrd_graph_rog (int cod, tipostring host, long convs_as_source, long baseline) 186 | void rrd_graph_rog (int tip, int cod, tipostring host) 187 | { 188 | tipostring arquivo; 189 | tipostring arquivo_png; 190 | tipostring tittle; 191 | tipostring start; 192 | tipostring x_axis; 193 | tipostring def1; 194 | tipostring def2; 195 | tipostring def3; 196 | tipostring rrdmtime_comment; 197 | char **calcpr=NULL; 198 | int rrdargcount, xsize, ysize, result; 199 | double ymin, ymax; 200 | struct stat sb; 201 | 202 | 203 | // rrd a usar 204 | sprintf(arquivo, "%s/graph/%s_%d.rrd", base_www, host, flow_capture_time_sec); 205 | if (stat(arquivo, &sb) == -1) { 206 | perror("stat"); 207 | } 208 | else { 209 | //strftime(rrdmtime_comment, sizeof(rrdmtime_comment), "COMMENT:Ultima leitura\\:\t\t\t%a, %d %b %Y %H\\:%M\\:%S %Z", localtime(&sb.st_mtime)); 210 | strftime(rrdmtime_comment, sizeof(rrdmtime_comment), "COMMENT:Ultima leitura\\: %a, %d %b %Y %H\\:%M\\:%S %Z", localtime(&sb.st_mtime)); 211 | } 212 | 213 | if (tip == 0) 214 | { 215 | sprintf(def1, "DEF:convs_source=%s:convs_as_source:AVERAGE", arquivo); 216 | sprintf(def2, "DEF:baseline=%s:baseline:AVERAGE", arquivo); 217 | sprintf(def3, "DEF:threshold=%s:threshold:AVERAGE", arquivo); 218 | 219 | // Day 220 | if (cod == 0) 221 | { 222 | sprintf(arquivo_png, "%s/graph/%s_%d_base_day.png", base_www, host, flow_capture_time_sec); 223 | sprintf(tittle, "Diario - %s", host); 224 | strcpy(start, "-1day12hours"); 225 | strcpy(x_axis, "HOUR:1:HOUR:1:HOUR:2:0:%H"); 226 | } 227 | // Week 228 | if (cod == 1) 229 | { 230 | sprintf(arquivo_png, "%s/graph/%s_%d_base_week.png", base_www, host, flow_capture_time_sec); 231 | sprintf(tittle, "Semanal - %s", host); 232 | strcpy(start, "-1week2days"); 233 | strcpy(x_axis, "HOUR:8:DAY:1:DAY:1:86400:%a"); 234 | } 235 | // Month 236 | if (cod == 2) 237 | { 238 | sprintf(arquivo_png, "%s/graph/%s_%d_base_month.png", base_www, host, flow_capture_time_sec); 239 | sprintf(tittle, "Mensal - %s", host); 240 | strcpy(start, "-1month1week"); 241 | strcpy(x_axis, "DAY:1:WEEK:1:WEEK:1:604800:Semana %W"); 242 | } 243 | // Year 244 | if (cod == 3) 245 | { 246 | sprintf(arquivo_png, "%s/graph/%s_%d_base_year.png", base_www, host, flow_capture_time_sec); 247 | sprintf(tittle, "Anual - %s", host); 248 | strcpy(start, "-1year2months"); 249 | strcpy(x_axis, "WEEK:1:MONTH:1:MONTH:1:2678400:%b"); 250 | } 251 | 252 | /* 253 | printf("rrd: %s\n", arquivo); 254 | printf("png: %s\n", arquivo_png); 255 | printf("tittle: %s\n", tittle); 256 | printf("start: %s\n\n", start); 257 | fflush(stdout); 258 | */ 259 | 260 | char *params[] = { 261 | "graph", 262 | arquivo_png, 263 | "-t", tittle, 264 | "-s", start, 265 | "-x", x_axis, 266 | "-v", "Convs as Source", 267 | "-z", 268 | "-a", "PNG", 269 | "-w", "400", 270 | "-c", "SHADEA#000000", 271 | "-c", "SHADEB#000000", 272 | "-c", "MGRID#999999", 273 | "-c", "FRAME#000000", 274 | "-c", "AXIS#000000", 275 | "-E", 276 | "-i", 277 | def1, 278 | def2, 279 | def3, 280 | "CDEF:acima_mark=convs_source,threshold,GT,threshold,0,IF", 281 | "CDEF:acima_print=convs_source,threshold,GT,convs_source,threshold,-,0,IF", 282 | "VDEF:base_fill=baseline,LAST", 283 | "CDEF:baseline_fill=baseline,UN,base_fill,baseline,IF", 284 | "VDEF:thres_fill=threshold,LAST", 285 | "CDEF:threshold_fill=threshold,UN,thres_fill,threshold,IF", 286 | "CDEF:normal=convs_source,threshold,LT,convs_source,0,IF", 287 | "CDEF:comprometido=convs_source,threshold,GT,convs_source,0,IF", 288 | "COMMENT: Ultimo Maximo Media\\n", 289 | "AREA:convs_source#00FF00:Normal ", 290 | "LINE0.4:convs_source#000000", 291 | "GPRINT:normal:LAST:%6.0lf", 292 | "GPRINT:normal:MAX:%6.0lf", 293 | "GPRINT:normal:AVERAGE:%6.0lf\\n", 294 | "AREA:acima_mark", 295 | "AREA:acima_print#FF0000:Comprometido :STACK", 296 | "LINE0.4:acima_print#000000", 297 | "GPRINT:comprometido:LAST:%6.0lf", 298 | "GPRINT:comprometido:MAX:%6.0lf", 299 | "GPRINT:comprometido:AVERAGE:%6.0lf\\n", 300 | "LINE2:baseline_fill#5500FF", 301 | "LINE2:baseline#5500FF:Baseline ", 302 | "GPRINT:baseline:LAST:%6.0lf", 303 | "GPRINT:baseline:MAX:%6.0lf", 304 | "GPRINT:baseline:AVERAGE:%6.0lf\\n", 305 | "LINE2:threshold_fill#FF00FF", 306 | "LINE2:threshold#FF00FF:Limite ", 307 | "GPRINT:threshold:LAST:%6.0lf", 308 | "GPRINT:threshold:MAX:%6.0lf", 309 | "GPRINT:threshold:AVERAGE:%6.0lf\\n", 310 | "COMMENT:\\n", 311 | rrdmtime_comment, 312 | NULL 313 | }; 314 | // "VDEF:leitura_ativ_last=convs_source,LAST" - Hora/Data da última atividade 315 | // "GPRINT:leitura_ativ_last:%c", 316 | 317 | optind = opterr = 0; /* Because rrdtool uses getopt() */ 318 | rrd_clear_error(); 319 | result = rrd_graph(62, params, &calcpr, &xsize, &ysize, NULL, &ymin, &ymax); 320 | } // tip 0 321 | else if (tip == 1) 322 | { 323 | sprintf(def1, "DEF:bytes_in=%s:bytes_in:AVERAGE", arquivo); 324 | sprintf(def2, "DEF:bytes_out=%s:bytes_out:AVERAGE", arquivo); 325 | 326 | // Day 327 | if (cod == 0) 328 | { 329 | sprintf(arquivo_png, "%s/graph/%s_%d_traf_day.png", base_www, host, flow_capture_time_sec); 330 | sprintf(tittle, "Diario - %s", host); 331 | strcpy(start, "-1day12hours"); 332 | strcpy(x_axis, "HOUR:1:HOUR:1:HOUR:2:0:%H"); 333 | } 334 | // Week 335 | if (cod == 1) 336 | { 337 | sprintf(arquivo_png, "%s/graph/%s_%d_traf_week.png", base_www, host, flow_capture_time_sec); 338 | sprintf(tittle, "Semanal - %s", host); 339 | strcpy(start, "-1week2days"); 340 | strcpy(x_axis, "HOUR:8:DAY:1:DAY:1:86400:%a"); 341 | } 342 | // Month 343 | if (cod == 2) 344 | { 345 | sprintf(arquivo_png, "%s/graph/%s_%d_traf_month.png", base_www, host, flow_capture_time_sec); 346 | sprintf(tittle, "Mensal - %s", host); 347 | strcpy(start, "-1month1week"); 348 | strcpy(x_axis, "DAY:1:WEEK:1:WEEK:1:604800:Semana %W"); 349 | } 350 | // Year 351 | if (cod == 3) 352 | { 353 | sprintf(arquivo_png, "%s/graph/%s_%d_traf_year.png", base_www, host, flow_capture_time_sec); 354 | sprintf(tittle, "Anual - %s", host); 355 | strcpy(start, "-1year2months"); 356 | strcpy(x_axis, "WEEK:1:MONTH:1:MONTH:1:2678400:%b"); 357 | } 358 | 359 | /* 360 | printf("rrd: %s\n", arquivo); 361 | printf("png: %s\n", arquivo_png); 362 | printf("tittle: %s\n", tittle); 363 | printf("start: %s\n\n", start); 364 | fflush(stdout); 365 | */ 366 | 367 | char *params[] = { 368 | "graph", 369 | arquivo_png, 370 | "-t", tittle, 371 | "-s", start, 372 | "-x", x_axis, 373 | "-v", "Trafego", 374 | "-z", 375 | "-a", "PNG", 376 | "-w", "400", 377 | "-c", "SHADEA#000000", 378 | "-c", "SHADEB#000000", 379 | "-c", "MGRID#999999", 380 | "-c", "FRAME#000000", 381 | "-c", "AXIS#000000", 382 | "-E", 383 | "-i", 384 | def1, 385 | def2, 386 | "CDEF:bits_in=bytes_in,8,*", 387 | "CDEF:bits_out=bytes_out,8,*", 388 | "CDEF:kbits_in=bytes_in,8,*,1000,/", 389 | "CDEF:kbits_out=bytes_out,8,*,1000,/", 390 | "COMMENT: Ultimo Maximo Media Total\\n", 391 | "AREA:bits_in#00FF00:Download (kbps)", 392 | "LINE0.4:bits_in#000000", 393 | "GPRINT:kbits_in:LAST:%6.0lf", 394 | "GPRINT:kbits_in:MAX:%6.0lf", 395 | "GPRINT:kbits_in:AVERAGE:%6.0lf", 396 | "CDEF:megas_in=bytes_in,1048576,/", 397 | "VDEF:total_in=megas_in,TOTAL", 398 | "GPRINT:total_in:%9.1lf (MB)\\n", 399 | "LINE1:bits_out#5500FF:Upload (kbps) ", 400 | "GPRINT:kbits_out:LAST:%6.0lf", 401 | "GPRINT:kbits_out:MAX:%6.0lf", 402 | "GPRINT:kbits_out:AVERAGE:%6.0lf", 403 | "CDEF:megas_out=bytes_out,1048576,/", 404 | "VDEF:total_out=megas_out,TOTAL", 405 | "GPRINT:total_out:%9.1lf (MB)\\n", 406 | "COMMENT:\\n", 407 | rrdmtime_comment, 408 | NULL 409 | }; 410 | // "VDEF:leitura_ativ_last=bytes_in,LAST" - Hora/Data da última atividade 411 | // Imprimir AREA e LINE com bits para mostrar o "k" no gráfico 412 | // Imprimir legendas em kbits para mostrar um valor mais inteligivel 413 | // "GPRINT:leitura_ativ_last:%c", 414 | 415 | optind = opterr = 0; /* Because rrdtool uses getopt() */ 416 | rrd_clear_error(); 417 | result = rrd_graph(51, params, &calcpr, &xsize, &ysize, NULL, &ymin, &ymax); 418 | } // tip 1 419 | 420 | // Liberar a memória 421 | if (calcpr) 422 | { 423 | int i; 424 | for (i=0; (calcpr[i]); i++) 425 | free(calcpr[i]); 426 | calcpr = NULL; 427 | } 428 | 429 | /* Was it OK ? */ 430 | if (rrd_test_error() || (result != 0)) 431 | // lazzy updates generates blank error, so we ignore it 432 | if (strcmp(rrd_get_error(), "") != 0) 433 | printf("Graph error: %s\n", rrd_get_error()); 434 | } 435 | 436 | 437 | // Gerencia os arquivos rrd 438 | void rrd_rog (graph_t *graph) 439 | { 440 | tipostring arquivo; 441 | graph_t graph_local; 442 | 443 | 444 | // Copia os valores um a um para uma estrutura local 445 | strcpy(graph_local.info, graph->info); 446 | graph_local.recv_f = graph->recv_f; 447 | graph_local.sent_f = graph->sent_f; 448 | graph_local.recv_b = graph->recv_b; 449 | graph_local.sent_b = graph->sent_b; 450 | graph_local.convs_as_source = graph->convs_as_source; 451 | graph_local.convs_as_destin = graph->convs_as_destin; 452 | strcpy(graph_local.iface, graph->iface); 453 | graph_local.baseline = graph->baseline; 454 | 455 | //printf("HOST %s -> %ld:%ld:%0.f\n", graph_local.info, graph_local.convs_as_source, graph_local.baseline, graph_local.baseline * threshold); 456 | sprintf(arquivo, "%s/graph/%s_%d.rrd", base_www, graph_local.info, flow_capture_time_sec); 457 | if (access(arquivo, F_OK)) // Se o arquivo .rrd não existir, cria. 458 | rrd_create_rog(arquivo); 459 | 460 | rrd_update_rog(arquivo, graph_local.convs_as_source, graph_local.convs_as_destin, graph_local.recv_f, graph_local.sent_f, graph_local.recv_b, graph_local.sent_b, graph_local.baseline); 461 | } 462 | 463 | 464 | // Gera os gráficos em thread, a cada intervalo regular de tempo 465 | void graphing (void) 466 | { 467 | MYSQL *conn=NULL; 468 | MYSQL_RES *res=NULL; 469 | MYSQL_ROW row; 470 | 471 | tipostring query; 472 | tipostring host; 473 | time_t data_hora; 474 | time_t data_hora_last=0; // hora da última atualização 475 | 476 | 477 | while (1) 478 | { 479 | // Captura a data atual 480 | time(&data_hora); 481 | 482 | // 6 - ATUALIZAÇÃO DOS GRÁFICOS 483 | // Se a hora atual for maior que a anterior somada ao delay escolhido, update nos graphs 484 | if (data_hora > data_hora_last + (graph_update_time_min * 60)) 485 | { 486 | // Marca data da última atualização 487 | // marcar logo no começo para que independentemente do tempo que levar para gerar os gráficos o software 488 | // não leve mais do que graph_update_time_min entre um start e outro do graphing, exceto, é claro, quando o 489 | // tempo de graphing for maior do que o tempo de graph_update_time_min. 490 | time(&data_hora_last); 491 | inicial(); 492 | if ((conn = conectar())) 493 | { 494 | // Somente gera gráficos dos hosts que tiveram atividade dentro das últimas 3 execuções de coleta 495 | sprintf(query, "SELECT host from (SELECT host,hora FROM %s WHERE data = '%s' GROUP BY host HAVING TIME_TO_SEC(TIMEDIFF(CURTIME(), MAX(hora))) <= %d AND TIME_TO_SEC(TIMEDIFF(CURTIME(), MAX(hora))) >= 0) as A;", MASS_T, data, flow_capture_time_sec * 3); 496 | //printf("Graph query: %s", query); 497 | 498 | res = sql(query, conn); 499 | 500 | while ((row = mysql_fetch_row(res))) 501 | { 502 | while (flag_limit_update) // enquanto estiver fazendo updates, dentro da checagem de limites, não gera gráficos 503 | { 504 | usleep(DELAY_MAIN); 505 | //printf("aguardando limit terminar..\n"); 506 | //fflush(stdout); 507 | } 508 | 509 | strcpy(host, row[0]); 510 | printf("graphing for %s\n", host); 511 | 512 | // VER AQUI - talvez verificar se flag_limit_update estah 1 antes de CADA chamada ao graph 513 | 514 | // BASE 515 | rrd_graph_rog(0, 0, host); // day 516 | rrd_graph_rog(0, 1, host); // week 517 | rrd_graph_rog(0, 2, host); // month 518 | rrd_graph_rog(0, 3, host); // year 519 | 520 | // TRAF 521 | rrd_graph_rog(1, 0, host); // day 522 | rrd_graph_rog(1, 1, host); // week 523 | rrd_graph_rog(1, 2, host); // month 524 | rrd_graph_rog(1, 3, host); // year 525 | 526 | fflush(stdout); 527 | } 528 | 529 | desconectar(conn); 530 | } // if conn 531 | 532 | final("GRAPHING"); 533 | } 534 | 535 | sleep(DELAY_UPDATE); 536 | } // while not the end of the world 537 | } 538 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------
Tabelas
25 |    $description 26 |
Inserir novo
".$field[$j]."
".$field[$j]."
".$field[$j]."
".$field[$j]."
".$dados[$j]."
".$dados[$j]."
82 |    Gráficos 83 |
".$dados[$j]."
101 |
102 | 105 | 108 |
109 |
AUTO
126 | 129 |
130 |
138 | 139 |
".$dados[$j]."
".$dados[$j]."
Inserir novo