Monday, October 1, 2012

Iptable a simple and effective firewall for LINUX based machine

Hi All,

When I first encountered iptables It sacred me a lot.  But believe me it is very simple to configure IPtable. In this post I am talking about how to achieve a host firewall using iptable
1. Install iptables. Usually it comes pre-installed unless and until you deselect it while OS installation.
2. In rpm based linux destro, iptables takes configuration from file /etc/sysconfig/iptables

But this does not restrict you to specify your configurations from other locations(in this scenario you have to run iptables-restore command. may in rc.local file)

3. Go for editing iptables file and put your configuration in filter table under INPUT (deals with packet address to this host machine) chain and OUTPUT (packet originating from this machine)chain

Set default policy DROP for all chain

*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]

#allow all connection from loopback address for all protocol
-A INPUT  -i lo  -j ACCEPT
-A OUTPUT  -o lo  -j ACCEPT

#accept all icmp packet
-A INPUT -i eth0 -s nw-address -p icmp --icmp-type echo-request -j ACCEPT
-A INPUT -i eth0 -s nw-address -p icmp --icmp-type echo-reply   -j ACCEPT
-A OUTPUT -o eth0 -d nw-address -p icmp --icmp-type echo-request -j ACCEPT
-A OUTPUT -o eth0 -d nw-address -p icmp --icmp-type echo-reply   -j ACCEPT

#accept ssh and webserver
-A INPUT -i eth0 -s nw-address  -p tcp  --match multiport --dports 22,80,443 -j ACCEPT
-A OUTPUT -o eth0 -d nw-address -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT



Instead for -j you may put DROP or LOG also


Thanks and regards
lalit patel


Monday, July 23, 2012

How to return mutiple objects from a function in java

Hi,
There a number of situation where we do require to return multiple object from a java function.  Let me clear one thing Java as of now does not support this. So how to achieve it ?

1. It returned objects are of same type: make an array and return it.

2. If the returned objects are of different type: wrap it in some other class,make a object and return.

simple and cool

thanks and regards
lalit patel

Thursday, July 5, 2012

Problem arising due to system name difference between file linux /etc/sysconfig/network and /etc/hosts file

Hi All,

Recently I came across a problem where system names differed between /etc/sysconfig/network and /etc/hosts file.

This broke down a SNMP application. After a long hour of headache and debugging I finally traced out. That both the name should be the same.


Thanks and regards

lalit patel

Problem of Jpcap require libpcap.so.0.9 library solved

Hi All,

Jpcap is a java library which uses native C library (libpcap) for packet capturing.
Jpcap require libpcap version to be greater than 0.9. Recently I came across a strange problem. I had Redhat 6 Enterprise  edition linux. It has got libpcap 1.0.0 version installed. But jpcap failed to recognize it. So I made a soft link using following command

ln -s libpcap.so.1.0.0 libpcap.so.0.9

and it worked

thanks and regards
lalit patel




Monday, June 18, 2012

How to send email alert without using sendmail or postfix

Hi All,

Recently I came across a problem where I had to send email alert(with out any attachment) about system health. One way was to configure Sendmail or Postfix. But It was overkill. I had to just send an alert and forget. For that tiny utility ssmtp comes in a very  handy way. First just install ssmtp using rpm of deb package. Thet configure /etc/ssmtp/ssmtp.conf file

  root=user@example.com

  AuthUser=username
  AuthPass=password
  AuthMethod=CRAM-MD5

  mailhub=mail.example.com  //your smtp server

  rewriteDomain=example.com  //your domain name

  hostname=hostname.domain //your machine hostname 
 
 
and bingo you are ready to use ssmtp to send mail
just try following command

echo "Hello world"| ssmtp yourmailid@example.com
 
also you can add these line in cronjob also. 
 

Note:-
1. Make ssmtp.conf permission as 640 aka chmod 640 /etc/ssmtp/ssmtp.conf
2. Make sure ssmtp user has no valid shell. Techincally it should have /sbin/nologin as shell
 
 
 Source:- 
ssmtp guide





Thursday, June 14, 2012

Traceroute using jpcap java libraray

Hi All,
Recently I came across a problem to develop a network traceroute application in JAVA. I tried Jpcap example code but it does not seems working in Window environment giving Destination unreachable(port unreachable) every time even though the normal traceroute through window command prompt is working fine. So I modified the code to make it working. Please change the IPs and interface index number as per your requirement.

How traceroute works:-

First we send a echo request packet with TTL value=1, the destination if reachable will reply with TTL expired. Capture this packet, this will be our first hop. Now increase the hop limit(TTL) by one and resend the packet. Capture the reply packet and so on till we get the echo reply packet from our actual destination.

hopes it will help you.

For any further query  contact me at lkpatel123 at the rate of gmail.com


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpcaputil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URL;
import java.util.Arrays;

import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.EthernetPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;

public class Traceroute {
    public static void main(String[] args) throws Exception{
        /*if(args.length<2){
            System.out.println("Usage: java Traceroute ");
            System.exit(0);
        }*/
           
               InetAddress srcIP=InetAddress.getByName("10.21.34.233");
               InetAddress dstIP=InetAddress.getByName("172.21.3.1");
               int ifIndex=2; //device interface index
       
        //initialize Jpcap
        NetworkInterface device=JpcapCaptor.getDeviceList()[ifIndex];
        JpcapCaptor captor=JpcapCaptor.openDevice(device,2000,false,5000);
       
        /*for(NetworkInterfaceAddress addr:device.addresses)
            if(addr.address instanceof Inet4Address){
                thisIP=addr.address;
                break;
            }
        */
               
              
        //obtain MAC address of the default gateway
        InetAddress pingAddr=InetAddress.getByName("google.co.in");
        captor.setFilter("tcp and dst host "+pingAddr.getHostAddress(),true);
        byte[] gwmac=null;
        while(true){
            new URL("http://google.co.in").openStream().close();
            Packet ping=captor.getPacket();
            if(ping==null){
                System.out.println("cannot obtain MAC address of default gateway.");
                System.exit(-1);
            }else if(Arrays.equals(((EthernetPacket)ping.datalink).dst_mac,device.mac_address))
                    continue;
            gwmac=((EthernetPacket)ping.datalink).dst_mac;
                      break;
        }
       
        //create ICMP packet
        ICMPPacket icmp=new ICMPPacket();
        icmp.type=ICMPPacket.ICMP_ECHO;
        icmp.seq=100;
        icmp.id=0x0300;
        icmp.setIPv4Parameter(0,false,false,false,0,false,false,false,0,0,0,IPPacket.IPPROTO_ICMP,
                srcIP,dstIP);
                byte[] myData=new byte[64];
                for(int i=0;i<64;i++)
                    myData[i]=(byte)00;
        icmp.data=myData;
       
        EthernetPacket ether=new EthernetPacket();
        ether.frametype=EthernetPacket.ETHERTYPE_IP;
        ether.src_mac=device.mac_address;
        ether.dst_mac=gwmac;
        icmp.datalink=ether;
       
        captor.setFilter("icmp and dst host "+srcIP.getHostAddress(),true);
        JpcapSender sender=captor.getJpcapSenderInstance();
        //JpcapSender sender=JpcapSender.openDevice(device);
                icmp.hop_limit=1;
        sender.sendPacket(icmp);
        while(true){
            ICMPPacket p=(ICMPPacket) captor.getPacket();
            //System.out.println("received "+p);
            if(p==null){
                System.out.println("Timeout");
            }else if(p.type==ICMPPacket.ICMP_TIMXCEED){
                                //System.out.println( "Got time exceeded "+  icmp.hop_limit+": "+p.src_ip);               
               
                System.out.println(icmp.hop_limit+": "+p.src_ip);
                icmp.hop_limit++;
            }else if(p.type==ICMPPacket.ICMP_UNREACH){
                                //System.out.println("Got icmp  unreach reply "+  icmp.hop_limit+": "+p.src_ip);
               
                System.out.println(icmp.hop_limit+": "+p.src_ip);
                                sender.close();
                System.exit(0);
            }else if(p.type==ICMPPacket.ICMP_ECHOREPLY){
                                //System.out.println("Got echo  reply "+ icmp.hop_limit+": "+p.src_ip);                             
                System.out.println(icmp.hop_limit+": "+p.src_ip);
                                sender.close();
                System.exit(0);
                                 }
                        else if (p.type==ICMPPacket.ICMP_REDIRECT_TOSHOST){ 
                             
                               // System.out.println("Got redirect reply "+ icmp.hop_limit+": "+p.src_ip);
                                sender.close();
                                System.exit(0);
            }else continue;
                      //  System.out.println("in while loop, about to send " + icmp.toString() + " with hoplimit of " + icmp.hop_limit); 
                  
            sender.sendPacket(icmp);
        }
    }
}


Tuesday, June 12, 2012

Adiscon LogAnalyzer reading all files from a directory

Hi all,

Adiscon LogAnalyzer  is a very good web interface to read,search,sort you log files. It can read logs from files as well as from databases(such as mysql). While reading from log files, you have to specify log files in config file. Recently I came across a scenario where I have read all log files from a directory. Log files are being dynamically generated and appended(by rsyslog).

For that to work I added following code at end of  config.php file


$CFG['DefaultSourceID'] = 'Source1';


$result=array();
$temp_result=array();

$log_dir="/var/log/sitelogs";

function find_all_files($dir)
{
    $temp_result=array();

    $root = scandir($dir);
    foreach($root as $value)
    {
        $temp_result=array();

        if($value === '.' || $value === '..') {continue;}
        if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;}

        $temp_result=find_all_files("$dir/$value");
        if(is_array($temp_result)&&sizeof($temp_result)>0)
        {
        foreach($temp_result as $value)
        {
            $result[]=$value;
        }
        }
    }
    return $result;
}

$files =find_all_files($log_dir);

$i=1;

foreach($files as $file)
{
$file_source_name=substr($file,strlen($log_dir));


$CFG['Sources']['Source'.$i]['ID'] = 'Source'.$i;
$CFG['Sources']['Source'.$i]['Name'] = $file_source_name;
$CFG['Sources']['Source'.$i]['ViewID'] = 'SYSLOG';
$CFG['Sources']['Source'.$i]['SourceType'] = SOURCE_DISK;
$CFG['Sources']['Source'.$i]['LogLineType'] = 'syslog';
$CFG['Sources']['Source'.$i]['DiskFile'] = $file;

$i=$i+1;
}


Telling in simple way, I enlisted all files in the directory in array and pushed that array into the configuration file. please make sure that your log directory is readable by apache web server.