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.




Wednesday, June 6, 2012

Java Capture packet for a fixed interval using Jnetpcap library

Hi,

Jnetpcap is java library built using libpcap/winpcap. I provides libpcap functionalities using JNI. Sample program are available across internet who capture a certain number of packet. Here is java program who capture packet for certain predefined time interval.


/**
 * Copyright (C) 2008 Sly Technologies, Inc. This library is free software; you
 * can redistribute it and/or modify it under the terms of the GNU Lesser
 * General Public License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version. This
 * library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details. You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package jnetpcap;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.jnetpcap.JBufferHandler;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapDumper;
import org.jnetpcap.PcapHeader;
import org.jnetpcap.PcapIf;
import org.jnetpcap.nio.JBuffer;
import org.jnetpcap.packet.PcapPacketHandler; 
import java.util.Date;
import org.jnetpcap.packet.PcapPacket; 
import org.jnetpcap.protocol.JProtocol;
/**
 * This example is uses pcap library to capture live packets and dump them to  console.Similar progam can be written to dump the packet to a file. Packets are captured for a certain amount of time and dumped to cosole. After the time interval expires pcap closes
 *
 * @author Mark Bednarczyk
 * @author Sly Technologies, Inc.
 */
public class CapturePacketForCertainTimeInterval {

     public static final int CAPTURE_INTERVAL = 60 * 1000; // 60 seconds in
                                                      

    public static void main(String[] args) {
        List alldevs = new ArrayList(); // Will be filled with
        // NICs
        StringBuilder errbuf = new StringBuilder(); // For any error msgs

        /***************************************************************************
         * First get a list of devices on this system
         **************************************************************************/
        int r = Pcap.findAllDevs(alldevs, errbuf);
        if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
            System.err.printf("Can't read list of devices, error is %s", errbuf
                    .toString());
            return;
        }
        PcapIf device = alldevs.get(0); // We know we have at least 1 device

        /***************************************************************************
         * Second we open up the selected device
         **************************************************************************/
        int snaplen = 64 * 1024; // Capture all packets, no truncation
        int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
        int timeout = 10*1000; // No timeout, non-interactive traffic
        Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout,
                errbuf);
        if (pcap == null) {
            System.err.printf("Error while opening device for capture: "
                    + errbuf.toString());
            return;
        }

                       final long interval = System.currentTimeMillis() + CAPTURE_INTERVAL;
               
                System.out.printf("Dump packet for "+(CAPTURE_INTERVAL/1000)+" Secs\n");

                /***************************************************************************
                 * third we create a packet hander which receive packets and break the pcap to end capture after predefined time interval                                 **************************************************************************/
                                            
                                PcapPacketHandler jpacketHandler = new PcapPacketHandler() { 
  
                                public void nextPacket(PcapPacket packet, Pcap pcap) { 
  
                                System.out.printf("Received packet at %s caplen=%-4d len=%-4d\n", 
                                    new Date(packet.getCaptureHeader().timestampInMillis()),  
                                    packet.getCaptureHeader().caplen(),  // Length actually captured 
                                    packet.getCaptureHeader().wirelen() // Original length  
                                                              
                                    );
                               
                                  if (System.currentTimeMillis() > interval) {
                            pcap.breakloop();
                                                        pcap.close();
                                                       
                        }
                
                                     } 
                                }; 

                /***************************************************************************
                 * Fourth we enter the loop.                                  **************************************************************************/
                  pcap.dispatch(Pcap.LOOP_INFINITE,JProtocol.IP4_ID, jpacketHandler,  pcap); 
                             
                             
                                                            
                //dumper.close(); // close out the dumper and flush any unwritten packets
            }
      
}


Note:- pcap.dispatch function may vary depending on OS implementation.  I have run this code on Window XP SP3 using Netbean IDE

please feel free to contact me for any doubt. thanks



Monday, June 4, 2012

Search a word in pdf file in Linux using shell script and poppler library

Hi all,
back after long time

Here is a very simple shell script to search in pdf files in linux environment.
Script is orginally written by  Karsten Wade. I have modified it little bit to suit our need. Please free to contact me at lkpatel123@gmail.com.

Note that for this script to run you need poppler library to be installed.


#!/bin/bash
#
# Copyright 2009 Karsten Wade
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see .

#echo -en "String to search for in all PDF files? "
#read STRING

if [ $# -ne 2 ] ; then
 echo "please provide valid argument"
 echo "1: dir 2:string to be searched"
 exit
fi

shopt -s nullglob

#iterate over dir

src=$1


COUNT=0


#enable for loops over items with spaces in their name

IFS=$'\n'

for dir in `find "$src/" -type d -print`
do
  #if [ -d "$src/$dir" ]; then
    #yay, we get matches!
   FILES[$COUNT]=$dir"/*.pdf"
   COUNT=$((COUNT+1))
  #fi
done

COUNT=0

STRING=$2
for i in "${FILES[@]}"
do
for i in ${FILES[$COUNT]}
        do
        ch=`pdftotext "$i" - | grep -i $STRING`
        if [ -n "$ch" ]; then
        echo $i
        fi
        done

COUNT=$((COUNT+1))
done