+ Responder Tópico
  1. #1
    Membro Avatar de rocknaveia
    Info Conteúdo e Citações Jogos Mensageiros
    Registro
    Jul 2003
    Mensagens
    7.707
    Verdinhas
    259

    Programa em Java para rastrear IP pelo nome do Host e bloquear acesso

    Fala galera, fiz um programa pra rastrear o IP pelo nome do Host e bloquear no servidor, vou compartilhar, quem quiser melhorar fique a vontade.

    Ele fica agendado pra rodar a cada minuto pelo crontab em outro servidor que tem acesso liberado, e manda os comandos via SSH para o servidor que libera a internet para as estações, lembrando que fiz isso para complementar o bloqueio a sites indesejados.

    Script para criação do BD:

    Código:
    -- phpMyAdmin SQL Dump
    -- version 2.11.8.1deb5+lenny9
    -- http://www.phpmyadmin.net
    --
    -- Servidor: localhost
    -- Tempo de Geração: Jul 27, 2012 as 03:38 PM
    -- Versão do Servidor: 5.0.51
    -- Versão do PHP: 5.2.6-1+lenny9
    
    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
    
    --
    -- Banco de Dados: `iphost`
    --
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `host`
    --
    
    CREATE TABLE IF NOT EXISTS `host` (
      `host` varchar(200) NOT NULL,
      PRIMARY KEY  (`host`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    
    --
    -- Gatilhos `host`
    --
    DROP TRIGGER IF EXISTS `iphost`.`log_host_insert`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_host_insert` AFTER INSERT ON `iphost`.`host`
     FOR EACH ROW BEGIN
    INSERT INTO log_host SET
    id = '',
    data = NOW(),
    acao = 'insert',
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_host_update`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_host_update` AFTER UPDATE ON `iphost`.`host`
     FOR EACH ROW BEGIN
    INSERT INTO log_host SET
    id = '',
    data = NOW(),
    acao = 'update',
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_host_delete`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_host_delete` AFTER DELETE ON `iphost`.`host`
     FOR EACH ROW BEGIN
    INSERT INTO log_host SET
    id = '',
    data = NOW(),
    acao = 'delete',
    host = OLD.host;
    END
    //
    DELIMITER ;
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `iphost`
    --
    
    CREATE TABLE IF NOT EXISTS `iphost` (
      `ip` varchar(15) NOT NULL default '',
      `host` varchar(200) NOT NULL default '',
      PRIMARY KEY  (`ip`,`host`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    
    --
    -- Gatilhos `iphost`
    --
    DROP TRIGGER IF EXISTS `iphost`.`log_iphost_insert`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_iphost_insert` AFTER INSERT ON `iphost`.`iphost`
     FOR EACH ROW BEGIN
    INSERT INTO log_iphost SET
    id = '',
    data = NOW(),
    acao = 'insert',
    ip = NEW.ip,
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_iphost_update`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_iphost_update` AFTER UPDATE ON `iphost`.`iphost`
     FOR EACH ROW BEGIN
    INSERT INTO log_iphost SET
    id = '',
    data = NOW(),
    acao = 'update',
    ip = NEW.ip,
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_iphost_delete`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_iphost_delete` AFTER DELETE ON `iphost`.`iphost`
     FOR EACH ROW BEGIN
    INSERT INTO log_iphost SET
    id = '',
    data = NOW(),
    acao = 'delete',
    ip = OLD.ip,
    host = OLD.host;
    END
    //
    DELIMITER ;
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `log_host`
    --
    
    CREATE TABLE IF NOT EXISTS `log_host` (
      `id` int(11) NOT NULL auto_increment,
      `data` timestamp NOT NULL default CURRENT_TIMESTAMP,
      `acao` varchar(10) default NULL,
      `host` varchar(200) default NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `log_iphost`
    --
    
    CREATE TABLE IF NOT EXISTS `log_iphost` (
      `id` int(11) NOT NULL auto_increment,
      `data` timestamp NOT NULL default CURRENT_TIMESTAMP,
      `acao` varchar(10) default NULL,
      `ip` varchar(15) default NULL,
      `host` varchar(200) default NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2032 ;
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `log_removehost`
    --
    
    CREATE TABLE IF NOT EXISTS `log_removehost` (
      `id` int(11) NOT NULL auto_increment,
      `data` timestamp NOT NULL default CURRENT_TIMESTAMP,
      `acao` varchar(10) default NULL,
      `host` varchar(200) default NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=155 ;
    
    -- --------------------------------------------------------
    
    --
    -- Estrutura da tabela `removehost`
    --
    
    CREATE TABLE IF NOT EXISTS `removehost` (
      `host` varchar(200) NOT NULL,
      PRIMARY KEY  (`host`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    
    --
    -- Gatilhos `removehost`
    --
    DROP TRIGGER IF EXISTS `iphost`.`log_removehost_insert`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_removehost_insert` AFTER INSERT ON `iphost`.`removehost`
     FOR EACH ROW BEGIN
    INSERT INTO log_removehost SET
    id = '',
    data = NOW(),
    acao = 'insert',
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_removehost_update`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_removehost_update` AFTER UPDATE ON `iphost`.`removehost`
     FOR EACH ROW BEGIN
    INSERT INTO log_removehost SET
    id = '',
    data = NOW(),
    acao = 'update',
    host = NEW.host;
    END
    //
    DELIMITER ;
    DROP TRIGGER IF EXISTS `iphost`.`log_removehost_delete`;
    DELIMITER //
    CREATE TRIGGER `iphost`.`log_removehost_delete` AFTER DELETE ON `iphost`.`removehost`
     FOR EACH ROW BEGIN
    INSERT INTO log_removehost SET
    id = '',
    data = NOW(),
    acao = 'delete',
    host = OLD.host;
    END
    //
    DELIMITER ;
    Classe de conexão com o BD:

    Código:
    package bd;
    
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    
    public class Conector {
        public static Connection conectar(){
            Connection con;
           try {
               con = DriverManager.getConnection("jdbc:mysql://ip:3306/bd", "bd", "bd");
               
               return con;
            } catch (SQLException ex) {
                System.out.println(ex);
                System.out.println("Verifique a conexão com o banco de dados");
                return null;
            }
            
    
     
        }
    }
    DAOs

    Código:
    package dao;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import com.mysql.jdbc.Connection;
    
    import bd.Conector;
    
    public class DAOHost {
    
    	public static ArrayList<String> getHosts() {
    		try {
    
    			ArrayList<String> hosts = new ArrayList<String>();
    			Connection con = (Connection) Conector.conectar();
    			Statement stm = con.createStatement();
    			String sql = "SELECT `host` FROM host ;";
    			ResultSet rs = stm.executeQuery(sql);
    			
    			while (rs.next()) {
    				hosts.add(String.valueOf(rs.getString(1)));
    			}
    
    			return hosts;
    
    		} catch (SQLException ex) {
    			System.out.println(ex);
    			return null;
    		}
    
    	}
    	
    	public static void removeHost(String host){
    		
    		
    		try {
    			Connection con = (Connection) Conector.conectar();
    			Statement stm = con.createStatement();
    			String sql = "DELETE FROM host WHERE host = '"+host+"';";
    			stm.executeUpdate(sql);
    			
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		System.out.println("Host removido "+host);
    		
    		
    	}
    	
    }
    Código:
    package dao;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import com.mysql.jdbc.Connection;
    
    import bd.Conector;
    
    public class DAOIpHost {
    
    	public static void gravaIpHost(String ip, String host) {
    
    		Statement stmt = null;
    
    		try {
    			stmt = Conector.conectar().createStatement();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		String strSql = "INSERT INTO  `iphost`.`iphost` (`ip` ,`host`)VALUES ('"
    				+ ip + "','" + host + "');";
    
    		try {
    			stmt.executeUpdate(strSql);
    		} catch (SQLException e) {
    
    			e.printStackTrace();
    		}
    
    	}
    
    	public static boolean getInfo(String comparar) {
    
    		Statement stmt = null;
    
    		try {
    			stmt = Conector.conectar().createStatement();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		String strSql = "SELECT DISTINCT ip FROM iphost WHERE ip ='" + comparar
    				+ "'";
    
    		ResultSet rs = null;
    
    		try {
    			rs = stmt.executeQuery(strSql);
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		try {
    			return rs.next();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
    
    	public static boolean getInfoHost(String comparar) {
    
    		Statement stmt = null;
    
    		try {
    			stmt = Conector.conectar().createStatement();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		String strSql = "SELECT DISTINCT host FROM iphost WHERE host ='"
    				+ comparar + "'";
    
    		ResultSet rs = null;
    
    		try {
    			rs = stmt.executeQuery(strSql);
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		try {
    			return rs.next();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		return false;
    	}
    
    	public static ArrayList<String> getIps(String host) {
    		try {
    
    			ArrayList<String> ips = new ArrayList<String>();
    			Connection con = (Connection) Conector.conectar();
    			Statement stm = con.createStatement();
    			String sql = "SELECT `ip` FROM iphost where host = '" + host
    					+ "' ;";
    			ResultSet rs = stm.executeQuery(sql);
    
    			while (rs.next()) {
    				ips.add(String.valueOf(rs.getString(1)));
    			}
    
    			return ips;
    
    		} catch (SQLException ex) {
    			System.out.println(ex);
    			return null;
    		}
    	}
    
    	public static void removeIpHost(String host) {
    
    		Statement stmt = null;
    
    		try {
    			stmt = Conector.conectar().createStatement();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		String strSql = "DELETE FROM iphost WHERE `host` = '" + host + "';";
    
    		try {
    			stmt.executeUpdate(strSql);
    		} catch (SQLException e) {
    
    			e.printStackTrace();
    		}
    
    	}
    
    }
    Código:
    package dao;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import bd.Conector;
    
    import com.mysql.jdbc.Connection;
    
    public class DAORemoveHost {
    
    	public static ArrayList<String> getHosts() {
    		try {
    
    			ArrayList<String> hosts = new ArrayList<String>();
    			Connection con = (Connection) Conector.conectar();
    			Statement stm = con.createStatement();
    			String sql = "SELECT `host` FROM removehost ;";
    			ResultSet rs = stm.executeQuery(sql);
    
    			while (rs.next()) {
    				hosts.add(String.valueOf(rs.getString(1)));
    			}
    
    			return hosts;
    
    		} catch (SQLException ex) {
    			System.out.println(ex);
    			return null;
    		}
    
    	}
    
    	public static void removeHost(String host){
    		
    		Statement stmt = null;
    
    		try {
    			stmt = Conector.conectar().createStatement();
    		} catch (SQLException e1) {
    			e1.printStackTrace();
    		}
    
    		String strSql = "DELETE FROM removehost WHERE `host` = '" + host + "';";
    
    		try {
    			stmt.executeUpdate(strSql);
    		} catch (SQLException e) {
    
    			e.printStackTrace();
    		}
    		
    	}
    	
    }
    Classes

    Código:
    package pegaIp;
    
    import java.util.ArrayList;
    
    import dao.DAOHost;
    import dao.DAOIpHost;
    import dao.DAORemoveHost;
    
    public class Ip {
    
    	public static void bloqueiaIp() {
    
    		ArrayList<String> lista = DAOHost.getHosts();
    		String host = "", ip = "";
    
    		for (int i = 0; i < lista.size(); i++) {
    
    			host = lista.get(i).toString();
    
    			try {
    				ip = RetornaIp.getIp(host);
    
    				if (ip.equals("")) {
    					System.out.println("Host inválido " + ip + " " + host);
    					DAOHost.removeHost(host);
    				} else if (DAOIpHost.getInfo(ip)) {
    					System.out.println("IP já cadastrado " + ip + " " + host);
    
    				} else {
    					System.out.println("Adicionando a lista: "
    							+ RetornaIp.getIp(host) + " " + host);
    
    					DAOIpHost.gravaIpHost(ip, host);
    					IpTables.gravaIptables(ip);
    				}
    			} catch (Throwable e) {
    
    				e.printStackTrace();
    			}
    			;
    		}
    
    	}
    
    	public static void liberaIp() {
    
    		ArrayList<String> removeLista = DAORemoveHost.getHosts();
    		String removehost = "";
    
    		for (int i = 0; i < removeLista.size(); i++) {
    
    			removehost = removeLista.get(i).toString();
    
    			if (DAOIpHost.getInfoHost(removehost)) {
    				ArrayList<String> listaIP = DAOIpHost.getIps(removehost);
    				for (int r = 0; r < listaIP.size(); r++) {
    					IpTables.removeIptables(listaIP.get(r));
    					System.out.println("Desbloqueando IP: " + listaIP.get(r));
    
    				}
    				
    				 DAOHost.removeHost(removehost);
    				 DAOIpHost.removeIpHost(removehost);
    				 DAORemoveHost.removeHost(removehost);
    				 
    
    				System.out.println("Apagando das tabelas " + removehost);
    
    			} else {
    				DAORemoveHost.removeHost(removehost);
    				System.out.println("Host não existe, remover " + removehost);
    			}
    		}
    
    	}
    
    }
    Código:
    package pegaIp;
    
    import java.io.IOException;
    
    public class IpTables {
    
    	public static void gravaIptables(String ip) {
    
    		Runtime run = Runtime.getRuntime();
    
    		String command1 = "ssh [email protected] iptables -A FORWARD -d " + ip + " -j DROP";
    		String command2 = "ssh [email protected] iptables -A INPUT -d " + ip + " -j DROP";
    		String command3 = "ssh [email protected] iptables -A OUTPUT -d " + ip + " -j DROP";
    
    		try {
    			run.exec(command1);
    			run.exec(command2);
    			run.exec(command3);
    		} catch (IOException e) {
    
    			e.printStackTrace();
    		}
    
    	}
    	
    	public static void removeIptables(String ip){
    		
    		Runtime run = Runtime.getRuntime();
    
    		String command1 = "ssh [email protected] iptables -D FORWARD -d " + ip + " -j DROP";
    		String command2 = "ssh [email protected] iptables -D INPUT -d " + ip + " -j DROP";
    		String command3 = "ssh [email protected] iptables -D OUTPUT -d " + ip + " -j DROP";
    
    		try {
    			run.exec(command1);
    			run.exec(command2);
    			run.exec(command3);
    		} catch (IOException e) {
    
    			e.printStackTrace();
    		}
    		
    	}
    
    }
    Código:
    package pegaIp;
    
    import java.net.InetAddress;
    
    public class RetornaIp {
    
    	public static String getIp(String host) {
    
    		InetAddress ia = null;
    		String ip = "";
    		try {
    			ia = InetAddress.getByName(host);
    			ip = ia.getHostAddress().toString();
    		} catch (Exception e) {
    
    			return ip;
    		}
    
    		return ip;
    	}
    
    }
    Código:
    package pegaIp;
    
    public class Master {
    
    	public static void main(String[] args) {
    
    		Ip.liberaIp();
    		Ip.bloqueiaIp();
    
    	}
    }
    Última edição por rocknaveia : 27-07-2012 às 15:40

  2. # Publicidade
    Publicidade

  3. #2
    Membro
    Info Conteúdo e Citações Jogos Mensageiros
    Registro
    Feb 2007
    Mensagens
    232
    Verdinhas
    7

    Bem legal hein... nao testei, mas ia dar a idéia de vc colocar no github

  4. #3
    Membro Avatar de rocknaveia
    Autor do tópico
    Info Conteúdo e Citações Jogos Mensageiros
    Registro
    Jul 2003
    Mensagens
    7.707
    Verdinhas
    259

    Do jeito que fiz da pra adaptar pra fazer varias outras coisas, afinal vc pode mandar qualquer tipo de comando pro servidor, fica meio que assimétrico, vc faz o esquema pra receber os parametros no BD, igual fiz com o host, e a cada minuto ele vai la cata e processa.

    Acho que ficou bem simples, qualquer um com o básico em programação igual eu consegue usar a ideia.

    Vou ver como funfa pra por no github.

    Abraço.

+ Responder Tópico Ir para o Fórum

Assuntos do tópico

Compartilhar

Permissões