el caso es que se tiene uno o varios firewall en linux...
Los mismos funciona bien y se desea pasar dichas reglas del iptables a una base de datos en este caso postgres y a su ves colocarlo en el crontab para que cierto tiempo dicha tabla se mantenga actualizada.
Para realizarlo se utilizo Perl como lenguaje.
PASO 1.
Crear la tabla en nuestra base de datos y darle permiso al usuario y a la ip del firewall.
-- Table: iptables -- DROP TABLE iptables; CREATE TABLE iptables ( id_iptable serial NOT NULL, protocol character varying, bytes character varying, s_port character varying, packets character varying, dport character varying, state character varying, target character varying, intf_in character varying, d_port character varying, to_ip character varying, src character varying, intf_out character varying, sport character varying, dst character varying, to_port character varying, rawx character varying, firewall numeric, comentario character varying, CONSTRAINT pk_id_iptable PRIMARY KEY (id_iptable) ) WITH (OIDS=FALSE); ALTER TABLE iptables OWNER TO postgres; GRANT ALL ON TABLE iptables TO postgres; GRANT SELECT, INSERT, DELETE ON TABLE iptables TO mi_user;
PASO 2
Tener instalado PERL en el firewall o donde esten las reglas que deseamos pasar a la BD.
En el 99.99% de las distribuciones linux perl viene instalado por defecto.
PASO 3
Instala los modulos necesarios de Perl. Estas son:
- IPTables::Parse
- DBD::Pg (Opcional)
- DBI
Los mismos pueden ser instalados según su preferencia que hasta ahora yo conozco de tres maneras:
1_. Descargando las librerias e instalando con MAKEFILE()
2_. Utilizando CPAN(Es la forma automatizada de la manera 1).
3_. Entrar como root he instalar
#apt-get install libdbd-pg-perl libiptables-parse-perl libclass-dbi-pg-perl
PASO 4
Una vez instalado... creamos un archivo con el siguiente contenido
#!/usr/bin/perl use IPTables::Parse; use Data::Dumper; use DBI; $firewall = "Nombre del Firewall"; my %opts = ( 'iptables' => '/sbin/iptables', 'iptout' => '', 'ipterr' => '', 'debug' => 0, 'verbose' => 0 ); #Creamos los obj necesarios para guardar las reglas y recorrelas my $ipt_obj_forward = new IPTables::Parse(%opts) or die "[*] Could not acquire IPTables::Parse object"; my $ipt_obj_input = new IPTables::Parse(%opts) or die "[*] Could not acquire IPTables::Parse object"; my $ipt_obj_snat = new IPTables::Parse(%opts) or die "[*] Could not acquire IPTables::Parse object"; print "Cadena FORWARD por defecto: ",$ipt_obj_forward->chain_policy('filter', 'FORWARD'), "\n"; @rules_forward = $ipt_obj_forward->chain_rules('filter', 'FORWARD'); #Realizamos nuestra conexion a la BD my $dbh = DBI->connect("DBI:Pg:dbname=mi_bd;host=localhost", "mi_user", "password", {'RaiseError' => 1}); #Limpiamos reglas anteriores en la nuestra Tabla $sql = "DELETE FROM iptables WHERE firewall = '$firewall'"; my $rows = $dbh->do($sql); $num = 1; for ($count = 0; $count < $num; $count++) { %xhash =%{$rules_forward[0][$count]}; $proto = $xhash{protocol}; $bytes = $xhash{bytes}; $s_port = $xhash{s_port}; $packets = $xhash{packets}; $dport = $xhash{dport}; $state = $xhash{state}; $target = $xhash{target}; $intf_in = $xhash{intf_in}; $d_port = $xhash{d_port}; $to_ip = $xhash{to_ip}; $src = $xhash{src}; $intf_out = $xhash{intf_out}; $sport = $xhash{sport}; $dst = $xhash{dst}; $to_port = $xhash{to_port}; $raw = $xhash{raw}; $extended = $xhash{extended}; chop($proto); if ($raw ne ""){ #INSERTO REGLA EN BD @datos = split(/\t/, $raw); $sql = "INSERT INTO iptables(protocol, bytes, s_port, packets, dport, state, target, intf_in, d_port, to_ip, src, intf_out, sport, dst, to_port, rawx,firewall,comentario)VALUES ('$proto', '$bytes', '$s_port', '$packets', '$dport', '$state', '$target', '$intf_in', '$d_port', '$to_ip', '$src', '$intf_out', '$sport','$dst','$to_port','$raw','$firewall','$extended')"; my $rows = $dbh->do($sql); $num++; } } #Imprimo cantidad de reglas de dicho Filtro. print $num."\n"; print "Cadena INPUT por defecto: ",$ipt_obj_input->chain_policy('filter', 'INPUT'), "\n"; @rules_input = $ipt_obj_input->chain_rules('filter', 'INPUT'); $num = 1; for ($count = 0; $count < $num; $count++) { %xhash =%{$rules_input[0][$count]}; $proto = $xhash{protocol}; $bytes = $xhash{bytes}; $s_port = $xhash{s_port}; $packets = $xhash{packets}; $dport = $xhash{dport}; $state = $xhash{state}; $target = $xhash{target}; $intf_in = $xhash{intf_in}; $d_port = $xhash{d_port}; $to_ip = $xhash{to_ip}; $src = $xhash{src}; $intf_out = $xhash{intf_out}; $sport = $xhash{sport}; $dst = $xhash{dst}; $to_port = $xhash{to_port}; $raw = $xhash{raw}; $extended = $xhash{extended}; chop($proto); if ($raw ne ""){ #INSERTO REGLA EN BD @datos = split(/\t/, $raw); $sql = "INSERT INTO iptables(protocol, bytes, s_port, packets, dport, state, target, intf_in, d_port, to_ip, src, intf_out, sport, dst, to_port, rawx,firewall,comentario)VALUES ('$proto', '$bytes', '$s_port', '$packets', '$dport', '$state', '$target', '$intf_in', '$d_port', '$to_ip', '$src', '$intf_out', '$sport','$dst','$to_port','$raw','$firewall','$extended')"; my $rows = $dbh->do($sql); $num++; } } #Imprimo cantidad de reglas de dicho Filtro. print $num."\n"; print "Cadena NAT por defecto: ",$ipt_obj_snat->chain_policy('nat', 'POSTROUTING'), "\n"; @rules_snat = $ipt_obj_snat->chain_rules('nat', 'POSTROUTING'); $num = 1; for ($count = 0; $count < $num; $count++) { %xhash =%{$rules_snat[0][$count]}; $proto = $xhash{protocol}; $bytes = $xhash{bytes}; $s_port = $xhash{s_port}; $packets = $xhash{packets}; $dport = $xhash{dport}; $state = $xhash{state}; $target = $xhash{target}; $intf_in = $xhash{intf_in}; $d_port = $xhash{d_port}; $to_ip = $xhash{to_ip}; $src = $xhash{src}; $intf_out = $xhash{intf_out}; $sport = $xhash{sport}; $dst = $xhash{dst}; $to_port = $xhash{to_port}; $raw = $xhash{raw}; $extended = $xhash{extended}; chop($proto); if ($raw ne ""){ #INSERTO REGLA EN BD @datos = split(/\t/, $raw); $sql = "INSERT INTO iptables(protocol, bytes, s_port, packets, dport, state, target, intf_in, d_port, to_ip, src, intf_out, sport, dst, to_port, rawx,firewall,comentario)VALUES ('$proto', '$bytes', '$s_port', '$packets', '$dport', '$state', '$target', '$intf_in', '$d_port', '$to_ip', '$src', '$intf_out', '$sport','$dst','$to_port','$raw','$firewall','$extended')"; my $rows = $dbh->do($sql); $num++; } } #Imprimo cantidad de reglas de dicho Filtro. print $num."\n"; $dbh->disconnect();
CON EL NOMBRE Script_iptables_bd.pl
Como veran repetimos el ciclo 3 veces las mismas se realizan de esta manera porque
en IPTABLES existen tres tablas: FILTER, NAT Y MANGLE
- FILTER: En esta tabla hay tres cadenas INPUT, OUTPUT y FORWARD.
Adicionalmente, los target como ACCEPT y DROP son otra cosa
- NAT: En esta tabla hay tres cadenas PREROUTING, POSTROUTING, OUTPUT.
Adicionalmente, los target como SNAT y DNAT son otra cosa
- MANGLE: En esta tabla hay tres cadenas PREROUTING, INPUT, OUTPUT, FORWARD y
POSTROUTING.
Cada tabla de Iptables contiene información y se extrae cambiando el siguiente codigo
$ipt_obj->chain_rules($tabla, $cadena);
Ejemplo
$ipt_obj_forward->chain_policy('filter', 'FORWARD');
PASO 5
Una vez guardado el archivo...pues lo corremos.
de la siguiente manera:
#perl Script_iptables_bd.pl
El mismo va a imprimir algo como esto:
Cadena FORWARD por defecto: DROP
1698
Cadena INPUT por defecto: DROP
21
Cadena NAT por defecto: ACCEPT
30
Y listo lo ponemos en el crontab la siguiente linea:
0 7 * * * /home/usuario/perl Script_iptables_bd.pl
claro esta ponemos cada cuanto tiempo se ejecutara!!!
Y listo.
Eso es todo.
Más información:
http://cpan.uwinnipeg.ca/htdocs/IPTables-Parse/IPTables/Parse.html
No hay comentarios:
Publicar un comentario